From 1f4cfad6562914cbdb11107bc8f7e8174a8a9906 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Wed, 4 Nov 2026 20:48:40 +0800 Subject: [PATCH 001/103] fix(agent): close input admission and drain work after cancellation failures --- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- docs/event-producer-consumer.md | 22 +- docs/event-producer-consumer.zh.md | 22 +- docs/subsystems/core.md | 7 +- docs/subsystems/core.zh.md | 7 +- packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 24 +- packages/core/agent-loop/src/index.ts | 9 +- packages/core/agent-loop/tests/cancel.spec.ts | 12 +- .../tests/fixtures/serial-created.mjs | 37 +- .../agent-loop/tests/input-lifecycle.spec.ts | 151 ++++++ .../agent-loop/tests/request-freeze.spec.ts | 6 +- packages/core/agent/README.i18n.yaml | 4 +- packages/core/agent/README.md | 2 +- packages/core/agent/README.zh.md | 2 +- packages/core/agent/src/closed-error.ts | 15 + packages/core/agent/src/index.ts | 1 + packages/core/agent/src/runtime-types.ts | 7 +- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 4 +- scripts/smoke-python-runtime.py | 1 + .../advanced/result.json | 460 ++++++++++++++++-- .../advanced/session.1.v4.jsonl | 24 +- .../advanced/session.2.v4.jsonl | 24 +- snapshots/sdk/serial-created/session.v4.jsonl | 21 +- 31 files changed, 762 insertions(+), 124 deletions(-) create mode 100644 packages/core/agent-loop/tests/input-lifecycle.spec.ts create mode 100644 packages/core/agent/src/closed-error.ts diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index 19453e15a9..83a62a5480 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -21,8 +21,8 @@ en: 20ef882e44b06a10 zh: c10c3934ed5570e9 /deepseek-harness-architecture/events: - en: ddebac7cfd41ec73 - zh: 51e6d0866a9e7839 + en: 9a7297518f6b7bdf + zh: 883364ea3f1ac82b /deepseek-harness-architecture/turn-flow: en: 1a79a70b62c04cdb zh: c86d765e21430405 diff --git a/docs/architecture.md b/docs/architecture.md index 446c50e5bd..95eeab1b42 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,7 @@ Events provide extension points in three domains. Subagent Activations own runtime tree membership. -AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; unload retains resources through teardown ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). +AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown closes input admission, cancels and waits for admitted work despite queue-cleanup failures, then releases resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). [Event producers and consumers](event-producer-consumer.md). diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 275e1c863d..936a6493ff 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -76,7 +76,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 Subagent Activation 拥有运行时树成员关系。 -AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;卸载在 teardown 期间保留所需资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭先停止接收输入,在队列清理失败时仍取消并等待已接纳工作,然后释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 [事件生产者与消费者](event-producer-consumer.zh.md)。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e9172cc37..a32683e672 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 326beb8853..ff27d132ae 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,17 +14,17 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:399`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:290`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:299`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:328`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:336`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:317`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:350`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:389`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:309`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:417`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 40264ec898..7b8503cb1a 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -78,6 +78,7 @@ interface Agent { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -97,7 +98,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -112,6 +113,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -119,6 +121,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -128,6 +131,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -138,6 +142,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index ff1d3b579e..9f0bf51061 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -82,6 +82,7 @@ interface Agent { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -101,7 +102,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -116,6 +117,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -123,6 +125,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -132,6 +135,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -142,6 +146,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index 08e35ca2a9..9c73797cbb 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: ec2bf804bd1a5439 zh: 316e767507e859ef /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: e2cb7b6101f20425 - zh: a056c43886207083 + en: e66e878db8193219 + zh: 11a79267958b2f51 /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: 3b48a480036bd5df zh: 28cea2036b0dccee diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index 03fc5b2e16..c021ad2513 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. The caller Context owns the transaction and live handle; delegation services bind their runtime relationships during setup. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. +The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. New input is rejected when teardown begins; queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles. ### Persistence integration diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 977911bbbe..394130f0c4 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。调用方 Context 拥有事务和存活句柄;委派服务在 setup 期间绑定自己的运行时关系。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。 +loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。teardown 开始后拒绝新输入;清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。 ### 持久化集成 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index c4daa50c47..c23cc401e3 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -18,7 +18,7 @@ import type { PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { LlmError, @@ -141,6 +141,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, projections: LoopProjections, lastTurn: number, + private readonly lifetimeSignal: AbortSignal, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) @@ -168,6 +169,7 @@ export class ReactLoopAgent implements Agent { } send(message: UserMessage, target: InboxTarget, wakeup: boolean): void { + this.assertOpen() // Waking input cannot join an aborted activity, so it starts the next turn. // Captured before the insertion so a reentrant cancel from a splice observer cannot reclassify it. const wakingAfterAbort = wakeup && this.phase.kind !== 'idle' && this.phase.abort.signal.aborted @@ -189,14 +191,19 @@ export class ReactLoopAgent implements Agent { } cancel(cause: AgentCancelCause, options: CancelOptions = {}): void { - if (!options.keepInbox) { - this.inbox.clear() - if (this.phase.kind !== 'idle') this.phase.wakeRequested = false + try { + if (!options.keepInbox) this.inbox.clear() + } finally { + // Queue persistence must not prevent cancellation of admitted work. + if (this.phase.kind !== 'idle') { + if (!options.keepInbox) this.phase.wakeRequested = false + this.phase.abort.abort(cause) + } } - if (this.phase.kind !== 'idle') this.phase.abort.abort(cause) } runMaintenance(job: (signal: AbortSignal) => Promise): Promise { + this.assertOpen() if (this.phase.kind !== 'idle') throw new Error(`agent "${this.id}" already has active work`) const done = Promise.withResolvers() const maintenance: Phase = { @@ -228,6 +235,7 @@ export class ReactLoopAgent implements Agent { * the inbox insertion so a reentrant cancel cannot reclassify it. */ private wakeDriver(wakeAfterAbort = false): void { + if (this.lifetimeSignal.aborted) return if (this.phase.kind !== 'idle') { // Maintenance and aborted drivers cannot deliver the wake: latch it for // replay at convergence. Live drivers claim queued work themselves; @@ -257,6 +265,12 @@ export class ReactLoopAgent implements Agent { } while (activity !== this.activityDone) } + private assertOpen(): void { + if (this.lifetimeSignal.aborted) { + throw new AgentClosedError(this.id, { cause: this.lifetimeSignal.reason }) + } + } + /** Report one failure at its live boundary, then preserve it for driver containment. */ private throwError(error: unknown): never { const turn = this.phase.kind === 'running' ? this.phase.turn : this.phase.lastTurn diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 22b3192588..a0b02d4eee 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -514,7 +514,12 @@ export class AgentLoop extends Service implements AgentFactory { if (machine === undefined) await machineReady.promise /* v8 ignore next -- setup failure untracks this disposer before resolving without a machine. */ if (machine !== undefined) { - machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + try { + machine.cancel({ kind: 'disposed' }, { keepInbox: !ready }) + } catch (error: unknown) { + failures.push(error) + } + // A failed queue write must not release resources underneath work. await machine.whenIdle() } } catch (error: unknown) { @@ -573,6 +578,7 @@ export class AgentLoop extends Service implements AgentFactory { loopCtx, id, agentOptions, session, projections, lastTurn, + abort.signal, ) machineReady.resolve() // Adopt the scope on its original fiber so it cannot unload before teardown. @@ -636,6 +642,7 @@ export class AgentLoop extends Service implements AgentFactory { await loopCtx.agents.announce(agent, source, abort.signal) assertLive() ready = true + callerSignal?.removeEventListener('abort', onCallerAbort) return { agent, dispose } } catch (error: unknown) { // Failed initialization must not release queued input into a new turn. diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index c702b64e89..2ca5eb0299 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -16,7 +16,7 @@ import SessionStore, { Session, SessionId, SessionLogOffset, TurnEndReason } fro import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import AgentRegistry, { type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { AgentClosedError, type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts' @@ -319,14 +319,12 @@ describe('Agent.cancel()', () => { }) const agent = handle.agent + const streaming = Promise.withResolvers() + ctx.on('agent/assistant-stream', ({ frame }) => { if (frame.type === 'chunk') streaming.resolve(undefined) }) send(agent, 'active') - await new Promise(resolve => setTimeout(resolve, 30)) - - // Dispose cancels with `{ kind: 'disposed' }`; a wake landing in the - // abort-to-idle window must not latch, so `whenIdle()` does not wait on - // a model turn over the session being torn down. + await streaming.promise const disposal = handle.dispose() - setTimeout(() => { send(agent, 'late wake') }, 10) + expect(() =>{ send(agent, 'late wake') }).toThrow(AgentClosedError) await disposal expect(adapter.requests).toHaveLength(1) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 8cc624caae..138fd7d4b6 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,7 +6,42 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx) { +export function apply(ctx, config = {}) { + const checkedCancellation = new WeakSet() + ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { + if (checkedCancellation.has(agent) + || (config.checkRootCancellation === false && agent.session.header.origin !== 'subagent')) return next() + checkedCancellation.add(agent) + const pending = { + id: randomUUID(), role: 'user', + content: [{ type: 'text', text: 'Cancellation checkpoint probe.' }], + source: { kind: `plugin:${name}` }, + } + agent.inject(pending) + const failure = new Error('fixture queue-clear refusal') + const stopRejecting = ctx.on('internal/dispatch', (_mode, eventName, args) => { + if (eventName !== 'session/event') return + const [session, event] = args + if (session === agent.session && event.type === 'agent/inbox/spliced' + && event.data.outcome === 'canceled' && (event.data.removedCount ?? 0) > 0) throw failure + }) + try { + try { agent.cancel({ kind: 'user' }) } + catch (error) { if (error !== failure) throw error } + } finally { + stopRejecting() + } + if (!signal.aborted) throw new Error('queue-clear failure prevented cancellation') + agent.inbox.remove(pending.id) + for (const message of messages) { + const ordinary = message.source.kind === 'user' + const restored = message.source.kind === `plugin:${name}` + ? { ...message, content: [{ type: 'text', text: message.content[0].text + ' Queue-clear failures still cancel active work.' }] } + : message + agent.send(restored, ordinary ? 'next-turn' : 'next-step', ordinary) + } + return next() + }) const ready = new WeakSet() ctx.on('agent/created', async ({ agent }) => { await setImmediate() diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts new file mode 100644 index 0000000000..2e87517e1f --- /dev/null +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -0,0 +1,151 @@ +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import { afterEach, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import AgentRegistry, { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' +import * as CheckpointPolicy from '@deepseek-ai/dsh-session-checkpoint-policy' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import { MockAdapter, textResponse } from './mock-adapter.ts' + +const fixtures: { ctx: Context; agent?: Agent; root: string }[] = [] +afterEach(async () => { + for (const fixture of fixtures.splice(0)) { + try { + fixture.agent?.cancel({ kind: 'disposed' }, { keepInbox: true }) + await fixture.agent?.whenIdle() + await fixture.ctx.fiber.dispose() + } finally { + await rm(fixture.root, { recursive: true, force: true }) + } + } +}) + +const input = (text: string) => createUserMessage({ content: [{ type: 'text' as const, text }], source: { kind: 'user' as const } }) + +async function harness() { + const ctx = new Context() + const root = await mkdtemp(join(tmpdir(), 'dsh-input-atomicity-')) + const fixture: { ctx: Context; agent?: Agent; root: string } = { ctx, root } + fixtures.push(fixture) + await ctx.plugin(LlmRuntime) + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(SystemPrompt) + await ctx.plugin(ToolRuntime) + await ctx.plugin(NativeToolExecutor) + await ctx.plugin(AgentRegistry) + await ctx.plugin(JsonlSessionPersistence, { root, compression: 'none' }) + await ctx.plugin(CheckpointPolicy) + await ctx.plugin(AgentLoop, { agents: [] }) + const adapter = new MockAdapter(Array.from({ length: 5 }, () => textResponse('ok'))) + ctx.llm.registerAdapter(['mock'], adapter) + const handle = await ctx.agents.create({ sessionId: SessionId('diagnostic'), agentOptions: { provider: 'mock', model: 'mock' } }) + fixture.agent = handle.agent + return { ctx, root, adapter, handle, agent: handle.agent } +} + + +it('cancellation still aborts the running request when queue clearing fails', async () => { + const { ctx, agent } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const hold = ctx.on('agent/pre-step', async ({ signal }, next) => { entered.resolve(signal); await release.promise; return next() }) + let stopRejecting = () => {} + try { + agent.followup(input('running')) + const signal = await entered.promise + agent.inject(input('steering')) + const queued = input('queued') + agent.followup(queued) + stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn' + && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure') + }) + expect(() =>{ agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') + expect(signal.aborted).toBe(true) + } finally { + stopRejecting() + hold() + agent.cancel({ kind: 'disposed' }, { keepInbox: true }) + release.resolve(undefined) + await agent.whenIdle() + } +}) + + +it('an Agent still in the registry rejects new input while its owner is closing', async () => { + const { ctx, agent, handle } = await harness() + const release = Promise.withResolvers() + const aborted = Promise.withResolvers() + const work = agent.runMaintenance(async (signal) => { + signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) + await release.promise + }) + const closing = handle.dispose() + try { + await aborted.promise + expect(ctx.agents.get(agent.id)).toBe(agent) + const message = input('during closing') + for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {})]) { + expect(submit).toThrow(AgentClosedError) + } + const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) + expect(pending).toBe(false) + } finally { + release.resolve(undefined) + await work + await closing + } +}) + + + +it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { + const { ctx, agent, handle } = await harness() + const release = Promise.withResolvers() + const waiting = Promise.withResolvers<'waiting'>() + const disposed = Promise.withResolvers<'disposed'>() + let scopeDisposed = false + agent.ctx.effect(() => () => { scopeDisposed = true; disposed.resolve('disposed') }) + const work = agent.runMaintenance(async () => { + await release.promise + agent.session.append('request/context', { provider: 'mock', model: 'mock' }) + }) + agent.inject(input('pending')) + const stopRejecting = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (session === agent.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) { + throw new Error('queue clear failed') + } + }) + const whenIdle = agent.whenIdle.bind(agent) + const spy = vi.spyOn(agent, 'whenIdle').mockImplementation(() => { waiting.resolve('waiting'); return whenIdle() }) + const closing = handle.dispose().then(() => undefined, (error: unknown) => error) + try { + expect(await Promise.race([waiting.promise, disposed.promise])).toBe('waiting') + expect(scopeDisposed).toBe(false) + expect(ctx.sessions.get(agent.id)).toBe(agent.session) + release.resolve(undefined) + await work + expect(await closing).toEqual(new Error('queue clear failed')) + expect(scopeDisposed).toBe(true) + expect(agent.session.snapshotEvents().at(-1)?.type).toBe('request/context') + } finally { + stopRejecting() + spy.mockRestore() + release.resolve(undefined) + await work + await closing + } +}) diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index 8ed1c4d138..f4ef29eea3 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -79,7 +79,8 @@ describe('loop-owned request freezing', () => { const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition) const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition) const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { agent.cancel({ kind: 'disposed' }) await agent.whenIdle() @@ -129,7 +130,8 @@ describe('loop-owned request freezing', () => { expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1) expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1) const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, + new AbortController().signal) cleanups.push(async () => { resumed.cancel({ kind: 'disposed' }) await resumed.whenIdle() diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 358d56ae02..df3e29c8a9 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -24,8 +24,8 @@ en: 85b0ff72a187110f zh: 3f61c1568d27b8bc /deepseek-ai-dsh-agent/use-this-package/drive-an-agent-s-conversation: - en: 71e258897e2e7d73 - zh: abf0991012faa17e + en: ff2b530bb20bcfe2 + zh: 4f9024c4881a4ba5 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: en: 2594a1e02adea801 zh: cae8860369728efb diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index c84ac3d237..9772578fcc 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -55,7 +55,7 @@ For scoped switch notices, call `installModelSelection(agentCtx)` from `dsh-agen ### Drive an agent's conversation -The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. +The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. Disposal rejects new input and maintenance with `AgentClosedError` before mutation. A queue-write failure during cancellation still aborts active work and propagates to the caller. ```text handle.agent.followup({ diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index a2fae55b56..b5b2af52d4 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -55,7 +55,7 @@ await handle.dispose() // stops the loop, unregisters, removes the session, un ### 驱动 agent 的对话 -句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。 +句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。释放开始后,新输入和维护任务会在修改状态前抛出 `AgentClosedError`。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。 ```text handle.agent.followup({ diff --git a/packages/core/agent/src/closed-error.ts b/packages/core/agent/src/closed-error.ts new file mode 100644 index 0000000000..abcb335320 --- /dev/null +++ b/packages/core/agent/src/closed-error.ts @@ -0,0 +1,15 @@ +/** Rejection of new work after an Agent starts closing. @module @deepseek-ai/dsh-agent/closed-error */ + +import type { SessionId } from '@deepseek-ai/dsh-session' + +/** An Agent has stopped accepting new input and maintenance work. */ +export class AgentClosedError extends Error { + /** + * @param agentId - closing Agent identity. + * @param options - original lifecycle cancellation, when available. + */ + constructor(readonly agentId: SessionId, options?: ErrorOptions) { + super(`agent "${agentId}" is closing`, options) + this.name = 'AgentClosedError' + } +} diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 374be30180..35fbdd6b1d 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -19,6 +19,7 @@ import type { AgentOptions, SessionStartSource } from './runtime-types.ts' import { turnBoundaryProjectionDefinition } from './projection.ts' export * from './runtime-types.ts' +export { AgentClosedError } from './closed-error.ts' export * from './types.ts' export { AgentModel, modelSelectionProjectionDefinition, installModelSelection } from './model-selection.ts' export type { ModelSelectionProjectionState } from './model-selection.ts' diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 2b1698e39c..aa5efe6d0a 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -206,6 +206,7 @@ declare module './types.ts' { * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no * active activity, cancellation is a no-op and does not arm later work. + * Queue-write failures still abort the activity and propagate to the caller. * @param cause - the stable caller intent carried by the active operation signal. * @param options - cancellation options; `keepInbox` preserves pending work. */ @@ -225,7 +226,7 @@ declare module './types.ts' { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws synchronously when turn-driving or another maintenance task already owns the agent. + * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -240,6 +241,7 @@ declare module './types.ts' { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. + * @throws AgentClosedError after disposal begins; no input is inserted. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -247,6 +249,7 @@ declare module './types.ts' { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ followup(message: UserMessage): void @@ -256,6 +259,7 @@ declare module './types.ts' { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ steer(message: UserMessage): void @@ -266,6 +270,7 @@ declare module './types.ts' { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. + * @throws AgentClosedError after disposal begins; no input is inserted. */ inject(message: UserMessage): void } diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4ff564cb25..3b160b2782 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 9543250098033347 - zh: 3721af3e31409a32 + en: 152d969b7214b4cd + zh: 2ba2a43599b009d9 /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index b8fd869989..c3da369bed 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. An Agent that has begun closing ends the local settlement observer rather than retrying maintenance admission. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index e0f8f35bda..ed72da6c0a 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,本地结算观察器会结束,不再重试维护准入。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index db6f04b019..e1b0bc6e68 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -11,6 +11,7 @@ import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -991,7 +992,8 @@ export class SubagentManager { done = this.close(activation, () => this.finishDisposal(activation, false)) return Promise.resolve() }) - } catch (_error: unknown) { + } catch (error: unknown) { + if (error instanceof AgentClosedError) return Promise.resolve('closed') // Another activity already owns the Agent's idle phase. return Promise.resolve('retry') } diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index 311fa10ff6..49dca3772a 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -1787,6 +1787,7 @@ def smoke_sdk_snapshot_mode( {"insert": [{ "id": "serial-created-fixture", "name": str(Path(__file__).resolve().parents[1] / "packages/core/agent-loop/tests/fixtures/serial-created.mjs"), + "config": {"checkRootCancellation": False}, }]}, ]) with DeepSeekHarness( diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index 47c767ccd9..68401cbcf2 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -2880,11 +2880,205 @@ "payload": { "sessionId": "{{child-1}}", "event": { - "type": "step/start", + "type": "agent/inbox/spliced", "seq": 9, "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Cancellation checkpoint probe." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 10, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [], + "outcome": "canceled" + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 11, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 12, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "inserted": [ + { + "content": [ + { + "type": "text", + "text": "Reply with exactly DIRECT_CHILD_OK and nothing else." + }, + { + "type": "text", + "text": "Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message." + } + ], + "source": { + "kind": "user" + }, + "role": "user", + "id": "{{messageId}}" + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "turn/end", + "seq": 13, + "time": 0, "data": { "turn": 1, + "reason": { + "kind": "aborted", + "reason": { + "kind": "user" + } + } + } + } + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-1}}", + "status": "idle" + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-1}}", + "status": "running" + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "turn/start", + "seq": 14, + "time": 0, + "data": { + "turn": 2 + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 15, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 16, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-1}}", + "event": { + "type": "step/start", + "seq": 17, + "time": 0, + "data": { + "turn": 2, "step": 1 } } @@ -2896,10 +3090,10 @@ "sessionId": "{{child-1}}", "event": { "type": "system/message", - "seq": 10, + "seq": 18, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "system", @@ -2925,7 +3119,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 11, + "seq": 19, "time": 0, "data": { "id": "{{messageId}}", @@ -2933,7 +3127,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed." + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." } ], "source": { @@ -2950,7 +3144,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 12, + "seq": 20, "time": 0, "data": { "content": [ @@ -2979,7 +3173,7 @@ "sessionId": "{{child-1}}", "event": { "type": "user/message", - "seq": 13, + "seq": 21, "time": 0, "data": { "content": [ @@ -3027,7 +3221,7 @@ "sessionId": "{{child-1}}", "event": { "type": "request/header", - "seq": 14, + "seq": 22, "time": 0, "data": { "header": { @@ -3063,7 +3257,7 @@ "sessionId": "{{child-1}}", "event": { "type": "request/context", - "seq": 15, + "seq": 23, "time": 0, "data": { "provider": "deepseek-official", @@ -3079,12 +3273,12 @@ "sessionId": "{{child-1}}", "event": { "type": "session/title", - "seq": 16, + "seq": 24, "time": 0, "data": { "title": "Reply with exactly DIRECT_CHILD_OK and", "messageSeqs": [ - 12 + 20 ], "source": { "kind": "fallback" @@ -3099,12 +3293,12 @@ "sessionId": "{{child-1}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 17, + "seq": 25, "time": 0, "data": { "sessionId": "{{child-1}}", "sessionFormatVersion": 4, - "throughSeq": 16 + "throughSeq": 24 } } } @@ -3115,10 +3309,10 @@ "sessionId": "{{child-1}}", "event": { "type": "assistant/message", - "seq": 18, + "seq": 26, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "assistant", @@ -3229,10 +3423,10 @@ "sessionId": "{{child-1}}", "event": { "type": "step/end", - "seq": 19, + "seq": 27, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1 } } @@ -3244,10 +3438,10 @@ "sessionId": "{{child-1}}", "event": { "type": "turn/end", - "seq": 20, + "seq": 28, "time": 0, "data": { - "turn": 1, + "turn": 2, "reason": { "kind": "completed" } @@ -3712,11 +3906,201 @@ "payload": { "sessionId": "{{child-2}}", "event": { - "type": "step/start", + "type": "agent/inbox/spliced", "seq": 9, "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Cancellation checkpoint probe." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 10, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [], + "outcome": "canceled" + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 11, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "inserted": [ + { + "id": "{{messageId}}", + "role": "user", + "content": [ + { + "type": "text", + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + } + ], + "source": { + "kind": "plugin:serial-created-fixture" + } + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 12, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "inserted": [ + { + "content": [ + { + "type": "text", + "text": "Reply with exactly WORKFLOW_CHILD_OK and nothing else." + } + ], + "source": { + "kind": "user" + }, + "role": "user", + "id": "{{messageId}}" + } + ] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "turn/end", + "seq": 13, + "time": 0, "data": { "turn": 1, + "reason": { + "kind": "aborted", + "reason": { + "kind": "user" + } + } + } + } + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-2}}", + "status": "idle" + } + }, + { + "method": "session.status", + "payload": { + "sessionId": "{{child-2}}", + "status": "running" + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "turn/start", + "seq": 14, + "time": 0, + "data": { + "turn": 2 + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 15, + "time": 0, + "data": { + "target": "next-step", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "agent/inbox/spliced", + "seq": 16, + "time": 0, + "data": { + "target": "next-turn", + "start": 0, + "removedCount": 1, + "inserted": [] + } + } + } + }, + { + "method": "session.event", + "payload": { + "sessionId": "{{child-2}}", + "event": { + "type": "step/start", + "seq": 17, + "time": 0, + "data": { + "turn": 2, "step": 1 } } @@ -3728,10 +4112,10 @@ "sessionId": "{{child-2}}", "event": { "type": "system/message", - "seq": 10, + "seq": 18, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "system", @@ -3757,7 +4141,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 11, + "seq": 19, "time": 0, "data": { "id": "{{messageId}}", @@ -3765,7 +4149,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed." + "text": "Serial agent creation completed. Queue-clear failures still cancel active work." } ], "source": { @@ -3782,7 +4166,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 12, + "seq": 20, "time": 0, "data": { "content": [ @@ -3807,7 +4191,7 @@ "sessionId": "{{child-2}}", "event": { "type": "user/message", - "seq": 13, + "seq": 21, "time": 0, "data": { "content": [ @@ -3855,7 +4239,7 @@ "sessionId": "{{child-2}}", "event": { "type": "request/header", - "seq": 14, + "seq": 22, "time": 0, "data": { "header": { @@ -3891,7 +4275,7 @@ "sessionId": "{{child-2}}", "event": { "type": "request/context", - "seq": 15, + "seq": 23, "time": 0, "data": { "provider": "deepseek-official", @@ -3907,12 +4291,12 @@ "sessionId": "{{child-2}}", "event": { "type": "session/title", - "seq": 16, + "seq": 24, "time": 0, "data": { "title": "Reply with exactly WORKFLOW_CHILD_OK and", "messageSeqs": [ - 12 + 20 ], "source": { "kind": "fallback" @@ -3927,12 +4311,12 @@ "sessionId": "{{child-2}}", "event": { "type": "session-log-deepseek/delivery-accepted", - "seq": 17, + "seq": 25, "time": 0, "data": { "sessionId": "{{child-2}}", "sessionFormatVersion": 4, - "throughSeq": 16 + "throughSeq": 24 } } } @@ -3943,10 +4327,10 @@ "sessionId": "{{child-2}}", "event": { "type": "assistant/message", - "seq": 18, + "seq": 26, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1, "message": { "role": "assistant", @@ -4057,10 +4441,10 @@ "sessionId": "{{child-2}}", "event": { "type": "step/end", - "seq": 19, + "seq": 27, "time": 0, "data": { - "turn": 1, + "turn": 2, "step": 1 } } @@ -4072,10 +4456,10 @@ "sessionId": "{{child-2}}", "event": { "type": "turn/end", - "seq": 20, + "seq": 28, "time": 0, "data": { - "turn": 1, + "turn": 2, "reason": { "kind": "completed" } diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl index 46fbdba75d..e15e79f377 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl @@ -8,15 +8,23 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":16}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session/title","data":{"title":"Reply with exactly DIRECT_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-1}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DIRECT_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DIRECT_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl index 9c7213f1fd..817f66b355 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl @@ -8,15 +8,23 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"smoke-model","contextWindow":1000000}} -{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[12],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":16}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session/title","data":{"title":"Reply with exactly WORKFLOW_CHILD_OK and","messageSeqs":[20],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{child-2}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"WORKFLOW_CHILD_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["WORKFLOW_CHILD_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"WORKFLOW_CHILD_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} diff --git a/snapshots/sdk/serial-created/session.v4.jsonl b/snapshots/sdk/serial-created/session.v4.jsonl index 93cc0348f2..5109ba2c62 100644 --- a/snapshots/sdk/serial-created/session.v4.jsonl +++ b/snapshots/sdk/serial-created/session.v4.jsonl @@ -7,15 +7,12 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} -{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} -{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[11],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":15}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1788943826008,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788943826008,"index":0,"dt":[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788943826009,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:3}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"aborted","reason":{"kind":"disposed"}}}} From 5a537ce4865b130badf25163ceda875977540345 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Wed, 4 Nov 2026 21:42:43 +0800 Subject: [PATCH 002/103] test(sdk): keep root snapshot runs active through completion --- .../tests/fixtures/serial-created.mjs | 2 +- snapshots/sdk/serial-created/session.v4.jsonl | 21 +++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 138fd7d4b6..1295611023 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -10,7 +10,7 @@ export function apply(ctx, config = {}) { const checkedCancellation = new WeakSet() ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { if (checkedCancellation.has(agent) - || (config.checkRootCancellation === false && agent.session.header.origin !== 'subagent')) return next() + || (config.checkRootCancellation !== true && agent.session.header.origin !== 'subagent')) return next() checkedCancellation.add(agent) const pending = { id: randomUUID(), role: 'user', diff --git a/snapshots/sdk/serial-created/session.v4.jsonl b/snapshots/sdk/serial-created/session.v4.jsonl index 5109ba2c62..93cc0348f2 100644 --- a/snapshots/sdk/serial-created/session.v4.jsonl +++ b/snapshots/sdk/serial-created/session.v4.jsonl @@ -7,12 +7,15 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:3}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"}]}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} -{"type":"turn/start","data":{"turn":2}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} -{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"turn/end","data":{"turn":2,"reason":{"kind":"aborted","reason":{"kind":"disposed"}}}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} +{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[11],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":15}} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1788943826008,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788943826008,"index":0,"dt":[0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788943826009,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1788943826009,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":1}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 6e1eebe215583a08d87225c328e834c307983e50 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 03:11:46 +0800 Subject: [PATCH 003/103] fix(subagent): settle activations after agent factory unload --- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 5 +- .../subagent/tests/factory-settlement.spec.ts | 50 +++++++++++++++++++ 5 files changed, 58 insertions(+), 5 deletions(-) create mode 100644 packages/subagent/subagent/tests/factory-settlement.spec.ts diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 3b160b2782..4248dbcefa 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 152d969b7214b4cd - zh: 2ba2a43599b009d9 + en: e8b2853fe4a5105d + zh: fb0fdeeefee852ce /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index c3da369bed..a2012acd79 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. An Agent that has begun closing ends the local settlement observer rather than retrying maintenance admission. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When an Agent has begun closing, the manager settles its Activation through the shared close transaction without retrying maintenance admission. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index ed72da6c0a..b5159612d0 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,本地结算观察器会结束,不再重试维护准入。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,管理器通过共享关闭事务结算其 Activation,不再重试维护准入。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index e1b0bc6e68..ba0b8f4c29 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -993,7 +993,10 @@ export class SubagentManager { return Promise.resolve() }) } catch (error: unknown) { - if (error instanceof AgentClosedError) return Promise.resolve('closed') + if (error instanceof AgentClosedError) { + done = this.close(activation, () => this.finishDisposal(activation, false)) + return Promise.resolve({ done }) + } // Another activity already owns the Agent's idle phase. return Promise.resolve('retry') } diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts new file mode 100644 index 0000000000..6b5bb37324 --- /dev/null +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -0,0 +1,50 @@ +import { expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' +import { SessionId } from '@deepseek-ai/dsh-session' +import SubagentRuntime from '../src/index.ts' +import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' +import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' +import { managerState } from './manager-internals.ts' +import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' + +it('settles an activation when its factory unloads during the final flush', async () => { + const ctx = new Context() + const release = Promise.withResolvers() + const flushing = Promise.withResolvers() + try { + await mountAgentLoopTestDependencies(ctx) + const loop = await ctx.plugin(AgentLoop, { agents: [] }) + await mountWorkingDirectoryFixture(ctx) + await ctx.plugin(SubagentRuntime) + await ctx.plugin(SubagentSpawn, { providerName: 'spawn' }) + ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('answer')])) + const parent = await ctx.agentLoop.create(SessionId('factory-unload-parent'), { provider: 'mock', model: 'mock' }) + ctx.on('session/flush', async (session) => { + if (session.header.origin !== 'subagent') return + flushing.resolve(undefined) + await release.promise + }) + const started = await ctx.subagents.startActivation({ + provider: 'spawn', label: 'child', prompt: [{ type: 'text', text: 'task' }], + parent, signal: new AbortController().signal, delivery: 'caller', + }) + await flushing.promise + const state = managerState(ctx) + const activation = state.resident.get(started.childId)! + const released = vi.spyOn(activation, 'releaseSlot') + const ended = vi.fn() + ctx.on('subagent/end', ended) + await loop.dispose() + expect(ctx.agents.get(started.childId)).toBeUndefined() + release.resolve(undefined) + await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) + expect(await started.result).toMatchObject({ stopReason: 'completed' }) + expect(released).toHaveBeenCalledTimes(1) + expect(ended).toHaveBeenCalledTimes(1) + } finally { + release.resolve(undefined) + await ctx.fiber.dispose() + } +}) From a11de46bfd0f33efe211a392926c8440aa447461 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:16:47 +0800 Subject: [PATCH 004/103] fix(agent): guard inbox admission and settle disposed activations --- packages/core/agent-loop/src/agent.ts | 6 +++--- packages/core/agent-loop/src/inbox.ts | 12 ++++++++++++ .../agent-loop/tests/input-lifecycle.spec.ts | 19 ++++++++++++++++++- packages/subagent/subagent/src/manager.ts | 7 +++++++ .../subagent/tests/factory-settlement.spec.ts | 16 ++++++++++++++-- 5 files changed, 54 insertions(+), 6 deletions(-) diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 76b2c2b80e..12464720ae 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -148,7 +148,7 @@ export class ReactLoopAgent implements Agent { this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx this.model = new AgentModel(projections.modelSelection, session, options) - this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => this.assertOpen()) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) @@ -606,13 +606,13 @@ export class ReactLoopAgent implements Agent { maxParallelToolCalls, toolSet: decision.toolSet, }) for (const context of result.additionalContexts) { - this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) + this.inbox.retainContext(context) } return result.concluded ? { kind: 'completed' } : null } catch (error: unknown) { if (!(error instanceof ToolBatchExecutionError)) throw error for (const context of error.partial.additionalContexts) { - this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) + this.inbox.retainContext(context) } throw error.cause } diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index affe0c6b2f..8972667b10 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -69,12 +69,14 @@ export const inboxProjectionDefinition = { * @param readState - reader for the live Inbox projection state. * @param session - session whose durable events store pending input. * @param dispatch - agent-scoped notifications for Inbox lifecycle events. + * @param assertAdmission - rejects public insertions and replacements after admission closes. */ export class ReactLoopInbox implements InboxContract { constructor( private readonly readState: () => InboxState, private readonly session: Session, private readonly dispatch: AgentEventDispatch, + private readonly assertAdmission: () => void = () => {}, ) {} /** Prompts awaiting individual turns. */ @@ -137,6 +139,7 @@ export class ReactLoopInbox implements InboxContract { * @returns whether the message was still pending. */ replace(messageId: MessageId, newMessage: UserMessage): boolean { + this.assertAdmission() const location = this.locate(messageId) if (location === undefined) return false this.splice(location.target, location.index, 1, [newMessage]) @@ -169,9 +172,18 @@ export class ReactLoopInbox implements InboxContract { deleteCount: number, inserted: UserMessage[], ): UserMessage[] { + if (inserted.length > 0) this.assertAdmission() return this.mutate(target, start, deleteCount, inserted, true) } + /** + * Retain context finalized by admitted work, including during shutdown. + * @param message - context produced by the active driver. + */ + retainContext(message: UserMessage): void { + this.mutate('next-step', this.nextStep.length, 0, [message], true) + } + /** Locate one pending identity across both owned lists. */ private locate(messageId: MessageId): { target: InboxTarget; index: number } | undefined { const state = this.readState() diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 2e87517e1f..3cdb06da2c 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -96,7 +96,7 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') - for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {})]) { + for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => agent.inbox.append('next-turn', message), () => agent.inbox.prepend('next-step', message), () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) @@ -149,3 +149,20 @@ it('waits for admitted maintenance after a queue-clear failure before releasing await closing } }) + +it('does not start a driver when an inbox observer closes its owner during admission', async () => { + const { ctx, agent, handle, adapter } = await harness() + let closing: Promise | undefined + const stop = ctx.on('agent/inbox/inserted', ({ message }) => { + if (message.source.kind === 'user') closing = handle.dispose() + }) + try { + agent.followup(input('close during admission')) + expect(closing).toBeDefined() + await closing + expect(adapter.requests).toHaveLength(0) + } finally { + stop() + await closing + } +}) diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index ba0b8f4c29..f4a2a3d652 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -174,6 +174,12 @@ export class SubagentManager { }, session => host.identityOf(session)) ctx.on('agent/disposed', ({ agent }) => { this.closingRoots.delete(agent) + const activation = this.resident.get(agent.id) + if (activation?.kind === 'local' && activation.handle.agent === agent) { + void this.close(activation, () => this.finishDisposal(activation, false)).catch((error: unknown) => { + this.reportTeardownFailure(activation, error) + }) + } }) ctx.effect(function* (this: SubagentManager) { yield scope.dispose @@ -1127,6 +1133,7 @@ export class SubagentManager { } this.sendWaking(parent, message, parent.status === 'idle' ? 'queue' : 'steer') } catch (error: unknown) { + if (error instanceof AgentClosedError) return this.ctx.logger.warn( `subagent "${activation.childId}" settlement notice was not delivered to its parent: ` + errorChain(error), diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index 6b5bb37324..ed339efca6 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -2,14 +2,15 @@ import { expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' -import { SessionId } from '@deepseek-ai/dsh-session' +import { SessionId, type Session, type SessionEvent } from '@deepseek-ai/dsh-session' import SubagentRuntime from '../src/index.ts' import * as SubagentSpawn from '@deepseek-ai/dsh-subagent-spawn-in-process' import { mountWorkingDirectoryFixture } from './working-directory-fixture.ts' import { managerState } from './manager-internals.ts' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts' -it('settles an activation when its factory unloads during the final flush', async () => { +it.each([false, true])('settles an activation after factory unload with queue-clear failure=%s', async (rejectQueueClear) => { const ctx = new Context() const release = Promise.withResolvers() const flushing = Promise.withResolvers() @@ -36,7 +37,18 @@ it('settles an activation when its factory unloads during the final flush', asyn const released = vi.spyOn(activation, 'releaseSlot') const ended = vi.fn() ctx.on('subagent/end', ended) + const child = ctx.agents.get(started.childId)! + if (rejectQueueClear) child.inject(createUserMessage({ content: [{ type: 'text', text: 'pending' }], source: { kind: 'user' } })) + const rejectClear = ctx.on('internal/dispatch', (_mode, name, args) => { + if (name !== 'session/event') return + const [session, event] = args as [Session, SessionEvent] + if (rejectQueueClear && session === child.session && event.type === 'agent/inbox/spliced' && (event.data.removedCount ?? 0) > 0) { + throw new Error('queue clear rejected') + } + }) await loop.dispose() + expect(child.inbox.hasPending).toBe(rejectQueueClear) + rejectClear() expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) From 1e90c99c48cb9e6bc2f3fafbfbea85ec122de9fa Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:17:45 +0800 Subject: [PATCH 005/103] test(subagent): inspect pending input through public Inbox fields --- packages/subagent/subagent/tests/factory-settlement.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index ed339efca6..0228655cc5 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -47,7 +47,7 @@ it.each([false, true])('settles an activation after factory unload with queue-cl } }) await loop.dispose() - expect(child.inbox.hasPending).toBe(rejectQueueClear) + expect(child.inbox.nextStep.length + child.inbox.nextTurn.length > 0).toBe(rejectQueueClear) rejectClear() expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) From 477ca41b357b1a05d0d11f79f7c838f4004bab80 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:23:44 +0800 Subject: [PATCH 006/103] fix(ci): use block bodies for void admission callbacks --- packages/core/agent-loop/src/agent.ts | 2 +- packages/core/agent-loop/tests/input-lifecycle.spec.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 12464720ae..874739d7e1 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -148,7 +148,7 @@ export class ReactLoopAgent implements Agent { this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx this.model = new AgentModel(projections.modelSelection, session, options) - this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => this.assertOpen()) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => { this.assertOpen() }) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 3cdb06da2c..e3f095da28 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -71,7 +71,7 @@ it('cancellation still aborts the running request when queue clearing fails', as if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.target === 'next-turn' && (event.data.removedCount ?? 0) > 0) throw new Error('injected queue clear failure') }) - expect(() =>{ agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') + expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') expect(signal.aborted).toBe(true) } finally { stopRejecting() @@ -96,7 +96,7 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') - for (const submit of [() =>{ agent.followup(message) }, () =>{ agent.steer(message) }, () =>{ agent.inject(message) }, () =>{ agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => agent.inbox.append('next-turn', message), () => agent.inbox.prepend('next-step', message), () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { + for (const submit of [() => { agent.followup(message) }, () => { agent.steer(message) }, () => { agent.inject(message) }, () => { agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => { agent.inbox.append('next-turn', message) }, () => { agent.inbox.prepend('next-step', message) }, () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) From 7512ac4ce4ad63c8cdf940a8141308abd8f247d6 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:29:26 +0800 Subject: [PATCH 007/103] test(subagent): cover closure before settlement maintenance --- .../subagent/tests/continuation.spec.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..627f0f085e 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -8,7 +8,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { liveConfig } from '../../../settings/settings/tests/live-config.ts' import type { Agent } from '@deepseek-ai/dsh-agent' -import { agentEvents } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' @@ -2570,6 +2570,22 @@ describe('continuable review regressions', () => { expect(managerState(ctx).resident.get(started.childId)).toBeUndefined() }) + it('settles when Agent admission closes before settlement maintenance starts', async () => { + const release = Promise.withResolvers() + const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) + const { ctx, parent } = await setupWith(adapter) + const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) + await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) + const child = ctx.agents.get(started.childId)! + const maintenance = vi.spyOn(child, 'runMaintenance').mockImplementation(() => { + throw new AgentClosedError(child.id) + }) + release.resolve(undefined) + await waitNoActivation(ctx, started.childId) + expect(maintenance).toHaveBeenCalledTimes(1) + expect(await started.result).toMatchObject({ stopReason: 'completed' }) + }) + it('keeps a maintenance task that claimed the idle phase after whenIdle resolved', async () => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) From fe57dfce386d35c61ab1001722ec78f3dc0fe921 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:40:17 +0800 Subject: [PATCH 008/103] test(agent): cover quiescence failure during disposal --- .../core/agent-loop/tests/input-lifecycle.spec.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index e3f095da28..9a61005689 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -166,3 +166,16 @@ it('does not start a driver when an inbox observer closes its owner during admis await closing } }) + +it('reports a quiescence failure while releasing the Agent and Session', async () => { + const { ctx, agent, handle } = await harness() + const failure = new Error('injected quiescence failure') + const idle = vi.spyOn(agent, 'whenIdle').mockRejectedValueOnce(failure) + try { + await expect(handle.dispose()).rejects.toThrow('injected quiescence failure') + expect(ctx.agents.get(agent.id)).toBeUndefined() + expect(ctx.sessions.get(agent.id)).toBeUndefined() + } finally { + idle.mockRestore() + } +}) From e530b606e5a0c3f2d92a15f7a1c8e4c23120be5d Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 16:45:56 +0800 Subject: [PATCH 009/103] test(agent): retain resources through interrupted creation listeners --- .../agent-loop/tests/input-lifecycle.spec.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 9a61005689..560fea3ca1 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -179,3 +179,30 @@ it('reports a quiescence failure while releasing the Agent and Session', async ( idle.mockRestore() } }) + +it('keeps creation resources alive until an interrupted creation listener finishes', async () => { + const { ctx } = await harness() + const entered = Promise.withResolvers() + const release = Promise.withResolvers() + const signal = new AbortController() + const id = SessionId('interrupted-announcement') + const stop = ctx.on('agent/created', async ({ agent }) => { + if (agent.id !== id) return + entered.resolve(agent) + await release.promise + }) + const creation = ctx.agents.create({ sessionId: id, agentOptions: { provider: 'mock', model: 'mock' }, signal: signal.signal }) + .then(handle => handle.dispose(), (error: unknown) => error) + try { + const agent = await entered.promise + signal.abort(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBe(agent.session) + release.resolve(undefined) + expect(await creation).toEqual(new Error('creation interrupted')) + expect(ctx.sessions.get(id)).toBeUndefined() + } finally { + release.resolve(undefined) + await creation + stop() + } +}) From 9dc9f76702eef1dbd0474908591acf75567f7cb8 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Thu, 5 Nov 2026 17:06:51 +0800 Subject: [PATCH 010/103] test(session): refresh terminal panel runtime context reminder --- snapshots/session/terminal-panel-tools/session.v4.jsonl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snapshots/session/terminal-panel-tools/session.v4.jsonl b/snapshots/session/terminal-panel-tools/session.v4.jsonl index 01574413c3..290e17f9f6 100644 --- a/snapshots/session/terminal-panel-tools/session.v4.jsonl +++ b/snapshots/session/terminal-panel-tools/session.v4.jsonl @@ -8,7 +8,7 @@ {"type":"step/start","data":{"turn":1,"step":1}} {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"My tests fail in my terminal. What does it say?"}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} {"type":"session/title","data":{"title":"My tests fail in my","messageSeqs":[8],"source":{"kind":"fallback"}}} From feeb88466c0353f3b8340d9da1f08c355ade841c Mon Sep 17 00:00:00 2001 From: yudshj Date: Thu, 5 Nov 2026 23:22:47 +0800 Subject: [PATCH 011/103] =?UTF-8?q?perf(open-in-app):=20=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E5=8F=B3=E9=94=AE=E8=8F=9C=E5=8D=95=E4=B8=8D=E5=86=8D=E7=AD=89?= =?UTF-8?q?=E5=BE=85=E5=85=B3=E8=81=94=E5=BA=94=E7=94=A8=E6=9F=A5=E8=AF=A2?= =?UTF-8?q?=EF=BC=8C=E6=8C=89=E6=96=87=E4=BB=B6=E7=B1=BB=E5=9E=8B=E7=BC=93?= =?UTF-8?q?=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The file context menu now names the application recorded for the file's type without waiting for the Host's native association query (osascript / PowerShell / gio), then re-queries in the background and updates the open menu in place when the answer changes. Before the first answer for a type, the row opens the file through its OS association. --- .../client/ui-open-in-app/README.i18n.yaml | 12 +-- packages/client/ui-open-in-app/README.md | 7 +- packages/client/ui-open-in-app/README.zh.md | 7 +- .../src/client/context-menus.tsx | 87 +++++++++------- .../client/ui-open-in-app/src/client/index.ts | 1 + .../ui-open-in-app/src/client/open-path.ts | 98 +++++++++++++++++-- .../tests/browser-plugin.client.spec.ts | 23 ++++- .../tests/context-menu-actions.client.spec.ts | 81 +++++++++++++-- .../tests/open-path.client.spec.ts | 89 +++++++++++++++++ 9 files changed, 343 insertions(+), 62 deletions(-) diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index cfc7291505..5c3f8aa198 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: e07d3a607d54cb47 - zh: 9a7342f05b64db38 + en: 23fe56e2d62462ac + zh: e703585eac610e47 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: 22da59203ca974e6 - zh: f288bd6a193bccef + en: 32c651cd37edf401 + zh: c62dff20876e41fe /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: 59c434b70679fc16 - zh: 7fe9e52b0bb82df1 + en: bf22c831463d67b6 + zh: 78965275b1bc1179 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 9b0f75963b..5faf096be6 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -39,11 +39,11 @@ The **Open locally** shortcut captures the main Session’s directory and rememb File menus list the discovered associated applications without a separate “Open in default app” row. “Show file location” stays in a fixed footer separated from the scrolling applications. A successful query with only one available action renders a single button without a dropdown. Initial file-association loading uses a gray skeleton icon. When the Host identifies a default application the menu marks it “(default)” and the main button opens it; otherwise the first associated application takes that place, so the main button reveals the file only when no application is registered. Directory menus have no reveal row. Choosing a file application does not change the system default. An unpreviewable file uses the same menu in a 40px-high split button with an icon and action text; its label is “Open” or “Show file location” according to the default action. -Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. +Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. Every successful answer also replaces the page’s record for the file’s association class: the final name extension, or the whole path when the name has none. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. -Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata before querying applications. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. +Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata, then name the application recorded for the file’s type without waiting for the Host. Until the Host first answers for that type, the row reads “Open in default application” and opens the file through its OS association. Each opening re-queries the Host in the background; a changed answer updates the open menu in place, and a failed query keeps the recorded answer. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. File menus copy absolute paths without line numbers; URL copying preserves query and fragment. Image files also expose image copy and original download, alongside the existing file actions. Successful downloads and saves show the shared Toast; picker cancellation is silent. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh per class, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot and re-resolves from its verified path synchronously, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. @@ -93,6 +93,7 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. +- **File associations are cached by type for the page.** Files sharing a final name extension share one answer, so a per-document override, such as a macOS “Open with” choice for one file, or Linux content sniffing and multi-part extensions such as `.tar.gz` can show the type’s previous answer until the background query corrects the open menu. Names without an extension are recorded per path. Records grow with the file types seen and end with the page. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index 7bac1ae79f..b0a6177b8f 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -39,11 +39,11 @@ kind: "package-reference" 文件菜单列出已发现的关联应用,不单列“用默认应用打开”。“显示文件位置”固定在菜单底部,通过分隔线与滚动的应用列表分开。查询成功且只有一个可用操作时显示单按钮,不再显示下拉箭头。文件关联首次加载时使用灰色骨架图标。Host 识别出默认应用时,菜单将该项标注为“(默认)”,主按钮打开该应用;否则第一个关联应用占据该位置,只有在一个关联应用都没有时主按钮才执行文件定位。目录菜单不包含定位项。选择文件应用不修改系统默认应用。无法预览文件时,空态使用同一菜单,按钮增大到 40px 高并显示图标和动作文字;根据默认动作显示“打开”或“显示文件位置”。 -使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 +使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。每次查询成功后,结果还会替换本页面中该文件关联类别的记录:类别按文件名的最后一个扩展名划分,没有扩展名的文件按完整路径划分。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 -右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,再查询关联应用。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 +右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,然后直接显示该文件类型已记录的应用,不等待 Host。Host 首次回答该类型之前,这一项显示“使用默认应用打开”,通过系统的文件关联打开文件。每次打开菜单都会在后台重新查询 Host;回答有变化时,已打开的菜单原地更新,查询失败则保留已记录的回答。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 文件菜单复制不含行号的绝对路径;网址复制保留查询参数与锚点。图片文件在既有文件操作之外,还提供复制图片与下载原图。下载和保存成功后显示共享 Toast,取消选择器时不提示。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,每个类别同一时间只运行一次后台刷新,只在回答变化时发布新快照。文件菜单观察该快照,并基于已验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 @@ -93,6 +93,7 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 +- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答,因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”),或 Linux 的内容嗅探与 `.tar.gz` 这类多段扩展名,可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。没有扩展名的文件按路径记录。记录随出现过的文件类型增长,并在页面关闭时释放。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 5810a3aab7..6ee7d48cca 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -3,7 +3,7 @@ import { useState } from 'react' import { IconRightUpOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' import type { Context } from '@deepseek-ai/cordis' -import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { ContextMenuTargetMap, MenuAction } from '@deepseek-ai/dsh-client-ui-context-menu/client' import type {} from '@deepseek-ai/dsh-client-ui-workspace/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-api-workspace-files/remote' @@ -76,40 +76,61 @@ export function registerContextMenus( ] }, }), 'open-in-app: directory context menu') + const fileMenu = (target: ContextMenuTargetMap['file'], absolutePath: string | undefined): MenuAction[] => { + const { sessionId, path, line } = target + const available = absolutePath !== undefined + const desktop = paths.desktop.getSnapshot() === true && available + // Undefined until the Host first answers for this file type; the row then opens through the association. + const apps = desktop ? paths.cachedApplications(absolutePath) : [] + const application = apps?.find(app => app.default) + const openApplication = absolutePath === undefined || !desktop ? undefined + : application !== undefined ? () => open(absolutePath, 'open', application.id) + : apps === undefined ? () => open(absolutePath, 'open') : undefined + // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. + const openIn = (destination: 'sidebar' | 'float') => () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { + destination, ...(line === undefined ? {} : { params: { line } }), + }) + } + return [ + { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, + { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, + { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, + ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, + { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), + icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, + disabled: openApplication === undefined, ...openApplication === undefined ? {} : { run: openApplication } }, + { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), + run: async () => { + const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd + await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) + ctx.contextMenus.notify(t('menu.copied'), true) + } }, + ] + } + // The verified Host path of each open file menu. Association answers re-resolve the menu from it + // synchronously, so the registry keeps the other rows while the application row changes in place. + const verified = new WeakMap() ctx.effect(() => ctx.contextMenus.register({ id: 'open-in-app.file', target: 'file', order: 100, - resolve: async (target, signal) => { - const { sessionId, path, line } = target - await paths.load() - const absolutePath = await resolvePath(sessionId, path, signal) - const available = absolutePath !== undefined - const desktop = paths.desktop.getSnapshot() === true && available - const apps = desktop ? await paths.applications(absolutePath, signal) : [] - signal.throwIfAborted() - const application = apps?.find(app => app.default) - // The menu names a host, not the pane it was raised in: a floating pane is never a docked landing place. - const openIn = (destination: 'sidebar' | 'float') => () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - ctx.sidebarRight.openResourceIn(sessionId, fileAddressFor(sessionId, cwd, path), { - destination, ...(line === undefined ? {} : { params: { line } }), - }) - } - return [ - { id: 'sidebar', icon: { key: 'open-in-app.sidebar' }, label: t('menu.openInSidebar'), disabled: !available, run: openIn('sidebar') }, - { id: 'float', icon: { key: 'open-in-app.float' }, label: t('menu.openInFloat'), disabled: !available, run: openIn('float') }, - { id: 'reveal', icon: { key: 'open-in-app.reveal' }, label: fileManager(), disabled: !desktop, - ...absolutePath === undefined ? {} : { run: () => open(absolutePath, 'reveal') } }, - { id: 'open', label: application ? t('open.title', { app: application.name }) : t('menu.defaultApp'), - icon: { key: 'open-in-app.application', ...application?.icon ? { src: application.icon } : {} }, - disabled: application === undefined, - ...absolutePath === undefined || application === undefined ? {} : { run: () => open(absolutePath, 'open', application.id) } }, - { id: 'copyPath', icon: { key: 'open-in-app.copy' }, failureLabel: t('menu.copyFailed'), label: t('menu.copyPath'), - run: async () => { - const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd - await navigator.clipboard.writeText(absolutePath ?? resolveWorkspacePath(cwd, path)) - ctx.contextMenus.notify(t('menu.copied'), true) - } }, - ] + observe: (target) => { + // Each occurrence subscribes before its first resolution, so a reopened target is verified again. + verified.set(target, null) + return [paths.associations] + }, + resolve: (target, signal) => { + const settled = verified.get(target) + if (settled) return fileMenu(target, settled.absolutePath) + return (async () => { + await paths.load() + const absolutePath = await resolvePath(target.sessionId, target.path, signal) + signal.throwIfAborted() + verified.set(target, { absolutePath }) + // A cached answer shows at once; every opening re-queries so a changed association reaches this menu. + if (absolutePath !== undefined && paths.desktop.getSnapshot() === true) paths.refreshApplications(absolutePath) + return fileMenu(target, absolutePath) + })() }, }), 'open-in-app: file context menu') ctx.effect(() => ctx.contextMenus.register({ diff --git a/packages/client/ui-open-in-app/src/client/index.ts b/packages/client/ui-open-in-app/src/client/index.ts index e706f9eb25..84bdc9168e 100644 --- a/packages/client/ui-open-in-app/src/client/index.ts +++ b/packages/client/ui-open-in-app/src/client/index.ts @@ -56,6 +56,7 @@ export function apply(ctx: ClientContext): void { const controller = new OpenInAppController() void controller.load() const paths = new OpenInAppPathController(ctx.remote) + ctx.effect(() => () => { paths.dispose() }, 'open-in-app: association refreshes') ctx.effect(() => ctx.locale.register(NS, { zh, en, ja, es, fr, de, ru, pt }), 'open-in-app: dictionaries') const t = ctx.locale.bind(NS) // Keep operation feedback visible after its initiating panel closes. diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index 4484bb29b9..bc9fb4c808 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -1,12 +1,34 @@ /** * Host desktop availability, file associations, and open/reveal actions over the Session Remote. - * The desktop answer is read once per page; a failed read renders no control. + * The desktop answer is read once per page; a failed read renders no control. Association answers + * are recorded per association class so menus can show them without waiting for the Host. */ -import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type ObservableSnapshot, type SnapshotStore } from '@deepseek-ai/dsh-client-store' import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import type { SessionOpenWorkspacePathRequest, SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppOutcome, OpenInAppPathFailure } from './outcome.ts' +type Applications = readonly SessionWorkspacePathApplication[] + +/** + * Name the association class of a Host path: desktops look handlers up by the final name extension, so + * files sharing it share one answer; a name without one (`Makefile`, `.env`) is its own class. + */ +function associationKey(path: string): string { + const name = path.slice(Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) + 1) + const dot = name.lastIndexOf('.') + return dot > 0 && dot < name.length - 1 ? `extension:${name.slice(dot)}` : `path:${path}` +} + +/** Compare two answers field by field, including icon data. */ +function sameApplications(left: Applications, right: Applications): boolean { + return left.length === right.length && left.every((app, index) => { + const other = right[index] + return other !== undefined && app.id === other.id && app.name === other.name + && app.default === other.default && app.icon === other.icon + }) +} + /** What a path gesture asks of the Host desktop: the default application, or the file manager showing the file. */ export type OpenInAppPathAction = 'open' | 'reveal' @@ -24,11 +46,24 @@ export interface OpenInAppPathRemote { } } -/** Page-lifetime desktop availability and the open/reveal carrier shared by every path control. */ +/** + * Page-lifetime desktop availability, association answers, and the open/reveal carrier shared by every path control. + * Answers are kept per association class for the page's life and grow with the classes queried. + */ export class OpenInAppPathController { /** Whether the Host desktop can open paths; null until the Host answered, false also after a failed read. */ readonly desktop: SnapshotStore = createSnapshotStore(null) + private readonly answers = createSnapshotStore>(new Map()) + /** Latest successful answer per association class; the snapshot keeps its identity until an answer changes. */ + readonly associations: ObservableSnapshot> = this.answers private loading: Promise | undefined + private readonly lifetime = new AbortController() + private readonly refreshing = new Set() + /** Start order of the query whose answer each class holds; an earlier query never replaces a later one. */ + private readonly answeredBy = new Map() + /** One icon string per application id, reused by every class that lists the application. */ + private readonly icons = new Map() + private queries = 0 /** * @param remote - the Session Remote namespace answering availability and running gestures. @@ -66,20 +101,67 @@ export class OpenInAppPathController { } /** - * Refresh the file's OS associations; failures remain distinct from an empty handler list. + * Query the file's current OS associations and record a successful answer for its association class. + * Failures remain distinct from an empty handler list and leave the recorded answer in place. * @param path - file path reported by the Host. - * @param signal - lifetime of the requesting preview. + * @param signal - lifetime of the requesting control. * @returns application metadata, or null when the query fails. */ - async applications(path: string, signal: AbortSignal): Promise { - let result: RemoteResult + async applications(path: string, signal: AbortSignal): Promise { + const order = ++this.queries + let result: RemoteResult try { result = await this.remote.session.workspacePathApplications({ path }, signal) } catch (_error) { // The control reports query failure and keeps file reveal available. return null } - return result.ok ? result.value : null + if (!result.ok) return null + this.record(associationKey(path), order, result.value) + return result.value + } + + /** + * Read the recorded answer of a file's association class without querying the Host. + * @param path - absolute Host path of the file. + * @returns the latest successful answer, or undefined before a query of this class succeeded. + */ + cachedApplications(path: string): Applications | undefined { + return this.answers.getSnapshot().get(associationKey(path)) + } + + /** + * Re-query a file's associations in the background. One refresh per association class runs at a time; + * it outlives the requesting menu and ends with its answer or {@link dispose}. + * @param path - absolute Host path of the file. + */ + refreshApplications(path: string): void { + const key = associationKey(path) + if (this.lifetime.signal.aborted || this.refreshing.has(key)) return + this.refreshing.add(key) + void this.applications(path, this.lifetime.signal).finally(() => { this.refreshing.delete(key) }) + } + + /** Cancel background refreshes and refuse new ones; recorded answers stay readable. */ + dispose(): void { + this.lifetime.abort() + } + + private record(key: string, order: number, applications: Applications): void { + if ((this.answeredBy.get(key) ?? 0) > order) return + this.answeredBy.set(key, order) + const answers = this.answers.getSnapshot() + const previous = answers.get(key) + if (previous !== undefined && sameApplications(previous, applications)) return + const next = new Map(answers) + next.set(key, applications.map((app) => { + if (app.icon === null) return app + const icon = this.icons.get(app.id) + if (icon === app.icon) return { ...app, icon } + this.icons.set(app.id, app.icon) + return app + })) + this.answers.set(next) } private async run(): Promise { diff --git a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts index ca27f69e50..274d379207 100644 --- a/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/browser-plugin.client.spec.ts @@ -49,10 +49,13 @@ afterEach(() => { /** The Session Remote slice the path controls call; answers a desktop and acknowledges every gesture. */ const remote = { session: { - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal) => ({ ok: true as const, value: [] })), canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: { opened: true as const } })), }, + workspaceFiles: { + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: `/w/${path}` } })), + }, } /** Boot the browser half over a real slot tree that declares the header list and the document-preview seats. */ @@ -335,6 +338,24 @@ describe('open-in-app browser half', () => { expect(ctx.slots.entries('deliverables.file.actions')).toHaveLength(0) }) + it('lets a file-menu association refresh outlive the menu and cancels it with the plugin', async () => { + vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) + const { ctx, fiber } = await bench() + let refresh: AbortSignal | undefined + remote.session.workspacePathApplications.mockImplementationOnce((_request, signal) => { + refresh = signal + return new Promise(() => {}) + }) + const menu = ctx.contextMenus.resolve({ kind: 'file', value: { sessionId: 'files' as SessionId, path: 'notes.txt' } }) + await menu.ready + expect(remote.workspaceFiles.stat).toHaveBeenCalledWith('files', 'notes.txt', expect.any(AbortSignal)) + expect(remote.session.workspacePathApplications).toHaveBeenCalledWith({ path: '/w/notes.txt' }, refresh) + menu.dispose() + expect(refresh?.aborted).toBe(false) + await fiber.dispose() + expect(refresh?.aborted).toBe(true) + }) + it('injects the announcement seat into the delivery entries and releases every entry with the fiber', async () => { vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ apps: [] }), { status: 200 }))) const { ctx, fiber } = await bench() diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 10407f9f54..b3d7d5a319 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -7,6 +7,8 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' import { SessionId } from '@deepseek-ai/dsh-session' import { MenuRegistry } from '@deepseek-ai/dsh-client-ui-context-menu/src/client/registry.ts' import type { ContextMenus, ContextMenuTarget } from '@deepseek-ai/dsh-client-ui-context-menu/client' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { FileActionSource, FileSaveResult } from '@deepseek-ai/dsh-client-ui-file-actions/client' import { OpenInAppPathController } from '../src/client/open-path.ts' import { OpenInAppController } from '../src/client/controller.ts' @@ -15,6 +17,7 @@ import { registerContextMenus } from '../src/client/context-menus.tsx' import type { OpenInAppToastSource } from '../src/client/open-toast.tsx' const sessionId = SessionId('menu-actions') +type Applications = readonly SessionWorkspacePathApplication[] afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) async function boot() { @@ -27,13 +30,13 @@ async function boot() { const remote = { session: { canOpenWorkspacePath: vi.fn(async () => ({ ok: true as const, value: true })), - workspacePathApplications: vi.fn(async () => ({ ok: true as const, value: [ - { id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }, - ] })), + workspacePathApplications: vi.fn(async (_request: { path: string }, _signal?: AbortSignal): Promise> => ({ + ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: 'data:image/png;base64,a' }], + })), openWorkspacePath: vi.fn(async () => ({ ok: true as const, value: undefined })), }, workspaceFiles: { - stat: vi.fn(async () => ({ ok: true as const, value: { absolutePath: '/workspace/file.svg' } })), + stat: vi.fn(async (_sessionId: SessionId, path: string) => ({ ok: true as const, value: { absolutePath: path.startsWith('/') ? path : `/workspace/${path}` } })), readBytes: vi.fn(async () => ({ ok: true as const, value: { data: [...new TextEncoder().encode('')] } })), }, } @@ -82,14 +85,17 @@ it('routes file actions through an explicit host, the line, native association a const h = await boot() // A menu raised inside a floating panel names that panel; the open names a host instead, never a pane. const file = { kind: 'file', value: { sessionId, path: 'file.svg', paneId: 'float7' as never, line: 24 } } as const - const items = (await h.resolve(file)).source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) - expect(items.map(item => [item.id, item.label, item.icon?.key])).toEqual([ + const first = await h.resolve(file) + const items = () => first.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + await vi.waitFor(() => { expect(items().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(items().map(item => [item.id, item.label, item.icon?.key])).toEqual([ ['open-in-app.file/sidebar', 'menu.openInSidebar', 'open-in-app.sidebar'], ['open-in-app.file/float', 'menu.openInFloat', 'open-in-app.float'], ['open-in-app.file/reveal', 'menu.reveal', 'open-in-app.reveal'], ['open-in-app.file/open', 'open.title', 'open-in-app.application'], ['open-in-app.file/copyPath', 'menu.copyPath', 'open-in-app.copy'], ]) + first.dispose() await h.choose(file, 'open-in-app.file/sidebar') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(sessionId, expect.stringContaining('file.svg'), { destination: 'sidebar', params: { line: 24 } }) @@ -114,7 +120,8 @@ it('routes file actions through an explicit host, the line, native association a const simple = { kind: 'file', value: { sessionId: SessionId('absent'), path: '/file.unknown' } } as const h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const menu = await h.resolve(simple) - expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + // Without an answer the row opens through the association; the Host's empty answer then disables it in place. + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) }) expect(menu.source.getSnapshot().some(item => item.id.endsWith('/copyImage'))).toBe(false) expect(menu.source.getSnapshot().filter(item => item.id.startsWith('file-actions.')).map(item => item.id)) .toEqual(['file-actions.file/saveAs']) @@ -122,10 +129,59 @@ it('routes file actions through an explicit host, the line, native association a expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'sidebar' }) h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const floating = await h.resolve(simple) + expect(floating.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) floating.select('open-in-app.file/float') expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'float' }) }) +it('opens file menus before the Host answers and changes only the application row in place', async () => { + const h = await boot() + const answers: ((answer: RemoteResult) => void)[] = [] + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise((answer) => { answers.push(answer) })) + const file = { kind: 'file', value: { sessionId, path: 'notes.txt' } } as const + const menu = await h.resolve(file) + const rows = () => menu.source.getSnapshot().filter(item => item.id.startsWith('open-in-app.file/')) + const application = () => rows().find(item => item.id === 'open-in-app.file/open') + expect(answers).toHaveLength(1) + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + expect(application()?.icon).toEqual({ key: 'open-in-app.application' }) + const published: number[] = [] + const stop = menu.source.subscribe(() => { published.push(rows().length) }) + answers[0]!({ ok: true, value: [ + { id: '/Applications/TextEdit.app', name: 'TextEdit', default: false, icon: null }, + { id: '/Applications/Sublime Text.app', name: 'Sublime Text', default: true, icon: 'data:image/png;base64,c3Vi' }, + ] }) + await vi.waitFor(() => { expect(application()).toMatchObject({ label: 'open.title', icon: { src: 'data:image/png;base64,c3Vi' } }) }) + stop() + expect(published.length).toBeGreaterThan(0) + expect(published.every(count => count === 5)).toBe(true) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { + expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.txt', application: '/Applications/Sublime Text.app' }) + }) + // Another file of the same type shows the recorded answer at once and asks the Host again. + const other = await h.resolve({ kind: 'file', value: { sessionId, path: 'todo.txt' } }) + const otherApplication = () => other.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(otherApplication()?.label).toBe('open.title') + expect(answers).toHaveLength(2) + answers[1]!({ ok: true, value: [] }) + await vi.waitFor(() => { expect(otherApplication()).toMatchObject({ label: 'menu.defaultApp', disabled: true }) }) + other.dispose() + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens through the OS association until the Host first answers, including after failed queries', async () => { + const h = await boot() + h.remote.session.workspacePathApplications.mockResolvedValue({ ok: false } as never) + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.md' } }) + await vi.waitFor(() => { expect(h.remote.session.workspacePathApplications).toHaveBeenCalledOnce() }) + const application = menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(application).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.select('open-in-app.file/open') + await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.md' }) }) + await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'opened' }) }) +}) + it('keeps copy-path available on failed metadata and reports native action failures', async () => { const h = await boot() const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const @@ -139,14 +195,23 @@ it('keeps copy-path available on failed metadata and reports native action failu h.remote.session.openWorkspacePath.mockResolvedValueOnce({ ok: false } as never) await h.choose(file, 'open-in-app.file/reveal') await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'failed', failure: 'revealError' }) }) + await vi.waitFor(() => { expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) }) + // A failed query keeps the recorded answer. h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: false } as never) - expect((await h.resolve(file)).source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) + const kept = await h.resolve(file) + await vi.waitFor(() => { + expect(h.remote.session.workspacePathApplications.mock.settledResults.every(result => result.type !== 'incomplete')).toBe(true) + }) + expect(kept.source.getSnapshot().find(item => item.id.endsWith('/open'))).toMatchObject({ label: 'open.title', disabled: false }) + kept.dispose() h.paths.desktop.set(false) h.fileActions.canSaveAs = false + const queried = h.remote.session.workspacePathApplications.mock.calls.length const web = await h.resolve(file) expect(web.source.getSnapshot().some(item => item.id.endsWith('/saveAs'))).toBe(false) expect(web.source.getSnapshot().filter(item => ['/open', '/reveal'].some(suffix => item.id.endsWith(suffix))) .every(item => item.disabled)).toBe(true) + expect(h.remote.session.workspacePathApplications).toHaveBeenCalledTimes(queried) }) it('opens links in the registered browser, externally, and on the clipboard', async () => { diff --git a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts index e542b9164c..8eb4362032 100644 --- a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts @@ -94,3 +94,92 @@ it('distinguishes failed association queries from an empty application list', as const rejecting = new OpenInAppPathController(remoteOf({ workspacePathApplications: async () => { throw new Error('disconnected') } })) expect(await rejecting.applications('/file.mp3', new AbortController().signal)).toBeNull() }) + +describe('OpenInAppPathController association answers', () => { + type Answer = Awaited> + const app = (name: string, icon: string | null = null) => ({ id: `/Applications/${name}.app`, name, default: true, icon }) + const answered = (...apps: ReturnType[]): Answer => ({ ok: true, value: apps }) + /** A Remote whose association queries settle when the test answers them. */ + function deferredRemote() { + const queries: { path: string; signal: AbortSignal | undefined; answer: (result: Answer) => void }[] = [] + const workspacePathApplications = vi.fn((request: { path: string }, signal?: AbortSignal) => new Promise((answer) => { + queries.push({ path: request.path, signal, answer }) + })) + return { queries, controller: new OpenInAppPathController(remoteOf({ workspacePathApplications })) } + } + + it('shares an answer across files with the same final extension and keeps extensionless names apart', async () => { + const answers: Record = { + '/w/notes.txt': answered(app('TextEdit')), '/w/Makefile': answered(app('Xcode')), '/w/.env': answered(app('Zed')), + } + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications: async ({ path }) => answers[path]! })) + const signal = new AbortController().signal + expect(controller.cachedApplications('/w/notes.txt')).toBeUndefined() + for (const path of Object.keys(answers)) await controller.applications(path, signal) + expect(controller.cachedApplications('/elsewhere/todo.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('C:\\work\\archive.tar.txt')).toEqual([app('TextEdit')]) + expect(controller.cachedApplications('/w/NOTES.TXT')).toBeUndefined() + expect(controller.cachedApplications('/w/Makefile')).toEqual([app('Xcode')]) + expect(controller.cachedApplications('/other/Makefile')).toBeUndefined() + expect(controller.cachedApplications('/w/.env')).toEqual([app('Zed')]) + expect(controller.cachedApplications('/w/draft.')).toBeUndefined() + }) + + it('publishes changed answers only, and an earlier query never replaces a later answer', async () => { + const { queries, controller } = deferredRemote() + const signal = new AbortController().signal + const earlier = controller.applications('/w/a.txt', signal) + const later = controller.applications('/w/b.txt', signal) + queries[1]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + expect(await later).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const published = controller.associations.getSnapshot() + queries[0]!.answer(answered(app('TextEdit'))) + expect(await earlier).toEqual([app('TextEdit')]) + expect(controller.associations.getSnapshot()).toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,c3Vi')]) + const unchanged = controller.applications('/w/c.txt', signal) + queries[2]!.answer(answered(app('Sublime Text', 'data:image/png;base64,c3Vi'))) + await unchanged + expect(controller.associations.getSnapshot()).toBe(published) + const changed = controller.applications('/w/c.txt', signal) + queries[3]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit'))) + await changed + expect(controller.associations.getSnapshot()).not.toBe(published) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3'), app('TextEdit')]) + const other = controller.applications('/w/d.md', signal) + queries[4]!.answer(answered(app('Sublime Text', 'data:image/png;base64,bmV3'))) + await other + expect(controller.cachedApplications('/w/e.md')).toEqual([app('Sublime Text', 'data:image/png;base64,bmV3')]) + expect(controller.cachedApplications('/w/e.txt')).toHaveLength(2) + }) + + it('keeps the recorded answer through refused and rejected queries', async () => { + const workspacePathApplications = vi.fn() + .mockResolvedValueOnce(answered(app('Preview'))) + .mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'boom', {}) }) + .mockRejectedValueOnce(new Error('down')) + const controller = new OpenInAppPathController(remoteOf({ workspacePathApplications })) + const signal = new AbortController().signal + await controller.applications('/w/a.png', signal) + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(await controller.applications('/w/a.png', signal)).toBeNull() + expect(controller.cachedApplications('/w/b.png')).toEqual([app('Preview')]) + }) + + it('runs one background refresh per association class until it settles, and disposal cancels it', async () => { + const { queries, controller } = deferredRemote() + controller.refreshApplications('/w/a.txt') + controller.refreshApplications('/w/b.txt') + controller.refreshApplications('/w/c.md') + expect(queries.map(query => query.path)).toEqual(['/w/a.txt', '/w/c.md']) + queries[0]!.answer(answered(app('TextEdit'))) + await vi.waitFor(() => { expect(controller.cachedApplications('/w/b.txt')).toEqual([app('TextEdit')]) }) + controller.refreshApplications('/w/b.txt') + expect(queries.map(query => query.path)).toEqual(['/w/a.txt', '/w/c.md', '/w/b.txt']) + controller.dispose() + expect(queries.every(query => query.signal?.aborted)).toBe(true) + controller.refreshApplications('/w/d.json') + expect(queries).toHaveLength(3) + expect(controller.cachedApplications('/w/a.txt')).toEqual([app('TextEdit')]) + }) +}) From 0eda288f13d124932378cb47bccb08f974d787de Mon Sep 17 00:00:00 2001 From: yudshj Date: Thu, 5 Nov 2026 23:47:41 +0800 Subject: [PATCH 012/103] =?UTF-8?q?fix(open-in-app):=20=E5=90=8E=E5=8F=B0?= =?UTF-8?q?=E5=88=B7=E6=96=B0=E5=90=8C=E4=B8=80=E6=97=B6=E9=97=B4=E5=8F=AA?= =?UTF-8?q?=E8=B7=91=E4=B8=80=E4=B8=AA=EF=BC=8C=E9=AA=8C=E8=AF=81=E6=9C=9F?= =?UTF-8?q?=E9=97=B4=E7=9A=84=E5=9B=9E=E7=AD=94=E4=B8=8D=E5=86=8D=E8=A7=A6?= =?UTF-8?q?=E5=8F=91=E9=87=8D=E5=A4=8D=20stat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A newer file-menu opening cancels the unfinished background refresh and queries its own file, so a stuck native query cannot block later refreshes and quick openings no longer fan out concurrent queries. Answers published while a menu is still verifying its target no longer restart that verification. README wording now matches the refresh order and documents the remaining cache limitations. --- .../client/ui-open-in-app/README.i18n.yaml | 12 +++--- packages/client/ui-open-in-app/README.md | 6 +-- packages/client/ui-open-in-app/README.zh.md | 6 +-- .../src/client/context-menus.tsx | 9 ++++- .../ui-open-in-app/src/client/open-path.ts | 20 +++++----- .../tests/context-menu-actions.client.spec.ts | 37 +++++++++++++++++-- .../tests/open-path.client.spec.ts | 21 +++++------ 7 files changed, 73 insertions(+), 38 deletions(-) diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index 5c3f8aa198..1524a8857f 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: 23fe56e2d62462ac - zh: e703585eac610e47 + en: 4e40e41d89fe99a9 + zh: 818b488e997132f5 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: 32c651cd37edf401 - zh: c62dff20876e41fe + en: 020fda5b8360fb3d + zh: 7c33f3f45c41e64e /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: bf22c831463d67b6 - zh: 78965275b1bc1179 + en: 2fd6d93cc66f3b42 + zh: 9199fbf041fe2ad4 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 5faf096be6..a5eecd9344 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -39,7 +39,7 @@ The **Open locally** shortcut captures the main Session’s directory and rememb File menus list the discovered associated applications without a separate “Open in default app” row. “Show file location” stays in a fixed footer separated from the scrolling applications. A successful query with only one available action renders a single button without a dropdown. Initial file-association loading uses a gray skeleton icon. When the Host identifies a default application the menu marks it “(default)” and the main button opens it; otherwise the first associated application takes that place, so the main button reveals the file only when no application is registered. Directory menus have no reveal row. Choosing a file application does not change the system default. An unpreviewable file uses the same menu in a 40px-high split button with an icon and action text; its label is “Open” or “Show file location” according to the default action. -Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. Every successful answer also replaces the page’s record for the file’s association class: the final name extension, or the whole path when the name has none. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. +Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A successful answer also replaces the page’s record for the file’s association class unless a later-started query has already answered it; the class is the final name extension, compared case-sensitively, or the whole path when the name has none. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh per class, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot and re-resolves from its verified path synchronously, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot and re-resolves from its verified path synchronously, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. @@ -93,7 +93,7 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. -- **File associations are cached by type for the page.** Files sharing a final name extension share one answer, so a per-document override, such as a macOS “Open with” choice for one file, or Linux content sniffing and multi-part extensions such as `.tar.gz` can show the type’s previous answer until the background query corrects the open menu. Names without an extension are recorded per path. Records grow with the file types seen and end with the page. +- **File associations are cached by type for the page.** Files sharing a final name extension share one answer. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu; Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index b0a6177b8f..d4fb2fe9eb 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference" 文件菜单列出已发现的关联应用,不单列“用默认应用打开”。“显示文件位置”固定在菜单底部,通过分隔线与滚动的应用列表分开。查询成功且只有一个可用操作时显示单按钮,不再显示下拉箭头。文件关联首次加载时使用灰色骨架图标。Host 识别出默认应用时,菜单将该项标注为“(默认)”,主按钮打开该应用;否则第一个关联应用占据该位置,只有在一个关联应用都没有时主按钮才执行文件定位。目录菜单不包含定位项。选择文件应用不修改系统默认应用。无法预览文件时,空态使用同一菜单,按钮增大到 40px 高并显示图标和动作文字;根据默认动作显示“打开”或“显示文件位置”。 -使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。每次查询成功后,结果还会替换本页面中该文件关联类别的记录:类别按文件名的最后一个扩展名划分,没有扩展名的文件按完整路径划分。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 +使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询成功后,结果还会替换本页面中该文件关联类别的记录,除非更晚发起的查询已经给出回答;类别按文件名的最后一个扩展名划分(区分大小写),没有扩展名的文件按完整路径划分。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,每个类别同一时间只运行一次后台刷新,只在回答变化时发布新快照。文件菜单观察该快照,并基于已验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照,并基于已验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 @@ -93,7 +93,7 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 -- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答,因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”),或 Linux 的内容嗅探与 `.tar.gz` 这类多段扩展名,可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。没有扩展名的文件按路径记录。记录随出现过的文件类型增长,并在页面关闭时释放。 +- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单;Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 6ee7d48cca..2ec13942e7 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -111,13 +111,18 @@ export function registerContextMenus( } // The verified Host path of each open file menu. Association answers re-resolve the menu from it // synchronously, so the registry keeps the other rows while the application row changes in place. + // This relies on the registry subscribing once per occurrence before its first resolution, and on a + // synchronous resolution replacing rows without clearing them first. const verified = new WeakMap() ctx.effect(() => ctx.contextMenus.register({ id: 'open-in-app.file', target: 'file', order: 100, observe: (target) => { - // Each occurrence subscribes before its first resolution, so a reopened target is verified again. verified.set(target, null) - return [paths.associations] + // The first resolution reads the newest answers once verified; answers arriving earlier need no re-resolution. + return [{ + getSnapshot: paths.associations.getSnapshot.bind(paths.associations), + subscribe: (listener: () => void) => paths.associations.subscribe(() => { if (verified.get(target)) listener() }), + }] }, resolve: (target, signal) => { const settled = verified.get(target) diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index bc9fb4c808..b0c70ba38f 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -20,7 +20,7 @@ function associationKey(path: string): string { return dot > 0 && dot < name.length - 1 ? `extension:${name.slice(dot)}` : `path:${path}` } -/** Compare two answers field by field, including icon data. */ +/** Equal answers keep the published snapshot, so observers re-resolve only when an answer changes. */ function sameApplications(left: Applications, right: Applications): boolean { return left.length === right.length && left.every((app, index) => { const other = right[index] @@ -58,10 +58,11 @@ export class OpenInAppPathController { readonly associations: ObservableSnapshot> = this.answers private loading: Promise | undefined private readonly lifetime = new AbortController() - private readonly refreshing = new Set() + /** The background refresh in flight; a newer refresh cancels it. */ + private refresh: AbortController | undefined /** Start order of the query whose answer each class holds; an earlier query never replaces a later one. */ private readonly answeredBy = new Map() - /** One icon string per application id, reused by every class that lists the application. */ + /** One icon string per application id, reused by every class that lists the application so its data URL is held once. */ private readonly icons = new Map() private queries = 0 @@ -131,15 +132,16 @@ export class OpenInAppPathController { } /** - * Re-query a file's associations in the background. One refresh per association class runs at a time; - * it outlives the requesting menu and ends with its answer or {@link dispose}. + * Re-query a file's associations in the background. One refresh runs at a time: it outlives the + * requesting menu and ends with its answer, the next refresh, which cancels it, or {@link dispose}. * @param path - absolute Host path of the file. */ refreshApplications(path: string): void { - const key = associationKey(path) - if (this.lifetime.signal.aborted || this.refreshing.has(key)) return - this.refreshing.add(key) - void this.applications(path, this.lifetime.signal).finally(() => { this.refreshing.delete(key) }) + if (this.lifetime.signal.aborted) return + this.refresh?.abort() + const refresh = new AbortController() + this.refresh = refresh + void this.applications(path, AbortSignal.any([this.lifetime.signal, refresh.signal])) } /** Cancel background refreshes and refuse new ones; recorded answers stay readable. */ diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index b3d7d5a319..2ea3d500a2 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -18,6 +18,8 @@ import type { OpenInAppToastSource } from '../src/client/open-toast.tsx' const sessionId = SessionId('menu-actions') type Applications = readonly SessionWorkspacePathApplication[] +/** Let settled Remote answers finish their queued continuations. */ +const settle = () => new Promise((resolve) => { setTimeout(resolve, 0) }) afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals() }) async function boot() { @@ -172,16 +174,41 @@ it('opens file menus before the Host answers and changes only the application ro it('opens through the OS association until the Host first answers, including after failed queries', async () => { const h = await boot() - h.remote.session.workspacePathApplications.mockResolvedValue({ ok: false } as never) + let refuse = () => {} + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + refuse = () => { answer({ ok: false } as never) } + })) const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.md' } }) - await vi.waitFor(() => { expect(h.remote.session.workspacePathApplications).toHaveBeenCalledOnce() }) - const application = menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') - expect(application).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + const application = () => menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open') + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + refuse() + await settle() + expect(h.paths.cachedApplications('/workspace/notes.md')).toBeUndefined() + expect(application()).toMatchObject({ label: 'menu.defaultApp', disabled: false }) menu.select('open-in-app.file/open') await vi.waitFor(() => { expect(h.remote.session.openWorkspacePath).toHaveBeenLastCalledWith({ path: '/workspace/notes.md' }) }) await vi.waitFor(() => { expect(h.report).toHaveBeenLastCalledWith({ kind: 'opened' }) }) }) +it('verifies a file menu once when answers for other files arrive during verification', async () => { + const h = await boot() + let release = () => {} + const verifying = new Promise((resolve) => { release = resolve }) + h.remote.workspaceFiles.stat.mockImplementation(async (_sessionId: SessionId, path: string) => { + await verifying + return { ok: true as const, value: { absolutePath: `/workspace/${path}` } } + }) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + release() + await menu.ready + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) + menu.dispose() +}) + it('keeps copy-path available on failed metadata and reports native action failures', async () => { const h = await boot() const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const @@ -202,6 +229,8 @@ it('keeps copy-path available on failed metadata and reports native action failu await vi.waitFor(() => { expect(h.remote.session.workspacePathApplications.mock.settledResults.every(result => result.type !== 'incomplete')).toBe(true) }) + await settle() + expect(h.paths.cachedApplications('/workspace/file.svg')).toHaveLength(1) expect(kept.source.getSnapshot().find(item => item.id.endsWith('/open'))).toMatchObject({ label: 'open.title', disabled: false }) kept.dispose() h.paths.desktop.set(false) diff --git a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts index 8eb4362032..af6f3475b7 100644 --- a/packages/client/ui-open-in-app/tests/open-path.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/open-path.client.spec.ts @@ -99,11 +99,12 @@ describe('OpenInAppPathController association answers', () => { type Answer = Awaited> const app = (name: string, icon: string | null = null) => ({ id: `/Applications/${name}.app`, name, default: true, icon }) const answered = (...apps: ReturnType[]): Answer => ({ ok: true, value: apps }) - /** A Remote whose association queries settle when the test answers them. */ + /** A Remote whose association queries settle when the test answers them, and reject once cancelled. */ function deferredRemote() { const queries: { path: string; signal: AbortSignal | undefined; answer: (result: Answer) => void }[] = [] - const workspacePathApplications = vi.fn((request: { path: string }, signal?: AbortSignal) => new Promise((answer) => { + const workspacePathApplications = vi.fn((request: { path: string }, signal?: AbortSignal) => new Promise((answer, reject) => { queries.push({ path: request.path, signal, answer }) + signal?.addEventListener('abort', () => { reject(new Error('cancelled')) }, { once: true }) })) return { queries, controller: new OpenInAppPathController(remoteOf({ workspacePathApplications })) } } @@ -166,19 +167,17 @@ describe('OpenInAppPathController association answers', () => { expect(controller.cachedApplications('/w/b.png')).toEqual([app('Preview')]) }) - it('runs one background refresh per association class until it settles, and disposal cancels it', async () => { + it('runs one background refresh at a time, cancelling the older for the newer file, and disposal cancels it', async () => { const { queries, controller } = deferredRemote() controller.refreshApplications('/w/a.txt') controller.refreshApplications('/w/b.txt') - controller.refreshApplications('/w/c.md') - expect(queries.map(query => query.path)).toEqual(['/w/a.txt', '/w/c.md']) - queries[0]!.answer(answered(app('TextEdit'))) - await vi.waitFor(() => { expect(controller.cachedApplications('/w/b.txt')).toEqual([app('TextEdit')]) }) - controller.refreshApplications('/w/b.txt') - expect(queries.map(query => query.path)).toEqual(['/w/a.txt', '/w/c.md', '/w/b.txt']) + expect(queries.map(query => [query.path, query.signal?.aborted])).toEqual([['/w/a.txt', true], ['/w/b.txt', false]]) + queries[1]!.answer(answered(app('TextEdit'))) + await vi.waitFor(() => { expect(controller.cachedApplications('/w/c.txt')).toEqual([app('TextEdit')]) }) + controller.refreshApplications('/w/d.md') controller.dispose() - expect(queries.every(query => query.signal?.aborted)).toBe(true) - controller.refreshApplications('/w/d.json') + expect(queries[2]).toMatchObject({ path: '/w/d.md', signal: { aborted: true } }) + controller.refreshApplications('/w/e.json') expect(queries).toHaveLength(3) expect(controller.cachedApplications('/w/a.txt')).toEqual([app('TextEdit')]) }) From ea7c21c8a47dba0814ef3e6e13af8b4316a8d261 Mon Sep 17 00:00:00 2001 From: yudshj Date: Fri, 6 Nov 2026 09:01:29 +0800 Subject: [PATCH 013/103] =?UTF-8?q?fix(open-in-app):=20=E6=AF=8F=E6=AC=A1?= =?UTF-8?q?=E6=89=93=E5=BC=80=E6=96=87=E4=BB=B6=E8=8F=9C=E5=8D=95=E9=83=BD?= =?UTF-8?q?=E6=A0=A1=E9=AA=8C=E8=B7=AF=E5=BE=84=EF=BC=8C=E5=B7=B2=E6=89=93?= =?UTF-8?q?=E5=BC=80=E7=9A=84=E8=8F=9C=E5=8D=95=E5=8F=AA=E5=93=8D=E5=BA=94?= =?UTF-8?q?=E6=9C=AC=E7=B1=BB=E5=9E=8B=E7=9A=84=E5=9B=9E=E7=AD=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A file menu now reuses its verified Host path only while its own association subscription re-resolves it synchronously, and the verification record is cleared when a stat starts instead of when the registry observes. Every opening therefore runs its own stat whatever order the context-menu registry observes and resolves in; a registry change can at most cost another stat or a flicker. An open menu re-resolves only when its own file type's answer changes. The answer comparison lists every application field and fails to compile when the type gains one. README documents the remaining cache limitations. --- .../client/ui-open-in-app/README.i18n.yaml | 12 ++--- packages/client/ui-open-in-app/README.md | 7 +-- packages/client/ui-open-in-app/README.zh.md | 7 +-- .../src/client/context-menus.tsx | 51 ++++++++++++------- .../ui-open-in-app/src/client/open-path.ts | 10 ++-- .../tests/context-menu-actions.client.spec.ts | 22 ++++++++ 6 files changed, 76 insertions(+), 33 deletions(-) diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index 1524a8857f..a38fe57e45 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: 4e40e41d89fe99a9 - zh: 818b488e997132f5 + en: 53d5d74d5b1d9b66 + zh: bdd9806dca51e957 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: 020fda5b8360fb3d - zh: 7c33f3f45c41e64e + en: c26d8937f5d38119 + zh: d353c2377b9747aa /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: 2fd6d93cc66f3b42 - zh: 9199fbf041fe2ad4 + en: f206d2fefa52f81d + zh: 51025a6e19d01295 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index a5eecd9344..5ab8a3894f 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -39,7 +39,7 @@ The **Open locally** shortcut captures the main Session’s directory and rememb File menus list the discovered associated applications without a separate “Open in default app” row. “Show file location” stays in a fixed footer separated from the scrolling applications. A successful query with only one available action renders a single button without a dropdown. Initial file-association loading uses a gray skeleton icon. When the Host identifies a default application the menu marks it “(default)” and the main button opens it; otherwise the first associated application takes that place, so the main button reveals the file only when no application is registered. Directory menus have no reveal row. Choosing a file application does not change the system default. An unpreviewable file uses the same menu in a 40px-high split button with an icon and action text; its label is “Open” or “Show file location” according to the default action. -Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A successful answer also replaces the page’s record for the file’s association class unless a later-started query has already answered it; the class is the final name extension, compared case-sensitively, or the whole path when the name has none. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. +Mounted controls with the same association reader and file share one query and its results; opening either menu refreshes all of them. Releasing the last control cancels the query and discards its state. Cancelled queries cannot replace another file’s results. A successful answer also replaces the page’s record for the file’s association class unless a later-started query has already answered it; the class is the final name extension, compared case-sensitively, or the whole path when the name has none. Mounted controls do not read that record and keep their own answer until their menu opens again, so the file header and a context menu can name different applications for one file meanwhile. A failed query displays a menu message and leaves reveal available as the default action. File-association discovery follows [native-command](../../util/native-command/README.md); an empty result, including a platform without a discovery adapter, uses the same reveal fallback without platform branches in the control. Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot and re-resolves from its verified path synchronously, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening or plugin unload cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot; when its own file type’s answer changes, it re-resolves synchronously from the path its opening verified, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. @@ -93,7 +93,8 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. -- **File associations are cached by type for the page.** Files sharing a final name extension share one answer. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu; Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. +- **File associations are cached by type for the page.** Files sharing a final name extension share one answer; extensions that differ only in case, such as `.PNG` and `.png`, are separate types. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu. Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect, and one file’s empty answer shows the row disabled for the type’s other files the same way. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. +- **One background refresh at a time.** Opening another file menu cancels the previous menu’s unanswered query, so that type keeps its earlier answer, or none, until its next opening. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index d4fb2fe9eb..dd65ffdb58 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -39,7 +39,7 @@ kind: "package-reference" 文件菜单列出已发现的关联应用,不单列“用默认应用打开”。“显示文件位置”固定在菜单底部,通过分隔线与滚动的应用列表分开。查询成功且只有一个可用操作时显示单按钮,不再显示下拉箭头。文件关联首次加载时使用灰色骨架图标。Host 识别出默认应用时,菜单将该项标注为“(默认)”,主按钮打开该应用;否则第一个关联应用占据该位置,只有在一个关联应用都没有时主按钮才执行文件定位。目录菜单不包含定位项。选择文件应用不修改系统默认应用。无法预览文件时,空态使用同一菜单,按钮增大到 40px 高并显示图标和动作文字;根据默认动作显示“打开”或“显示文件位置”。 -使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询成功后,结果还会替换本页面中该文件关联类别的记录,除非更晚发起的查询已经给出回答;类别按文件名的最后一个扩展名划分(区分大小写),没有扩展名的文件按完整路径划分。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 +使用同一查询函数和文件的已挂载控件共用查询与结果,打开任一菜单会刷新所有相关控件。最后一个控件释放后取消查询并清除状态。已取消的查询不会覆盖其他文件的结果。查询成功后,结果还会替换本页面中该文件关联类别的记录,除非更晚发起的查询已经给出回答;类别按文件名的最后一个扩展名划分(区分大小写),没有扩展名的文件按完整路径划分。已挂载控件不读取这份记录,会保留自己的回答,直到再次打开其菜单,因此在此期间同一个文件在文件标题栏和右键菜单中可能显示不同的应用。查询失败时菜单显示提示,并以文件定位作为默认动作。文件关联查询的平台支持范围见 [native-command](../../util/native-command/README.zh.md);查询结果为空时,包括平台尚无查询适配器的情况,控件统一使用定位动作,不按操作系统分支处理。 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照,并基于已验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单或插件卸载会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照;只有本文件类型的回答变化时,才基于本次打开时验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 @@ -93,7 +93,8 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 -- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单;Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 +- **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答;只有大小写不同的扩展名(如 `.PNG` 和 `.png`)算作不同类型。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果;某个文件的空回答也会以同样的方式,让同类型其他文件的这一项先显示为禁用。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 +- **同一时间只有一次后台刷新。** 打开另一个文件的菜单会取消前一个菜单尚未返回的查询,该类型保留之前的回答(或仍没有回答),直到下次打开。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 2ec13942e7..76e518ae3d 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -109,31 +109,46 @@ export function registerContextMenus( } }, ] } - // The verified Host path of each open file menu. Association answers re-resolve the menu from it - // synchronously, so the registry keeps the other rows while the application row changes in place. - // This relies on the registry subscribing once per occurrence before its first resolution, and on a - // synchronous resolution replacing rows without clearing them first. - const verified = new WeakMap() + // The Host path from each file target's latest successful stat, shared by menus open on one target object at once. + // A stat clears it while running; answers arriving meanwhile need no re-resolution, as that stat's resolution reads + // the newest answers. + const verified = new WeakMap() + // The target whose changed association answer is being applied; only that re-resolution reuses the verified path, + // so every opening runs its own stat. The in-place update relies on the registry re-resolving synchronously from + // the notification, without which the menu stats again, and on a synchronous resolution replacing rows without + // clearing them first, without which the rows flicker. + let answering: ContextMenuTargetMap['file'] | undefined ctx.effect(() => ctx.contextMenus.register({ id: 'open-in-app.file', target: 'file', order: 100, - observe: (target) => { - verified.set(target, null) - // The first resolution reads the newest answers once verified; answers arriving earlier need no re-resolution. - return [{ - getSnapshot: paths.associations.getSnapshot.bind(paths.associations), - subscribe: (listener: () => void) => paths.associations.subscribe(() => { if (verified.get(target)) listener() }), - }] - }, + observe: target => [{ + getSnapshot: paths.associations.getSnapshot.bind(paths.associations), + subscribe: (listener: () => void) => { + // Answers for other file types leave this menu unchanged. + let shown: ReturnType + return paths.associations.subscribe(() => { + const absolutePath = verified.get(target) + if (absolutePath === undefined) return + const applications = paths.cachedApplications(absolutePath) + if (applications === shown) return + shown = applications + answering = target + try { listener() } finally { answering = undefined } + }) + }, + }], resolve: (target, signal) => { - const settled = verified.get(target) - if (settled) return fileMenu(target, settled.absolutePath) + const verifiedPath = answering === target ? verified.get(target) : undefined + if (verifiedPath !== undefined) return fileMenu(target, verifiedPath) + verified.delete(target) return (async () => { await paths.load() const absolutePath = await resolvePath(target.sessionId, target.path, signal) signal.throwIfAborted() - verified.set(target, { absolutePath }) - // A cached answer shows at once; every opening re-queries so a changed association reaches this menu. - if (absolutePath !== undefined && paths.desktop.getSnapshot() === true) paths.refreshApplications(absolutePath) + if (absolutePath !== undefined) { + verified.set(target, absolutePath) + // A cached answer shows at once; every opening re-queries so a changed association reaches this menu. + if (paths.desktop.getSnapshot() === true) paths.refreshApplications(absolutePath) + } return fileMenu(target, absolutePath) })() }, diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index b0c70ba38f..ba17321fca 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -20,12 +20,16 @@ function associationKey(path: string): string { return dot > 0 && dot < name.length - 1 ? `extension:${name.slice(dot)}` : `path:${path}` } +/** The compared application fields; a field added to the type fails to compile until it is listed here. */ +const APPLICATION_FIELDS = Object.keys({ + id: true, name: true, default: true, icon: true, +} satisfies Record) as readonly (keyof SessionWorkspacePathApplication)[] + /** Equal answers keep the published snapshot, so observers re-resolve only when an answer changes. */ function sameApplications(left: Applications, right: Applications): boolean { return left.length === right.length && left.every((app, index) => { const other = right[index] - return other !== undefined && app.id === other.id && app.name === other.name - && app.default === other.default && app.icon === other.icon + return other !== undefined && APPLICATION_FIELDS.every(field => app[field] === other[field]) }) } @@ -58,7 +62,7 @@ export class OpenInAppPathController { readonly associations: ObservableSnapshot> = this.answers private loading: Promise | undefined private readonly lifetime = new AbortController() - /** The background refresh in flight; a newer refresh cancels it. */ + /** The latest background refresh; a newer refresh aborts it. */ private refresh: AbortController | undefined /** Start order of the query whose answer each class holds; an earlier query never replaces a later one. */ private readonly answeredBy = new Map() diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 2ea3d500a2..85a92ccac3 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -209,6 +209,28 @@ it('verifies a file menu once when answers for other files arrive during verific menu.dispose() }) +it('verifies every opening of a file target, whatever order the registry observes and resolves in', async () => { + const register = vi.spyOn(MenuRegistry.prototype, 'register') + const h = await boot() + const contribution = register.mock.calls.map(([input]) => input).find(input => input.id === 'open-in-app.file')! + const target = { sessionId, path: 'notes.txt' } + // Resolving without observing first, as a registry that subscribes after its first resolution would. + await contribution.resolve(target, new AbortController().signal) + await contribution.resolve(target, new AbortController().signal) + expect(h.remote.workspaceFiles.stat).toHaveBeenCalledTimes(2) +}) + +it('re-resolves an open file menu only when its own file type answers differently', async () => { + const h = await boot() + const menu = await h.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label).toBe('open.title') }) + const shown = menu.source.getSnapshot() + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) + expect(menu.source.getSnapshot()).toBe(shown) + menu.dispose() +}) + it('keeps copy-path available on failed metadata and reports native action failures', async () => { const h = await boot() const file = { kind: 'file', value: { sessionId, path: 'file.svg' } } as const From a0ae65fa355438b04859843cff248399267ccc43 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 13:18:42 +0800 Subject: [PATCH 014/103] Honor the selected macOS window for element clicks and hover --- .../native/Sources/CuaNative/AXAccess.swift | 4 ++-- .../native/Sources/CuaNative/AXWorker.swift | 13 +++++++++++-- packages/experimental/cua-macos/src/guidance.ts | 2 +- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 8376f1a312..50c8bd3a64 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -639,7 +639,7 @@ final class AXAccess { return AXProjection(tree: lines.joined(separator: "\n"), elements: elements, indexed: indexed, focusedWindowID: focusedID, truncated: truncated) } - func enclosingWindow(_ element: AXUIElement, owner: ProcessIdentity) throws -> WindowInfo { + func enclosingWindow(_ element: AXUIElement) throws -> (element: AXUIElement, id: UInt32) { var current: AXUIElement? = element var visited: [AXUIElement] = [] for _ in 0..<100 { @@ -648,7 +648,7 @@ final class AXAccess { visited.append(node) let role = try string(node, "AXRole") if role == "AXWindow" || role == "AXSheet", let id = try windowID(node) { - return try WindowGeometry.resolve(owner: owner, windowID: id) { try bounds(node) } + return (node, id) } current = try self.element(node, "AXParent") } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index dea2eacb7a..ad079bedac 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -350,8 +350,16 @@ actor AXWorker { let point: WindowPoint var hoverElement: AXUIElement? if params.contains("elementId") { - guard !params.contains("x"), !params.contains("y"), !params.contains("windowId") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } + guard !params.contains("x"), !params.contains("y"), !params.contains("relative") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } let selected = try element(handle, params) + let scopedWindow = try params.optionalWindowID().map { id in + try coordinateSnapshot(handle, params, id) + let enclosing = try ax().enclosingWindow(selected) + guard enclosing.id == id else { + throw NativeFailure(code: "STALE_SNAPSHOT", message: "Element belongs to another window; read the selected window again") + } + return enclosing + } hoverElement = selected if method == "click" { let names = try ax().actions(selected) @@ -364,7 +372,8 @@ actor AXWorker { try ax().requireEnabled(selected) } guard let bounds = try ax().bounds(selected), bounds.width > 0, bounds.height > 0 else { throw NativeFailure(code: "NATIVE_ERROR", message: "Element has no pointer bounds") } - window = try ax().enclosingWindow(selected, owner: identity) + let enclosing = try scopedWindow ?? ax().enclosingWindow(selected) + window = try WindowGeometry.resolve(owner: identity, windowID: enclosing.id) { try ax().bounds(enclosing.element) } point = WindowPoint(x: bounds.x + bounds.width / 2 - window.bounds.x, y: bounds.y + bounds.height / 2 - window.bounds.y) } else { let id = try params.windowID() diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 3f062dfbc7..d50011eb06 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} From 10d4199270a6445945caf33622bdd4360b9f7faf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 13:22:18 +0800 Subject: [PATCH 015/103] Document and exercise window-scoped macOS element input --- packages/experimental/cua-macos/README.i18n.yaml | 8 ++++---- packages/experimental/cua-macos/README.md | 5 +++-- packages/experimental/cua-macos/README.zh.md | 5 +++-- packages/experimental/cua-macos/native/tests/e2e.py | 13 +++++++++++-- .../session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../ptc-script-retained/system-prompt.expected.md | 2 +- 7 files changed, 24 insertions(+), 13 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index f5c5b0ad0e..88d127489f 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: 7fdb7c0462275417 zh: 0a4a9562f4a82945 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 8bf27cf5a258b1f4 - zh: dba694e92bc6c091 + en: d80ab0362946144c + zh: 2cb9fc12bb473300 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 @@ -45,8 +45,8 @@ en: a2c9acb5a4320dda zh: e8d1586af60215c4 /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work: - en: dfedb97af676b4f4 - zh: 1c910e047dbb04ff + en: 4fefaf88ea9eefc6 + zh: d3d18cfbccf8c20f /deepseek-ai-dsh-experimental-cua-macos/known-limitations-and-deferred-work/dev-note: en: b836f01bd0bceb4a zh: 8122fa08b2aa95fa diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 4cc1f4b2b6..311c7cce7a 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -122,6 +122,8 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Screenshot capture requires an attachment store and a resolved model route declaring image input. The shared attachment admission validates canonical Base64, the raster and its configured capacity, then stores the image once. Native data remains available to programmatic callers; model content carries coordinate metadata and the durable image reference. Response byte limits apply before parsing. +Window clicks and mouse moves accept an element ID from the latest tree. The element must belong to the selected window. To trigger the default action of a menu item outside any window, use `app.invoke(id)`. + Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; `scroll` uses named `x` and `y`. All use pixels in the latest returned screenshot. Pass `relative: true` for integer thousandths of window width and height, from 0 to 999; omission or `false` uses pixels. Relative input can use a successful AX read or screenshot, while absolute input requires a screenshot. The Host maps the delivered image to native points, including attachment and model-request resizing. A value of 999 remains inside the window edge. Coordinate options do not apply to element IDs. A width or height change since the latest observation returns `WINDOW_CHANGED` before input, including raw coordinate calls without a snapshot ID; read fresh AX or take a new screenshot before proceeding. Window movement alone preserves window-local coordinates. Capture and pointer input reject known disagreement between the selected window’s accessibility frame and displayed bounds with `WINDOW_CHANGED`, before posting pointer events. This includes Stage Manager transformations when AX retains the full window frame. Read fresh state; any activation or window raise remains explicit. Advertised AX actions remain available. Missing AX geometry retains the AXless path and does not establish that a transformed window can be operated. Retained objects resolve the current tool binding on every call. The external runtime owns persistence, imports, cancellation and completion-value serialization. Screenshots return encoded bytes with their MIME type, pixel dimensions and window ID; the standard tool pipeline admits the image attachment exactly once. `emit: false` suppresses facade output only. A host that uses another dispatcher can build objects through `createCuaApi` from `./api`. @@ -173,7 +175,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -241,7 +243,6 @@ The queue orders individual native requests. Holding an app object does not rese - The guide closes when its selected settings window leaves the visible-window list, including when a Space switch or minimization removes it. Request permission again after returning to reopen the guide. - Only the macOS native implementation is provided. Windows support is in development; this package remains in `experimental` until that support is complete, then moves to the `computer-use` group. Browser tabs, AX diffs, unassociated system panels and accessory-only apps are unsupported. - Element IDs belong to the application's current accessibility snapshot; a later read replaces them. Screenshots and pointer input require an explicit window object. -- On macOS, the window object includes its window ID on element-targeted `click` and `mouseMove` calls. The helper rejects that combination with `INVALID_ARGUMENT`. Use window coordinates for pointer input or `invoke(elementId)` for a control’s default action. - Coordinates use the returned screenshot pixels, including the title bar; `relative: true` selects integers from 0 to 999. Native point conversion is Host-owned. Window movement, application changes and other desktop users can race observations and input. - macOS Stage Manager can reduce background window bounds and screenshots to thumbnails. Full-window observation and coordinate input in this state are not guaranteed; model guidance requires explaining foreground needs and avoiding repeated focus reclamation. - Background input depends on private SkyLight symbols; macOS updates can make them unavailable. Validate each target OS version. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 9bb74015f4..629c99c357 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -122,6 +122,8 @@ void await window.getScreenshot() 截图要求附件服务可用,并确认当前模型支持图片输入。共享附件接入校验规范 Base64、图像数据及配置容量,然后保存一次图片。程序调用方仍可取得原生数据,模型内容包含坐标元数据和持久图片引用。响应字节上限在解析前执行。 +窗口的 `click` 和 `mouseMove` 接受最新树中的元素 ID。元素必须属于所选窗口。菜单项如果不属于任何窗口,可用 `app.invoke(id)` 触发默认动作。 + `mouseMove`、`click` 和 `drag` 的绝对坐标使用 `[x, y]` 元组;`scroll` 使用命名的 `x` 和 `y`。它们都使用最近返回截图中的像素。传入 `relative: true` 时使用 0~999 的千分比整数;省略或传入 `false` 时使用像素。相对坐标可基于成功的 AX 读取或截图,绝对坐标必须先截图。Host 根据实际送入模型的图片尺寸换算原生 point,包含附件归一化和模型请求阶段的缩放。999 映射到窗口边缘以内。坐标选项不适用于元素 ID。窗口宽高与最近一次观察不同时,在输入前返回 `WINDOW_CHANGED`,即使原始坐标调用不传快照 ID 也会检查;重新读取 AX 或截图后再操作。单纯移动窗口不使窗口内坐标失效。截图和鼠标输入会核对所选窗口的辅助功能框与显示边界;已知两者不一致时,在发送任何鼠标事件前返回 `WINDOW_CHANGED`。当 AX 保留完整窗口框时,这也会拦住 Stage Manager 变换后的窗口。需要重新读取状态;激活应用或抬起窗口仍须显式调用。元素声明的 AX 动作保持可用。缺少 AX 几何时保留无 AX 路径,不代表变换后的窗口一定可以操作。 保留的对象会在每次调用时获取当前工具绑定。外部运行时负责持久化、导入、取消和最终表达式值的序列化。截图返回编码字节及其 MIME 类型、像素尺寸和窗口 ID,标准工具链负责将图片作为附件传递一次。`emit: false` 只控制对象层的输出。使用其他分派器的宿主可以通过 `./api` 的 `createCuaApi` 创建对象。 @@ -173,7 +175,7 @@ AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档 ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -241,7 +243,6 @@ Raw tools use { method, params }: include appHandle for app calls and windowId f - 所选设置窗口离开可见窗口列表时,引导框会关闭,包括切换桌面空间或最小化导致窗口不再可见的情况。返回后再次申请权限可重新打开引导。 - 只提供 macOS 原生实现,Windows 支持正在开发中。本包暂放在 `experimental`,待 Windows 支持完成后迁回 `computer-use` 组。不支持浏览器标签、启动应用、AX 差分、无法确认应用归属的系统面板,以及仅后台辅助类型的应用。 - 元素 ID 只对应用当前的辅助功能快照有效;之后的读取会替换它们。截图和指针输入都要求显式的窗口对象。 -- 在 macOS 上,窗口对象调用 `click(elementId)` 或 `mouseMove(elementId)` 时会附带窗口 ID,helper 会以 `INVALID_ARGUMENT` 拒绝该组合。鼠标操作可传窗口坐标,执行控件的默认动作可调用 `invoke(elementId)`。 - 坐标使用包含标题栏的返回截图像素;`relative: true` 使用 0~999 的整数,由 Host 换算原生 point。窗口移动、应用变化及其他桌面使用者的操作可能与观察和输入交错。 - macOS 台前调度可能将后台窗口的尺寸与截图变为缩略图,当前无法保证这种状态下的完整画面与坐标输入;模型指引要求说明前台需求并避免反复抢回焦点。 - 后台输入依赖私有 SkyLight 符号,macOS 升级可能使其不可用,需在目标系统版本验证。 diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 11c266387b..017a5dec75 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -158,7 +158,16 @@ def main(): assert len(matches) == 1, state return {**owner, "snapshotId": state["snapshotId"], "elementId": matches[0]["elementId"]} - target = button_target(first, "Increment primary") + target = {**button_target(first, "Increment primary"), "windowId": primary["windowId"]} + app_state = call("getState", {**owner, "maxElements": 300, "maxDepth": 20}) + other_button = button_target(app_state, "Increment secondary") + for method in ("click", "mouseMove"): + unknown = call(method, {**target, "elementId": "9999"}, "INVALID_ARGUMENT") + assert "elementId is absent" in unknown["message"], unknown + call(method, {**target, "x": 0, "y": 0}, "INVALID_ARGUMENT") + call(method, {**target, "relative": True}, "INVALID_ARGUMENT") + call(method, {**target, "windowId": secondary["windowId"]}, "STALE_SNAPSHOT") + call(method, {**other_button, "windowId": primary["windowId"]}, "STALE_SNAPSHOT") call("click", target) wait_state(lambda state: state["count"] == 1, "primary click was not received exactly once") call("click", button_target(second, "Increment secondary")) @@ -203,7 +212,7 @@ def main(): hover_state = call("getState", primary_params) capture(primary, "02-native-hover.png") assert json.loads(state_path.read_text())["hoverVisible"], "Observation dismissed native hover controls" - hover_target = button_target(hover_state, "Use native hover details") + hover_target = {**button_target(hover_state, "Use native hover details"), "windowId": primary["windowId"]} mouse_move(hover_target) call("click", hover_target) wait_state(lambda actual: actual["hoverClicks"] == 1, "Native hover control did not activate") diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index d736617f95..cd615392cd 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 1e4c496e13..cf3c4797fb 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index da1e87c182..a2b412b5ff 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Use window coordinates for click and mouseMove on macOS. The helper rejects element-targeted pointer requests carrying the window ID supplied by these object methods. For an element’s default action, use invoke with its latest ID. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. From d4f0efa260b3f8d4a3b02b6e00a6097c845a7609 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 13:23:45 +0800 Subject: [PATCH 016/103] Exercise mouse delivery to the center of a scoped element --- packages/experimental/cua-macos/native/tests/e2e.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 017a5dec75..e7e40f5c73 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -170,6 +170,8 @@ def main(): call(method, {**other_button, "windowId": primary["windowId"]}, "STALE_SNAPSHOT") call("click", target) wait_state(lambda state: state["count"] == 1, "primary click was not received exactly once") + call("click", {**target, "holdMs": 50}) + wait_state(lambda state: state["count"] == 2, "element-center mouse click did not reach the primary button") call("click", button_target(second, "Increment secondary")) wait_state(lambda state: state["secondaryCount"] == 1, "second window snapshot was invalidated by primary action") first = call("getState", primary_params) From 97ec654f44a0743988b282d85c4e0dd07a877ae4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:08:05 +0800 Subject: [PATCH 017/103] Send mouse events for every macOS click --- .../native/Sources/CuaNative/AXWorker.swift | 26 +++++-------------- .../experimental/cua-macos/src/guidance.ts | 2 +- 2 files changed, 8 insertions(+), 20 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index ad079bedac..ba16630e6a 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -350,29 +350,17 @@ actor AXWorker { let point: WindowPoint var hoverElement: AXUIElement? if params.contains("elementId") { - guard !params.contains("x"), !params.contains("y"), !params.contains("relative") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } + guard !params.contains("x"), !params.contains("y") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } + let requestedWindow = try params.optionalWindowID() + if let requestedWindow { try coordinateSnapshot(handle, params, requestedWindow) } let selected = try element(handle, params) - let scopedWindow = try params.optionalWindowID().map { id in - try coordinateSnapshot(handle, params, id) - let enclosing = try ax().enclosingWindow(selected) - guard enclosing.id == id else { - throw NativeFailure(code: "STALE_SNAPSHOT", message: "Element belongs to another window; read the selected window again") - } - return enclosing + let enclosing = try ax().enclosingWindow(selected) + if let requestedWindow, enclosing.id != requestedWindow { + throw NativeFailure(code: "STALE_SNAPSHOT", message: "Element belongs to window \(enclosing.id); select that window and read its tree") } + if method == "click" { try ax().requireEnabled(selected) } hoverElement = selected - if method == "click" { - let names = try ax().actions(selected) - let action: String? = holdMs != nil || !modifiers.isEmpty ? nil : button == "right" && names.contains("AXShowMenu") ? "AXShowMenu" - : (button == "left" && count == 1 ? (names.contains("AXPress") ? "AXPress" : names.contains("AXPick") ? "AXPick" : nil) : nil) - if let action { - try ax().perform(selected, action) - return .result(Self.actionResult) - } - try ax().requireEnabled(selected) - } guard let bounds = try ax().bounds(selected), bounds.width > 0, bounds.height > 0 else { throw NativeFailure(code: "NATIVE_ERROR", message: "Element has no pointer bounds") } - let enclosing = try scopedWindow ?? ax().enclosingWindow(selected) window = try WindowGeometry.resolve(owner: identity, windowID: enclosing.id) { try ax().bounds(enclosing.element) } point = WindowPoint(x: bounds.x + bounds.width / 2 - window.bounds.x, y: bounds.y + bounds.height / 2 - window.bounds.y) } else { diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index d50011eb06..dd01a43b6e 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} From ecd56a18d3c8a7128772d1d4ff0e6cd2c2df0f7d Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:08:06 +0800 Subject: [PATCH 018/103] Verify and document mouse clicks separately from AX actions --- .../cua-native-platform/guide.i18n.yaml | 4 +-- .../v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../cua-native-platform/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +-- packages/experimental/cua-macos/README.md | 6 ++-- packages/experimental/cua-macos/README.zh.md | 6 ++-- .../cua-macos/native/README.i18n.yaml | 4 +-- .../experimental/cua-macos/native/README.md | 6 ++-- .../cua-macos/native/README.zh.md | 6 ++-- .../native/tests/CapabilitiesFixture.swift | 6 +++- .../native/tests/application_consent_e2e.py | 4 +-- .../native/tests/capabilities_e2e.py | 31 +++++++++++-------- .../cua-macos/native/tests/electron_e2e.py | 2 +- .../cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 16 files changed, 49 insertions(+), 40 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index 8d9654901c..a76d4de320 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: 6cabae699a340845 - zh: f2256751518c5e36 + en: b09e3dde32391786 + zh: f702e1e25b260b29 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 5023ac9ff0..3179dae0d9 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -15,7 +15,7 @@ Providers supply startup capabilities alongside their platform guidance. The nat ## Migration -1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. +1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. 2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. 4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index 880034fbd8..f0a4a905e0 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -15,7 +15,7 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 ## 迁移 -1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。 +1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 88d127489f..42e23f1df1 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: 7fdb7c0462275417 zh: 0a4a9562f4a82945 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: d80ab0362946144c - zh: 2cb9fc12bb473300 + en: 6054576016409f5d + zh: 5dc25764c92b8db2 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 311c7cce7a..4fc614c260 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -122,7 +122,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Screenshot capture requires an attachment store and a resolved model route declaring image input. The shared attachment admission validates canonical Base64, the raster and its configured capacity, then stores the image once. Native data remains available to programmatic callers; model content carries coordinate metadata and the durable image reference. Response byte limits apply before parsing. -Window clicks and mouse moves accept an element ID from the latest tree. The element must belong to the selected window. To trigger the default action of a menu item outside any window, use `app.invoke(id)`. +Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. To trigger the default action of a menu item outside any window, use `app.invoke(id)`. Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; `scroll` uses named `x` and `y`. All use pixels in the latest returned screenshot. Pass `relative: true` for integer thousandths of window width and height, from 0 to 999; omission or `false` uses pixels. Relative input can use a successful AX read or screenshot, while absolute input requires a screenshot. The Host maps the delivered image to native points, including attachment and model-request resizing. A value of 999 remains inside the window edge. Coordinate options do not apply to element IDs. A width or height change since the latest observation returns `WINDOW_CHANGED` before input, including raw coordinate calls without a snapshot ID; read fresh AX or take a new screenshot before proceeding. Window movement alone preserves window-local coordinates. Capture and pointer input reject known disagreement between the selected window’s accessibility frame and displayed bounds with `WINDOW_CHANGED`, before posting pointer events. This includes Stage Manager transformations when AX retains the full window frame. Read fresh state; any activation or window raise remains explicit. Advertised AX actions remain available. Missing AX geometry retains the AXless path and does not establish that a transformed window can be operated. @@ -130,7 +130,7 @@ Retained objects resolve the current tool binding on every call. The external ru AppKit sheets are selectable by their window IDs and remain visible in their document window’s tree. Keyboard input follows a system Open/Save panel only when the application’s focused sheet identifies one Apple panel-service window and that service still focuses the same panel. Unrelated or ambiguous remote recipients fail before dispatch. -Element clicks use opaque element IDs from the current snapshot. Left clicks support a single or double click; right and middle clicks support one. Click and drag options accept a button and modifier names; a modified click uses pointer input. Drags hold that button and carry its modifiers through every movement and release. AX text marks disabled controls, `valueWritable=true`, and available `selected` state. The helper uses an advertised accessibility action for unmodified clicks when available; pointer delivery resolves the element’s current bounds and verifies its owning window. Actions report dispatch, not application success. A visual pointer or click marker can be rendered independently of input; AX actions do not require moving the system cursor. Window-directed mouse input can still change application focus, selection or dialogs. Read state after input. `STALE_APP` requires acquiring the application again; `STALE_SNAPSHOT` requires a fresh AX read. Request timeout/cancellation waits for native acknowledgement and preserves usable handles. Missing cleanup acknowledgement closes that Agent’s connection. A screenshot RPC still awaiting its system callback occupies the single capture slot; further screenshots return `CAPTURE_BUSY`, while AX and input remain available. A late capture result is discarded, and its real completion releases that slot. Only an unresponsive operation or failed cleanup can invalidate the shared process and all its handles. Never retry uncertain input automatically. Closing an Agent releases its connection and AX references, without undoing changes to applications. +Element clicks use opaque element IDs from the current snapshot. Left clicks support a single or double click; right and middle clicks support one. Click and drag options accept a button and modifier names. Drags hold that button and carry its modifiers through every movement and release. AX text marks disabled controls, `valueWritable=true`, and available `selected` state. Actions report dispatch, not application success. A visual pointer or click marker can be rendered independently of input; AX actions do not require moving the system cursor. Window-directed mouse input can still change application focus, selection or dialogs. Read state after input. `STALE_APP` requires acquiring the application again; `STALE_SNAPSHOT` requires a fresh AX read. Request timeout/cancellation waits for native acknowledgement and preserves usable handles. Missing cleanup acknowledgement closes that Agent’s connection. A screenshot RPC still awaiting its system callback occupies the single capture slot; further screenshots return `CAPTURE_BUSY`, while AX and input remain available. A late capture result is discarded, and its real completion releases that slot. Only an unresponsive operation or failed cleanup can invalidate the shared process and all its handles. Never retry uncertain input automatically. Closing an Agent releases its connection and AX references, without undoing changes to applications. ----- @@ -175,7 +175,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 629c99c357..5e2e721984 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -122,7 +122,7 @@ void await window.getScreenshot() 截图要求附件服务可用,并确认当前模型支持图片输入。共享附件接入校验规范 Base64、图像数据及配置容量,然后保存一次图片。程序调用方仍可取得原生数据,模型内容包含坐标元数据和持久图片引用。响应字节上限在解析前执行。 -窗口的 `click` 和 `mouseMove` 接受最新树中的元素 ID。元素必须属于所选窗口。菜单项如果不属于任何窗口,可用 `app.invoke(id)` 触发默认动作。 +`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。菜单项如果不属于任何窗口,可用 `app.invoke(id)` 触发默认动作。 `mouseMove`、`click` 和 `drag` 的绝对坐标使用 `[x, y]` 元组;`scroll` 使用命名的 `x` 和 `y`。它们都使用最近返回截图中的像素。传入 `relative: true` 时使用 0~999 的千分比整数;省略或传入 `false` 时使用像素。相对坐标可基于成功的 AX 读取或截图,绝对坐标必须先截图。Host 根据实际送入模型的图片尺寸换算原生 point,包含附件归一化和模型请求阶段的缩放。999 映射到窗口边缘以内。坐标选项不适用于元素 ID。窗口宽高与最近一次观察不同时,在输入前返回 `WINDOW_CHANGED`,即使原始坐标调用不传快照 ID 也会检查;重新读取 AX 或截图后再操作。单纯移动窗口不使窗口内坐标失效。截图和鼠标输入会核对所选窗口的辅助功能框与显示边界;已知两者不一致时,在发送任何鼠标事件前返回 `WINDOW_CHANGED`。当 AX 保留完整窗口框时,这也会拦住 Stage Manager 变换后的窗口。需要重新读取状态;激活应用或抬起窗口仍须显式调用。元素声明的 AX 动作保持可用。缺少 AX 几何时保留无 AX 路径,不代表变换后的窗口一定可以操作。 @@ -130,7 +130,7 @@ void await window.getScreenshot() AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档窗口的控件树中。只有应用当前获得焦点的 sheet 指向唯一的 Apple 面板服务窗口,且该服务仍聚焦于同一面板时,键盘输入才转交系统打开或保存面板。无法确认或存在歧义的远端接收方会在输入前报错。 -元素点击使用当前快照中的不透明元素 ID。左键支持单击或双击;右键和中键支持单击。点击和拖动选项可指定按键与修饰键名称;带修饰键的点击使用指针输入。拖动期间保持指定按键,并在移动和释放事件中携带修饰键。AX 文本标明禁用控件、`valueWritable=true` 和可读取的 `selected` 状态。不带修饰键的点击优先使用元素声明的辅助功能动作;需要发送鼠标事件时,会重新读取元素位置并核实所属窗口。动作返回只表示输入已分派。可视指针或点击标记可以独立绘制;AX 动作无需移动系统指针。窗口定向鼠标输入仍可能改变应用焦点、选区或对话框。输入后需要读取状态确认结果。`STALE_APP` 需要重新获取应用,`STALE_SNAPSHOT` 需要重新读取 AX。请求超时或取消会等待原生停止确认,保留仍可用的句柄;无法确认清理完成时关闭该 Agent 的连接。未返回系统回调的截图 RPC 占用唯一捕获槽位,新截图立即返回 `CAPTURE_BUSY`,AX 和输入仍可使用。迟到图片被丢弃,真实回调结束后释放槽位。只有操作无法停止或清理失败时,才可能使共享进程及所有旧句柄失效。不能自动重试结果不确定的输入。关闭 Agent 会释放其连接和 AX 引用,但不会撤销应用中的修改。 +元素点击使用当前快照中的不透明元素 ID。左键支持单击或双击;右键和中键支持单击。点击和拖动选项可指定按键与修饰键名称。拖动期间保持指定按键,并在移动和释放事件中携带修饰键。AX 文本标明禁用控件、`valueWritable=true` 和可读取的 `selected` 状态。动作返回只表示输入已分派。可视指针或点击标记可以独立绘制;AX 动作无需移动系统指针。窗口定向鼠标输入仍可能改变应用焦点、选区或对话框。输入后需要读取状态确认结果。`STALE_APP` 需要重新获取应用,`STALE_SNAPSHOT` 需要重新读取 AX。请求超时或取消会等待原生停止确认,保留仍可用的句柄;无法确认清理完成时关闭该 Agent 的连接。未返回系统回调的截图 RPC 占用唯一捕获槽位,新截图立即返回 `CAPTURE_BUSY`,AX 和输入仍可使用。迟到图片被丢弃,真实回调结束后释放槽位。只有操作无法停止或清理失败时,才可能使共享进程及所有旧句柄失效。不能自动重试结果不确定的输入。关闭 Agent 会释放其连接和 AX 引用,但不会撤销应用中的修改。 ----- @@ -175,7 +175,7 @@ AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档 ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index baff1bc950..6ae5afb709 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 20be674c0592d66d zh: e26112b908187acc /dsh-cua-native-helper/observation-and-input: - en: bf1fa9dbe1cb6dfe - zh: 14097def08a240a4 + en: 8c8ec56eeb88dccf + zh: 4a11a9682e4caec2 /dsh-cua-native-helper/verification: en: 77b266136d5e3631 zh: a5f135e1b12f7a52 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index d6a1ba141e..57891d69b4 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -97,9 +97,9 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro `getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId`, and an opaque string `elementId`; coordinate actions require `windowId` and may include a snapshot ID from that window or an app-wide observation. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. -Element clicks without holdMs prefer advertised AX actions and otherwise use pointer delivery. Coordinate click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Modified element clicks use pointer delivery. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. No implicit fallback sends global desktop input. +Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. No implicit fallback sends global desktop input. -`click.holdMs` is an optional nonnegative integer in milliseconds per press; zero adds no hold delay. Each connection supplies `maxClickHoldMs` to bound explicit holds. The diagnostic helper option `--max-click-hold-ms` defaults to 5000. It bypasses AX actions and uses the element center or supplied coordinates. Omission retains ordinary click timing. The complete gesture holds the request scheduler slot; cancellation, timeout and disconnect interrupt the hold and post the pending mouse-up before releasing that slot. Received events remain effective, and forced process termination cannot guarantee cleanup. +`click.holdMs` is an optional nonnegative integer in milliseconds per press; zero adds no hold delay. Each connection supplies `maxClickHoldMs` to bound explicit holds. The diagnostic helper option `--max-click-hold-ms` defaults to 5000. Omission retains ordinary click timing. The complete gesture holds the request scheduler slot; cancellation, timeout and disconnect interrupt the hold and post the pending mouse-up before releasing that slot. Received events remain effective, and forced process termination cannot guarantee cleanup. Capture and pointer delivery read CG bounds before and after an exact-window AX frame query. Movement during the query returns WINDOW_CHANGED. Valid AX/CG frames must have equal outward-rounded integral point rectangles; a known mismatch returns WINDOW_CHANGED before mouse movement, priming or button delivery. The helper preserves both coordinate sources rather than substituting AX geometry for CG geometry. Missing or unusable AX geometry remains unknown, while AX communication, permission and invalid-element errors propagate. Capture without Accessibility permission retains its CG/SCK checks. Advertised AX actions bypass this pointer preflight; an AX action error does not trigger pointer input. These reads do not lock the window against later movement, and no geometry check activates or raises it. @@ -111,7 +111,7 @@ Host-only permission controls are `permissionStatus {}`, `requestPermission` and Observation reads each non-layout node’s descriptive properties and children through `AXUIElementCopyMultipleAttributeValues`. Per-attribute errors retain the individual-read rules; unsupported batch APIs use individual reads. Values are retained only during that observation, and input reads live attributes. Application state can change between nodes; a batch does not make the whole tree atomic. -System file-panel keyboard routing resolves the remote recipient through the selected app’s focused AX sheet. Only Apple’s Open and Save Panel Service is accepted, and its focused ancestry must still contain the identified remote window. Element pointer fallbacks resolve an app-owned window or sheet through AX parents when AXWindow is unavailable. Ordinary clicks retain AX action priority over pointer input; visual click markers need no system-cursor movement. +System file-panel keyboard routing resolves the remote recipient through the selected app’s focused AX sheet. Only Apple’s Open and Save Panel Service is accepted, and its focused ancestry must still contain the identified remote window. Element-targeted pointer input follows AX parents to find the enclosing window or sheet. Keyboard modifier names are plain strings. The shared object API passes the names through unchanged; the macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and rejects an unknown name with `INVALID_ARGUMENT`. It does not parse chord strings. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 2863988e66..4d27f100c5 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -97,9 +97,9 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原始元素目标要求 `appHandle`、`snapshotId` 和不透明字符串 `elementId`;坐标动作要求 `windowId`,并可携带属于该窗口或应用级观察的快照 ID。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 -未指定 holdMs 的元素点击优先使用声明的 AX 动作,否则通过鼠标事件发送。坐标点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。带修饰键的元素点击使用鼠标输入。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 +点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 -`click.holdMs` 是可选的每次按住时长,单位为毫秒,接受非负整数;0 表示不额外等待。每个连接通过 `maxClickHoldMs` 限制显式按住时长。诊断 helper 的 `--max-click-hold-ms` 选项默认 5000。指定后使用元素中心或给定坐标发送鼠标事件,跳过 AX 动作。省略时保留普通点击时长。整个手势占用请求调度槽位;取消、超时和断开连接会中断等待,在释放槽位前发送对应的松开事件。已接收的事件仍然生效,进程被强制终止时无法保证清理。 +`click.holdMs` 是可选的每次按住时长,单位为毫秒,接受非负整数;0 表示不额外等待。每个连接通过 `maxClickHoldMs` 限制显式按住时长。诊断 helper 的 `--max-click-hold-ms` 选项默认 5000。省略时保留普通点击时长。整个手势占用请求调度槽位;取消、超时和断开连接会中断等待,在释放槽位前发送对应的松开事件。已接收的事件仍然生效,进程被强制终止时无法保证清理。 截图和鼠标输入在精确窗口的 AX 边界查询前后读取 CG 边界,查询期间移动会返回 WINDOW_CHANGED。有效的 AX/CG 边界向外取整后必须一致;已知不一致会在移动、预备事件或按键发送前返回 WINDOW_CHANGED。helper 保留两个坐标来源,不用 AX 几何替换 CG 几何。缺失或无效的 AX 几何仍表示未知,AX 通信、权限和无效元素错误继续传递。无辅助功能权限的截图保留 CG/SCK 检查。声明的 AX 动作不经过鼠标预检,AX 动作失败也不改用鼠标输入。这些读取不会锁住窗口以阻止后续移动,几何检查不激活或抬起窗口。 @@ -111,7 +111,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 观察通过 `AXUIElementCopyMultipleAttributeValues` 读取每个非布局节点的描述属性和子节点。逐属性错误保留单独读取的规则;不支持批量 API 时使用单独读取。值只在本次观察期间保留,输入读取即时属性。应用状态可能在节点之间变化,批量读取不使整棵树具备原子性。 -系统文件面板的键盘路由通过所选应用的 AX 焦点 sheet 解析远端接收方。只接受 Apple 的 Open and Save Panel Service,且其焦点祖先链仍须包含已识别的远端窗口。AXWindow 不可用时,元素鼠标后备路径沿 AX 父节点解析应用所属窗口或 sheet。普通点击保持 AX 动作优先,可视点击标记不需要系统鼠标移动。 +系统文件面板的键盘路由通过所选应用的 AX 焦点 sheet 解析远端接收方。只接受 Apple 的 Open and Save Panel Service,且其焦点祖先链仍须包含已识别的远端窗口。按元素发送鼠标事件时,helper 沿 AX 父节点查找所属窗口或 sheet。 键盘修饰键名称是普通字符串。共享对象 API 原样传递名称;macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,未知名称返回 `INVALID_ARGUMENT`。它不解析组合键字符串。 diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 8e621fd014..5382155260 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -4,9 +4,11 @@ import AppKit final class CapabilityPad: NSView { var received: ((NSEvent) -> Void)? var pressed: (() -> Void)? + var showMenu: (() -> Void)? override func isAccessibilityElement() -> Bool { true } override func accessibilityRole() -> NSAccessibility.Role? { .button } override func accessibilityPerformPress() -> Bool { pressed?(); return true } + override func accessibilityPerformShowMenu() -> Bool { showMenu?(); return true } override var isFlipped: Bool { true } override var acceptsFirstResponder: Bool { true } override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } @@ -46,6 +48,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega var pad: CapabilityPad! var events: [[String: Any]] = [] var axPresses = 0 + var axMenus = 0 init(statePath: String) { self.statePath = statePath } func applicationDidFinishLaunching(_ notification: Notification) { let bar = NSMenu() @@ -77,6 +80,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega pad = CapabilityPad(frame: NSRect(x: 20, y: 25, width: 600, height: 170)) pad.setAccessibilityTitle("Input receiver") pad.pressed = { [weak self] in self?.axPresses += 1; self?.persist() } + pad.showMenu = { [weak self] in self?.axMenus += 1; self?.persist() } pad.received = { [weak self] event in guard let self else { return } var value: [String: Any] = ["type": event.type.rawValue, "timestamp": event.timestamp, "flags": event.modifierFlags.rawValue, @@ -119,7 +123,7 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega let result: [String: Any] = ["pid": ProcessInfo.processInfo.processIdentifier, "windowId": window.windowNumber, "active": NSApplication.shared.isActive, "keyWindow": window.isKeyWindow, "textFocused": window.firstResponder === text, "pasteAttempts": pasteAttempts, - "text": text.string, "selection": [selection.location, selection.length], "runs": runs, "events": events, "axPresses": axPresses, + "text": text.string, "selection": [selection.location, selection.length], "runs": runs, "events": events, "axPresses": axPresses, "axMenus": axMenus, "pad": [frame.minX, window.frame.height - frame.maxY, frame.width, frame.height]] try! JSONSerialization.data(withJSONObject: result).write(to: URL(fileURLWithPath: statePath), options: .atomic) } diff --git a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py index f2579584b1..10a193d5f2 100644 --- a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py +++ b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py @@ -44,7 +44,7 @@ def main(): owner = {"appHandle": app["appHandle"], "windowId": state["windowId"]} observed = helper.call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) pad = next(item for item in observed["elements"] if item["role"] == "AXButton" and item["title"] == "Input receiver") - helper.call("click", {"appHandle": app["appHandle"], "snapshotId": observed["snapshotId"], "elementId": pad["elementId"]}) + helper.call("invoke", {**owner, "snapshotId": observed["snapshotId"], "elementId": pad["elementId"]}) wait_for_state(state_path, lambda value: value["axPresses"] == state["axPresses"] + 1) captured = helper.call("screenshot", owner) assert base64.b64decode(captured["data"], validate=True).startswith(b"\x89PNG\r\n\x1a\n") @@ -184,7 +184,7 @@ def main(): os.kill(pid, 0) print(f"Deleted executable: bundle_id={bundle_id is not None}, proc_pidpath_bytes={copied}, errno={path_error}") print("PASS: changed bundles cannot launch; cold/running and direct-bundle identities agree; copies share consent; other IDs stay separate; missing IDs and standalone GUIs use persistent paths across restarts" - + (f"; {checked_windows} GUI instances expose controls, receive an AX click and produce a PNG" if args.desktop else "")) + + (f"; {checked_windows} GUI instances expose controls, receive a default AX action and produce a PNG" if args.desktop else "")) if __name__ == "__main__": diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index aaf9cd03e7..650aff14e9 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -46,19 +46,24 @@ def stop_application(pid): raise AssertionError("fixture did not exit after SIGTERM") -def check_click_holds(helper, owner, window, point, state_file): - observed = helper.call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) +def check_clicks(helper, window, point, state_file): + observed = helper.call("getState", {**window, "maxElements": 2000, "maxDepth": 25}) pad = next(item for item in observed["elements"] if item["role"] == "AXButton" and item["title"] == "Input receiver") - target = {**owner, "snapshotId": observed["snapshotId"], "elementId": pad["elementId"]} + target = {**window, "snapshotId": observed["snapshotId"], "elementId": pad["elementId"]} state = json.loads(state_file.read_text()) - presses = state["axPresses"] - helper.call("click", target) - state = wait_for_state(state_file, lambda value: value["axPresses"] == presses + 1) count = len(state["events"]) + presses, menus = state["axPresses"], state["axMenus"] + assert {"AXPress", "AXShowMenu"}.issubset(helper.call("listActions", target)) + helper.call("invoke", target) + state = wait_for_state(state_file, lambda value: value["axPresses"] == presses + 1) + helper.call("performAction", {**target, "action": "AXShowMenu"}) + state = wait_for_state(state_file, lambda value: value["axMenus"] == menus + 1) + assert len(state["events"]) == count, state for invalid in [-1, 1.5, 5001, "800", None]: helper.call("click", {**target, "holdMs": invalid}, "INVALID_ARGUMENT") - assert json.loads(state_file.read_text())["axPresses"] == presses + 1 - for params, types in [({**target, "holdMs": 0}, [1, 2]), + for params, types in [(target, [1, 2]), ({**target, "mouseButton": "right"}, [3, 4]), + ({**window, **point}, [1, 2]), + ({**target, "holdMs": 0}, [1, 2]), ({**target, "holdMs": 150}, [1, 2]), ({**window, **point, "holdMs": 150, "mouseButton": "right"}, [3, 4]), ({**window, **point, "holdMs": 150, "mouseButton": "middle"}, [25, 26]), @@ -68,8 +73,8 @@ def check_click_holds(helper, owner, window, point, state_file): events = state["events"][count:] assert [event["type"] for event in events] == types, events for index in range(0, len(events), 2): - assert events[index + 1]["timestamp"] - events[index]["timestamp"] >= params["holdMs"] / 1000, events - assert state["axPresses"] == presses + 1, state + assert events[index + 1]["timestamp"] - events[index]["timestamp"] >= params.get("holdMs", 0) / 1000, events + assert (state["axPresses"], state["axMenus"]) == (presses + 1, menus + 1), state count += len(types) # Production cancellation travels directly over the socket; the diagnostic stdio proxy exchanges whole requests. key = hashlib.sha256(Path(helper.process.args[0]).read_bytes()).hexdigest() @@ -77,7 +82,7 @@ def check_click_holds(helper, owner, window, point, state_file): for ending in ["cancel", "timeout", "disconnect"]: connection = Connection(socket_path, key, maxClickHoldMs=7000, timeoutMs=2000 if ending == "timeout" else 30000) try: - app = connection.call("getApp", {"selector": str(observed["pid"])}) + app = connection.call("getApp", {"selector": str(state["pid"])}) connection.call("getState", {"appHandle": app["appHandle"], "windowId": window["windowId"], "maxElements": 2000, "maxDepth": 25}) params = {**window, **point, "appHandle": app["appHandle"], "holdMs": 6000} @@ -104,7 +109,7 @@ def check_click_holds(helper, owner, window, point, state_file): connection.close() connection = Connection(socket_path, key, maxClickHoldMs=0) try: - app = connection.call("getApp", {"selector": str(observed["pid"])}) + app = connection.call("getApp", {"selector": str(state["pid"])}) connection.call("getState", {"appHandle": app["appHandle"], "windowId": window["windowId"], "maxElements": 2000, "maxDepth": 25}) count = len(state["events"]) @@ -189,7 +194,7 @@ def main(): call("pressKey", {**owner, "key": "KP_0"}) call("pressKey", {**owner, "key": "KP_Enter"}) state = wait_for_state(state_file, lambda value: {82, 76}.issubset({event.get("keyCode") for event in value["events"]})) - state = check_click_holds(helper, owner, window, point, state_file) + state = check_clicks(helper, window, point, state_file) if args.artifacts: args.artifacts.mkdir(parents=True, exist_ok=True) shot = call("screenshot", window) diff --git a/packages/experimental/cua-macos/native/tests/electron_e2e.py b/packages/experimental/cua-macos/native/tests/electron_e2e.py index d23eb17ebd..0e2b966516 100644 --- a/packages/experimental/cua-macos/native/tests/electron_e2e.py +++ b/packages/experimental/cua-macos/native/tests/electron_e2e.py @@ -99,7 +99,7 @@ def main(): window = next(window for window in state['windows'] if window['windowId'] == window_id) if not args.hover_only: - call('click', {**owner, 'snapshotId': state['snapshotId'], 'elementId': buttons[0]['elementId']}) + call('invoke', {**owner, 'snapshotId': state['snapshotId'], 'elementId': buttons[0]['elementId']}) wait_state(lambda actual: actual['clicks'] == 1 and actual['lastClickTrusted'] is True, 'Native AX press did not produce one trusted DOM click') state = observe() diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index cd615392cd..9aed9a4161 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index cf3c4797fb..677eb6406d 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index a2b412b5ff..a138bad2ce 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For click and mouseMove, use window coordinates or an element ID from the latest tree that belongs to the selected window. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. From 5d0ffe3c995b5fdd9c3696c68c2f44e8b7b2ce47 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:10:51 +0800 Subject: [PATCH 019/103] Invoke the system Open panel button through its default action --- packages/experimental/cua-macos/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../cua-macos/native/tests/application_consent_e2e.py | 6 +++--- packages/experimental/cua-macos/native/tests/e2e.py | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 42e23f1df1..af699d02ba 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: 7fdb7c0462275417 zh: 0a4a9562f4a82945 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 6054576016409f5d - zh: 5dc25764c92b8db2 + en: 7a9e7a28f05a6937 + zh: c4d2494da7cf5d08 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 4fc614c260..339ac3a448 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -122,7 +122,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Screenshot capture requires an attachment store and a resolved model route declaring image input. The shared attachment admission validates canonical Base64, the raster and its configured capacity, then stores the image once. Native data remains available to programmatic callers; model content carries coordinate metadata and the durable image reference. Response byte limits apply before parsing. -Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. To trigger the default action of a menu item outside any window, use `app.invoke(id)`. +Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. Use `invoke(id)` to activate a control through accessibility, for example the Open button in a system file panel or a menu item in the app tree. Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; `scroll` uses named `x` and `y`. All use pixels in the latest returned screenshot. Pass `relative: true` for integer thousandths of window width and height, from 0 to 999; omission or `false` uses pixels. Relative input can use a successful AX read or screenshot, while absolute input requires a screenshot. The Host maps the delivered image to native points, including attachment and model-request resizing. A value of 999 remains inside the window edge. Coordinate options do not apply to element IDs. A width or height change since the latest observation returns `WINDOW_CHANGED` before input, including raw coordinate calls without a snapshot ID; read fresh AX or take a new screenshot before proceeding. Window movement alone preserves window-local coordinates. Capture and pointer input reject known disagreement between the selected window’s accessibility frame and displayed bounds with `WINDOW_CHANGED`, before posting pointer events. This includes Stage Manager transformations when AX retains the full window frame. Read fresh state; any activation or window raise remains explicit. Advertised AX actions remain available. Missing AX geometry retains the AXless path and does not establish that a transformed window can be operated. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 5e2e721984..52b12e5c39 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -122,7 +122,7 @@ void await window.getScreenshot() 截图要求附件服务可用,并确认当前模型支持图片输入。共享附件接入校验规范 Base64、图像数据及配置容量,然后保存一次图片。程序调用方仍可取得原生数据,模型内容包含坐标元数据和持久图片引用。响应字节上限在解析前执行。 -`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。菜单项如果不属于任何窗口,可用 `app.invoke(id)` 触发默认动作。 +`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。要通过辅助功能触发控件的默认动作,可用 `invoke(id)`,例如系统文件面板的“打开”按钮,或应用树中的菜单项。 `mouseMove`、`click` 和 `drag` 的绝对坐标使用 `[x, y]` 元组;`scroll` 使用命名的 `x` 和 `y`。它们都使用最近返回截图中的像素。传入 `relative: true` 时使用 0~999 的千分比整数;省略或传入 `false` 时使用像素。相对坐标可基于成功的 AX 读取或截图,绝对坐标必须先截图。Host 根据实际送入模型的图片尺寸换算原生 point,包含附件归一化和模型请求阶段的缩放。999 映射到窗口边缘以内。坐标选项不适用于元素 ID。窗口宽高与最近一次观察不同时,在输入前返回 `WINDOW_CHANGED`,即使原始坐标调用不传快照 ID 也会检查;重新读取 AX 或截图后再操作。单纯移动窗口不使窗口内坐标失效。截图和鼠标输入会核对所选窗口的辅助功能框与显示边界;已知两者不一致时,在发送任何鼠标事件前返回 `WINDOW_CHANGED`。当 AX 保留完整窗口框时,这也会拦住 Stage Manager 变换后的窗口。需要重新读取状态;激活应用或抬起窗口仍须显式调用。元素声明的 AX 动作保持可用。缺少 AX 几何时保留无 AX 路径,不代表变换后的窗口一定可以操作。 diff --git a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py index 10a193d5f2..e8b2b25be8 100644 --- a/packages/experimental/cua-macos/native/tests/application_consent_e2e.py +++ b/packages/experimental/cua-macos/native/tests/application_consent_e2e.py @@ -14,13 +14,13 @@ import tempfile import uuid from capabilities_e2e import stop_application, wait_for_state -from native_test_support import BINARY, ROOT, NativeHelper, stop +from native_test_support import ROOT, NativeHelper, stop def main(): parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--helper", type=Path, default=BINARY) - parser.add_argument("--desktop", action="store_true", help="Read, click and capture owned fixture windows; requires existing system grants") + parser.add_argument("--helper", type=Path) + parser.add_argument("--desktop", action="store_true", help="Read owned fixture windows, invoke their buttons and capture them; requires existing system grants") args = parser.parse_args() transcript = [] with tempfile.TemporaryDirectory(prefix="dsh-cua-consent-") as temporary, ExitStack() as cleanup: diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index e7e40f5c73..94eb893f74 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -76,7 +76,7 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state and any(e["identifier"] == "OKButton" and e["enabled"] for e in observed["elements"]), "Go to folder did not select the requested file") open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton") - call("click", {**owner, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]}) + assert call("invoke", {**owner, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] wait_state(lambda state: bool(state["selectedFile"]) and Path(state["selectedFile"]).samefile(selected_file), "File picker did not return the intended file") # AppKit can retain the dismissed panel's hidden WindowServer window after From 84c760f2050a993be3ec7057672fc597a8187633 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:33:59 +0800 Subject: [PATCH 020/103] Describe macOS mouse dispatch on the click method itself --- packages/experimental/cua-macos/README.md | 4 ++-- packages/experimental/cua-macos/README.zh.md | 4 ++-- packages/experimental/cua-macos/src/guidance.ts | 2 +- packages/experimental/cua/README.i18n.yaml | 4 ++-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/types.ts | 6 +++--- snapshots/session/cua-native/system-prompt.expected.md | 4 ++-- snapshots/session/cua-ptc/system-prompt.expected.md | 4 ++-- .../session/ptc-script-retained/system-prompt.expected.md | 4 ++-- 11 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 339ac3a448..2d5e828514 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -175,7 +175,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -210,7 +210,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 52b12e5c39..f0303b499c 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -175,7 +175,7 @@ AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档 ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -210,7 +210,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index dd01a43b6e..6624bde4b7 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index f4abb13c43..dd3c6d217a 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ba1f8e6ae51f69d7 - zh: 8f4fde9857bae319 + en: d0088d2ec1ab8cf2 + zh: d927289a63d7a564 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index c95e4ae8ec..365c549650 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -43,7 +43,7 @@ Application consent precedes launch, observation, capture, and input. Session ac Actions return a `dispatched` boolean; `mouseMove` also reports `hoverRoute` and `systemPointerMoved`, and `show()` adds `windowId` and `foregroundChanged`. Read fresh state to verify the result. Screenshots and pointer actions are available only on explicit window objects. Coordinate actions default to pixels in the latest returned screenshot; `relative: true` accepts integers from 0 to 999 after a successful window observation. Values are divided by 1000 and scaled to the window dimensions, then clamped inside the window. The Host resolves attachment normalization and the selected model route’s image projection before returning the screenshot, then converts input to the provider’s native window coordinates. Resizing invalidates the screenshot mapping; `SCREENSHOT_REQUIRED` requires a new screenshot for absolute coordinates. Resizing rejects old coordinates with `WINDOW_CHANGED`; movement alone preserves window-local coordinates. -`click(target, { holdMs: 800 })` holds the mouse button for 800 milliseconds before release. `holdMs` applies only to `click`; it accepts nonnegative integers and applies to each press of a double-click; zero releases without an additional hold. The provider config `maxClickHoldMs` limits explicit holds and defaults to 5000 ms. Explicit holds use pointer input; omission preserves ordinary click behavior. The operation deadline includes the hold, and cancellation or timeout releases the button. Received input cannot be undone; forced helper termination cannot guarantee release. +`click(target, { holdMs: 800 })` holds the mouse button for 800 milliseconds before release. `holdMs` applies only to `click`; it accepts nonnegative integers and applies to each press of a double-click; zero releases without an additional hold. The provider config `maxClickHoldMs` limits explicit holds and defaults to 5000 ms. On macOS, both ordinary and held clicks send mouse events at the element center or the supplied point. Use `invoke(id)` for the default accessibility action. The operation deadline includes the hold, and cancellation or timeout releases the button. Received input cannot be undone; forced helper termination cannot guarantee release. ### Permission controls diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c1c5ed863c..b64c445c44 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -43,7 +43,7 @@ kind: "package-reference" 动作返回 `dispatched` 布尔值;`mouseMove` 还会返回 `hoverRoute` 和 `systemPointerMoved`,`show()` 还会返回 `windowId` 和 `foregroundChanged`。请读取新状态以验证结果。截图和指针操作只能通过显式窗口对象使用。坐标操作默认使用最近返回截图中的像素;成功观察窗口后,传入 `relative: true` 可使用 0~999 的整数坐标。数值除以 1000 后按窗口尺寸缩放,并限制在窗口内。Host 在返回截图前解析附件归一化和当前模型的图片缩放规则,再将输入换算为提供方的原生窗口坐标。窗口尺寸变化会使截图映射失效,绝对坐标遇到 `SCREENSHOT_REQUIRED` 时需要重新截图。窗口缩放后以 `WINDOW_CHANGED` 拒绝旧坐标;单纯移动窗口不改变窗口内坐标。 -`click(target, { holdMs: 800 })` 按住鼠标按钮 800 毫秒后松开。`holdMs` 仅适用于 `click`;它接受非负整数,双击时应用于每次按下;0 表示按下后立即松开,不额外等待。提供方配置 `maxClickHoldMs` 限制显式按住时长,默认 5000 毫秒。指定时长后使用鼠标事件;省略时保留普通点击行为。按住时间计入操作超时,取消或超时会松开按钮。已接收的输入无法撤销;辅助进程被强制终止时无法保证松开。 +`click(target, { holdMs: 800 })` 按住鼠标按钮 800 毫秒后松开。`holdMs` 仅适用于 `click`;它接受非负整数,双击时应用于每次按下;0 表示按下后立即松开,不额外等待。提供方配置 `maxClickHoldMs` 限制显式按住时长,默认 5000 毫秒。在 macOS 上,无论是否指定按住时长,点击都会向元素中心或给定坐标发送鼠标事件。要执行控件的默认辅助功能动作,请用 `invoke(id)`。按住时间计入操作超时,取消或超时会松开按钮。已接收的输入无法撤销;辅助进程被强制终止时无法保证松开。 ### 权限控件 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 93947ad32c..adf62b8b5e 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -33,7 +33,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index c059a546f2..b44e8f4ef6 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -79,7 +79,6 @@ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. * holdMs is a nonnegative integer in milliseconds, limited by maxClickHoldMs; zero releases immediately. - * Explicit holds use pointer input; omission preserves ordinary clicks. */ export type CuaClickOptions = Pick, 'mouseButton' | 'clickCount' | 'modifiers' | 'holdMs'> & CuaCoordinateOptions /** One same-window drag; omitted button is left and omitted modifiers are empty. */ @@ -201,9 +200,10 @@ export interface CuaWindow extends CuaSurface { */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions): Promise /** - * Click a current element id or screenshot-local point. + * Click an element or a point in this window. On macOS both forms send mouse-down and mouse-up events. + * Use {@link CuaSurface.invoke} for the element's default accessibility action. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. - * @param target - element id or [x,y]. + * @param target - On macOS, an id from the latest tree targets the element center. A coordinate pair targets the given point. * @param options - button, click count, modifiers, optional hold duration and coordinate mode. * @returns dispatch evidence. */ diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 9aed9a4161..b34c3def7c 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -68,7 +68,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 677eb6406d..00451355c7 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -70,7 +70,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index a138bad2ce..b2abdbb7e7 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. click sends mouse events at window coordinates or at the center of an element from the latest tree in that window. Use invoke for the default accessibility action, including on menu items. mouseMove accepts either target. getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -70,7 +70,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. From 7557dda6fffe6215c62b6c1eca8fdc6fdcf99f4a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:43:03 +0800 Subject: [PATCH 021/103] Explain how to recover from macOS pointer target mismatches --- .../experimental/cua-macos/README.i18n.yaml | 4 +-- packages/experimental/cua-macos/README.md | 4 +-- packages/experimental/cua-macos/README.zh.md | 4 +-- .../cua-macos/native/README.i18n.yaml | 8 ++--- .../experimental/cua-macos/native/README.md | 4 +-- .../cua-macos/native/README.zh.md | 4 +-- .../native/Sources/CuaNative/AXAccess.swift | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 4 +-- .../cua-macos/native/tests/e2e.py | 30 +++++++++++++------ .../experimental/cua-macos/src/guidance.ts | 2 +- .../cua-native/system-prompt.expected.md | 2 +- .../cua-native/workspace/native-helper.mjs | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 14 files changed, 43 insertions(+), 31 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index af699d02ba..76c65f408d 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: 7fdb7c0462275417 zh: 0a4a9562f4a82945 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 7a9e7a28f05a6937 - zh: c4d2494da7cf5d08 + en: 740031b2bf73b350 + zh: 30c4929c5bb6baeb /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 2d5e828514..7a96cac17e 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -128,7 +128,7 @@ Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; ` Retained objects resolve the current tool binding on every call. The external runtime owns persistence, imports, cancellation and completion-value serialization. Screenshots return encoded bytes with their MIME type, pixel dimensions and window ID; the standard tool pipeline admits the image attachment exactly once. `emit: false` suppresses facade output only. A host that uses another dispatcher can build objects through `createCuaApi` from `./api`. -AppKit sheets are selectable by their window IDs and remain visible in their document window’s tree. Keyboard input follows a system Open/Save panel only when the application’s focused sheet identifies one Apple panel-service window and that service still focuses the same panel. Unrelated or ambiguous remote recipients fail before dispatch. +An AppKit sheet can appear in its document window’s tree with a separate window ID. For pointer input on the sheet, use `app.getWindow(sheetId)` and an element ID from that window’s tree. Keyboard input follows a system Open/Save panel only when the application’s focused sheet identifies one Apple panel-service window and that service still focuses the same panel. Unrelated or ambiguous remote recipients fail before dispatch. Element clicks use opaque element IDs from the current snapshot. Left clicks support a single or double click; right and middle clicks support one. Click and drag options accept a button and modifier names. Drags hold that button and carry its modifiers through every movement and release. AX text marks disabled controls, `valueWritable=true`, and available `selected` state. Actions report dispatch, not application success. A visual pointer or click marker can be rendered independently of input; AX actions do not require moving the system cursor. Window-directed mouse input can still change application focus, selection or dialogs. Read state after input. `STALE_APP` requires acquiring the application again; `STALE_SNAPSHOT` requires a fresh AX read. Request timeout/cancellation waits for native acknowledgement and preserves usable handles. Missing cleanup acknowledgement closes that Agent’s connection. A screenshot RPC still awaiting its system callback occupies the single capture slot; further screenshots return `CAPTURE_BUSY`, while AX and input remain available. A late capture result is discarded, and its real completion releases that slot. Only an unresponsive operation or failed cleanup can invalidate the shared process and all its handles. Never retry uncertain input automatically. Closing an Agent releases its connection and AX references, without undoing changes to applications. @@ -175,7 +175,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f0303b499c..ca39bab33c 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -128,7 +128,7 @@ void await window.getScreenshot() 保留的对象会在每次调用时获取当前工具绑定。外部运行时负责持久化、导入、取消和最终表达式值的序列化。截图返回编码字节及其 MIME 类型、像素尺寸和窗口 ID,标准工具链负责将图片作为附件传递一次。`emit: false` 只控制对象层的输出。使用其他分派器的宿主可以通过 `./api` 的 `createCuaApi` 创建对象。 -AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档窗口的控件树中。只有应用当前获得焦点的 sheet 指向唯一的 Apple 面板服务窗口,且该服务仍聚焦于同一面板时,键盘输入才转交系统打开或保存面板。无法确认或存在歧义的远端接收方会在输入前报错。 +AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID。对 sheet 发送鼠标输入时,先用 `app.getWindow(sheetId)` 选择它,再使用该窗口树中的元素 ID。只有应用当前获得焦点的 sheet 指向唯一的 Apple 面板服务窗口,且该服务仍聚焦于同一面板时,键盘输入才转交系统打开或保存面板。无法确认或存在歧义的远端接收方会在输入前报错。 元素点击使用当前快照中的不透明元素 ID。左键支持单击或双击;右键和中键支持单击。点击和拖动选项可指定按键与修饰键名称。拖动期间保持指定按键,并在移动和释放事件中携带修饰键。AX 文本标明禁用控件、`valueWritable=true` 和可读取的 `selected` 状态。动作返回只表示输入已分派。可视指针或点击标记可以独立绘制;AX 动作无需移动系统指针。窗口定向鼠标输入仍可能改变应用焦点、选区或对话框。输入后需要读取状态确认结果。`STALE_APP` 需要重新获取应用,`STALE_SNAPSHOT` 需要重新读取 AX。请求超时或取消会等待原生停止确认,保留仍可用的句柄;无法确认清理完成时关闭该 Agent 的连接。未返回系统回调的截图 RPC 占用唯一捕获槽位,新截图立即返回 `CAPTURE_BUSY`,AX 和输入仍可使用。迟到图片被丢弃,真实回调结束后释放槽位。只有操作无法停止或清理失败时,才可能使共享进程及所有旧句柄失效。不能自动重试结果不确定的输入。关闭 Agent 会释放其连接和 AX 引用,但不会撤销应用中的修改。 @@ -175,7 +175,7 @@ AppKit sheet 可以通过其窗口 ID 单独选择,也会出现在所属文档 ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 6ae5afb709..89135ddfbe 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,11 +21,11 @@ en: 20be674c0592d66d zh: e26112b908187acc /dsh-cua-native-helper/observation-and-input: - en: 8c8ec56eeb88dccf - zh: 4a11a9682e4caec2 + en: 2408e0c0e9c873a2 + zh: e06236fc32efc4fa /dsh-cua-native-helper/verification: - en: 77b266136d5e3631 - zh: a5f135e1b12f7a52 + en: 49f4cce2a4cc3114 + zh: e9d65c92ef35fe24 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 57891d69b4..c01b273d1b 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -95,7 +95,7 @@ Protocol declarations are generated from [the shared protocol](../../cua/src/pro ## Observation and input -`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId`, and an opaque string `elementId`; coordinate actions require `windowId` and may include a snapshot ID from that window or an app-wide observation. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. +`getState` optionally scopes AX traversal to an owned window or nested sheet `windowId`. A new or failed refresh invalidates the previous snapshot for that app/window scope, while other window scopes remain usable. When an owned CG window has no matching AX surface, getState returns a new snapshot with empty tree/elements and no truncation; its coordinates and screenshots remain available. It rechecks process lifetime, window ownership, the unlocked session and Accessibility permission after traversal. Window-discovery APIDisabled and communication errors remain failures; unsupported or absent optional AX attributes can produce an empty observation. Missing or foreign-owned windows never produce an empty success. An AX element invalidated during traversal rejects the whole read with `STALE_SNAPSHOT`; no partial snapshot is published. Callers may read again after the application changes, without repeating input. Raw element targets require `appHandle`, `snapshotId` and an opaque string `elementId`. For `click` and `mouseMove`, the optional `windowId` must match both the snapshot scope (unless app-wide) and the element’s enclosing window or sheet. A mismatch returns `STALE_SNAPSHOT` before dispatch. Coordinate targets use `windowId`, `x` and `y` and may include a snapshot from that window or the app. Mixing an element ID with coordinates returns `INVALID_ARGUMENT`. The Host converts relative coordinates before dispatch, so the native JSONL protocol rejects the `relative` field. Native references never cross JSON. Window-list refresh releases snapshots for closed windows. Native process identity, snapshot generation, and window ownership checks do not lock the desktop against simultaneous user or application changes. Clicks send mouse-down and mouse-up events at the element center or the supplied coordinates. Use `invoke` for the default AX action or `performAction` for a named action. Click, scroll and drag validate window ownership and bounds, then use background PID/window-directed primitives. Each event uses SkyLight when available, otherwise the public PID-targeted API. A posted event is never repeated through the other API. Coordinates are macOS points from the top-left of the entire window, including its title bar. Positive `deltaLinesY` reveals content above; negative reveals below. Positive `deltaLinesX` reveals content left; negative reveals right. Each axis accepts an integer from -10 to 10, and at least one must be nonzero. The helper sends line-unit scroll events directly. Click and drag accept left/right/middle buttons and command/control/option/shift/fn modifiers. Only left clicks support double-click. Drag uses one button press/move/release in one window; callers explicitly supply durationMs (1..5000) and steps (1..240). The movement delay budget is divided with fractional precision across the segments; fixed press/release settling and scheduler latency are additional. No implicit fallback sends global desktop input. @@ -147,7 +147,7 @@ Run `python3 packages/experimental/cua-macos/native/tests/axless_e2e.py` after b Run `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence` to compare complete observations of the same owned AppKit window with 35 and 400 synthetic rows. Each helper receives one warmup and three alternating measured requests. All result fields must match except helper-generated app and snapshot IDs. The report keeps raw timings, byte counts, hashes and replies; it sets no CI speed threshold and makes no memory claim. Fixture startup can activate the application. Run without other desktop automation or compilation jobs. -Use `--panels-only` to isolate the system file-panel checks. Fixture windows can join application sets so Stage Manager does not shrink them during background input. Use `--hover-only` with `e2e.py` or `electron_e2e.py` to verify hover independently of keyboard and file-panel scenarios. Add `--alternate-hover` to `e2e.py` for AX reveal, descendant entry, click and exit with sampled system-pointer stability. `--input-overlays` verifies that pass-through overlays allow hover and input-blocking overlays reject it without moving the pointer. +Use `--panels-only` to verify that a document-window request for a sheet control reports its sheet ID and that the control can be read from the selected sheet. Fixture windows can join application sets so Stage Manager does not shrink them during background input. Use `--hover-only` with `e2e.py` or `electron_e2e.py` to verify hover independently of keyboard and file-panel scenarios. Add `--alternate-hover` to `e2e.py` for AX reveal, descendant entry, click and exit with sampled system-pointer stability. `--input-overlays` verifies that pass-through overlays allow hover and input-blocking overlays reject it without moving the pointer. Run `python3 packages/experimental/cua-macos/native/tests/e2e.py` after building to exercise an isolated two-window AppKit fixture. It independently records button counts, Unicode text, actual scroll position, right-click callbacks, and drag release position. Scroll, right-button down/up, and drag down/up counters must each increase exactly once per requested gesture. The check also verifies a real NSOpenPanel sheet, path-entry keyboard routing and the selected file URL. It covers scoped snapshot replacement, screenshot dimensions, stale app cleanup and EOF shutdown. `--artifacts DIRECTORY` writes fixture-only screenshots and a private protocol transcript; the transcript contains the running-app inventory and is not a publication artifact. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 4d27f100c5..307d2eaee8 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -95,7 +95,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 ## 观察与输入 -`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原始元素目标要求 `appHandle`、`snapshotId` 和不透明字符串 `elementId`;坐标动作要求 `windowId`,并可携带属于该窗口或应用级观察的快照 ID。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 +`getState` 可将 AX 遍历限定到应用所属窗口或嵌套 sheet 的 `windowId`。新的刷新或失败的刷新使同一应用/窗口范围的旧快照失效,其他窗口范围仍可使用。应用所属 CG 窗口没有匹配 AX 界面时,getState 返回空 tree/elements、truncated 为 false 的新快照,仍可截图和坐标输入。遍历后重新检查进程生命期、窗口归属、会话未锁定及辅助功能权限。窗口发现中的 APIDisabled 和通信错误仍会失败;不支持或缺失的可选 AX 属性可以产生空观察。不存在或属于其他应用的窗口不会返回空成功结果。遍历中 AX 元素失效会以 `STALE_SNAPSHOT` 拒绝整次读取,不发布部分树。应用变化后可以重新观察,但不重复输入。原生元素目标需要 `appHandle`、`snapshotId` 和字符串 `elementId`。`click` 和 `mouseMove` 可附带 `windowId`。它必须与元素所属窗口或 sheet 一致,对窗口级快照还必须与快照的窗口一致,否则在发送输入前返回 `STALE_SNAPSHOT`。坐标目标使用 `windowId`、`x`、`y`,可以附带来自该窗口或应用的快照。混用元素 ID 和坐标会返回 `INVALID_ARGUMENT`。Host 在发送请求前换算相对坐标,原生 JSONL 协议会拒绝 `relative` 字段。原生引用不跨 JSON 传递。刷新窗口列表会释放已关闭窗口的快照。进程身份、快照代次和窗口归属检查不会锁住桌面,用户或应用仍可同时改变状态。 点击在元素中心或给定坐标发送鼠标按下和抬起事件。执行默认 AX 动作用 `invoke`,执行指定动作用 `performAction`。点击、滚动和拖动核实窗口归属和边界后,使用后台 PID/窗口定向输入。事件优先使用 SkyLight,不可用时使用公开的 PID 定向 API;已发送的事件不通过另一 API 重发。坐标是整个窗口左上角起算的 macOS point,包含标题栏。`deltaLinesY` 为正时显示上方内容,为负时显示下方内容;`deltaLinesX` 为正时显示左侧内容,为负时显示右侧内容。每个轴接受 -10 到 10 的整数,至少一个轴非零。helper 直接发送按行计量的滚轮事件。点击和拖动支持左、右、中键及 command/control/option/shift/fn 修饰键,只有左键支持双击。拖动在一个窗口中完成一次按下、移动、抬起,调用方显式提供 durationMs(1..5000)和 steps(1..240)。移动延迟按小数精度分配到各段,按下和抬起的固定等待及调度延迟另计。不存在隐式改用全局桌面输入的后备路径。 @@ -147,7 +147,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 运行 `python3 packages/experimental/cua-macos/native/tests/observation_benchmark.py --reference-helper /absolute/reference --candidate-helper /absolute/candidate --artifacts /private/evidence`,对比同一自建 AppKit 窗口中 35 行和 400 行合成内容的完整观察。每个 helper 先预热一次,再交替测量三次。除 helper 生成的应用和快照 ID 外,结果字段必须一致。报告保留原始耗时、字节数、哈希和回复,不设置 CI 性能阈值,也不声称内存表现。fixture 启动可能激活应用。运行时避免其他桌面自动化或编译任务。 -使用 `--panels-only` 单独检查系统文件面板。fixture 窗口可加入应用集合,避免 Stage Manager 在后台输入时缩小它们。使用 `e2e.py` 或 `electron_e2e.py` 的 `--hover-only`,可独立于键盘和文件面板场景验证悬停。为 `e2e.py` 加上 `--alternate-hover` 可验证 AX 展开、进入子控件、点击和移出,并采样确认系统指针不变。`--input-overlays` 验证穿透鼠标的覆盖窗口允许悬停、拦截输入的覆盖窗口拒绝悬停且不移动指针。 +使用 `--panels-only` 验证通过文档窗口操作 sheet 控件时会返回该 sheet 的窗口 ID,并验证选择 sheet 后能读取该控件。fixture 窗口可加入应用集合,避免 Stage Manager 在后台输入时缩小它们。使用 `e2e.py` 或 `electron_e2e.py` 的 `--hover-only`,可独立于键盘和文件面板场景验证悬停。为 `e2e.py` 加上 `--alternate-hover` 可验证 AX 展开、进入子控件、点击和移出,并采样确认系统指针不变。`--input-overlays` 验证穿透鼠标的覆盖窗口允许悬停、拦截输入的覆盖窗口拒绝悬停且不移动指针。 构建后运行 `python3 packages/experimental/cua-macos/native/tests/e2e.py`,操作一个隔离的双窗口 AppKit fixture。fixture 独立记录按钮计数、Unicode 文本、实际滚动位置、右键回调和拖动释放位置。滚动、右键按下/抬起和拖动按下/抬起计数每次手势必须恰好增加一次。检查还验证真实 NSOpenPanel sheet、路径输入的键盘路由和选中文件 URL,并覆盖范围内快照替换、截图尺寸、过期应用清理和 EOF 退出。`--artifacts DIRECTORY` 写出仅包含 fixture 的截图和私有协议记录;协议记录包含运行中应用清单,不用于公开发布。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 50c8bd3a64..1a1e4f595b 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -652,7 +652,7 @@ final class AXAccess { } current = try self.element(node, "AXParent") } - throw NativeFailure(code: "WINDOW_UNAVAILABLE", message: "Element has no app-owned window or sheet; refresh getAccessibilityTree") + throw NativeFailure(code: "WINDOW_UNAVAILABLE", message: "Pointer input requires an enclosing window or sheet. For a menu item’s default action, use app.invoke(id)") } func keyboardRecipient(_ owner: ProcessIdentity, catalog: ApplicationCatalogSnapshot) throws -> ProcessIdentity { var current = try element(AXUIElementCreateApplication(owner.pid), "AXFocusedWindow") diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index ba16630e6a..ea58f27f7e 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -155,8 +155,8 @@ actor AXWorker { private func coordinateSnapshot(_ handle: String, _ params: RequestParameters, _ windowID: UInt32) throws { guard let id = try params.optionalString("snapshotId") else { return } let value = try snapshot(handle, id) - guard value.scope.windowID == nil || value.scope.windowID == windowID else { - throw NativeFailure(code: "STALE_SNAPSHOT", message: "Snapshot belongs to another window") + if let source = value.scope.windowID, source != windowID { + throw NativeFailure(code: "STALE_SNAPSHOT", message: "Snapshot belongs to window \(source); read getAccessibilityTree on window \(windowID)") } } private func coordinateWindow(_ identity: ProcessIdentity, _ windowID: UInt32, trace: ScreenshotTrace? = nil) throws -> WindowInfo { diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 94eb893f74..92fd5bed9f 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -43,12 +43,18 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state raise AssertionError(description + ": " + observed["tree"]) time.sleep(0.025) - sheet = wait_observation(lambda observed: any(e["identifier"] == "open-panel" for e in observed["elements"]), - "File panel did not appear") - sheet_id = sheet["focusedWindowId"] - assert sheet_id != primary["windowId"], sheet + document = wait_observation(lambda observed: any(e["identifier"] == "OKButton" for e in observed["elements"]), + "File panel control did not appear in the document tree", primary_params) + sheet_id = document["focusedWindowId"] + assert sheet_id is not None and sheet_id != primary["windowId"], document + button = next(e for e in document["elements"] if e["identifier"] == "OKButton") + for method in ("click", "mouseMove"): + error = call(method, {**owner, "windowId": primary["windowId"], "snapshotId": document["snapshotId"], + "elementId": button["elementId"]}, "STALE_SNAPSHOT") + assert f"window {sheet_id}; select that window" in error["message"], error scoped = call("getState", {**primary_params, "windowId": sheet_id}) assert any(e["role"] == "AXSheet" for e in scoped["elements"]), scoped + assert any(e["identifier"] == "OKButton" for e in scoped["elements"]), scoped assert "Increment primary" not in scoped["tree"], scoped panel = next(e for e in scoped["elements"] if e["identifier"] == "open-panel") call("performAction", {**owner, "snapshotId": scoped["snapshotId"], "elementId": panel["elementId"], "action": "AXRaise"}) @@ -74,9 +80,9 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state call("pressKey", {**owner, "key": "Return"}) ready = wait_observation(lambda observed: not any(e["identifier"] == "PathTextField" for e in observed["elements"]) and any(e["identifier"] == "OKButton" and e["enabled"] for e in observed["elements"]), - "Go to folder did not select the requested file") + "Go to folder did not select the requested file", {**primary_params, "windowId": sheet_id}) open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton") - assert call("invoke", {**owner, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] + assert call("invoke", {**owner, "windowId": sheet_id, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] wait_state(lambda state: bool(state["selectedFile"]) and Path(state["selectedFile"]).samefile(selected_file), "File picker did not return the intended file") # AppKit can retain the dismissed panel's hidden WindowServer window after @@ -161,12 +167,18 @@ def main(): target = {**button_target(first, "Increment primary"), "windowId": primary["windowId"]} app_state = call("getState", {**owner, "maxElements": 300, "maxDepth": 20}) other_button = button_target(app_state, "Increment secondary") + menu_item = next(e for e in first["elements"] if e["role"] == "AXMenuBarItem") for method in ("click", "mouseMove"): + windowless = call(method, {**target, "elementId": menu_item["elementId"]}, "WINDOW_UNAVAILABLE") + assert "app.invoke(id)" in windowless["message"], windowless unknown = call(method, {**target, "elementId": "9999"}, "INVALID_ARGUMENT") assert "elementId is absent" in unknown["message"], unknown - call(method, {**target, "x": 0, "y": 0}, "INVALID_ARGUMENT") - call(method, {**target, "relative": True}, "INVALID_ARGUMENT") - call(method, {**target, "windowId": secondary["windowId"]}, "STALE_SNAPSHOT") + combined = call(method, {**target, "x": 0, "y": 0}, "INVALID_ARGUMENT") + assert combined["message"] == "Element and coordinate targets cannot be combined", combined + raw_relative = call(method, {**target, "relative": True}, "INVALID_ARGUMENT") + assert raw_relative["message"] == "Unknown operation parameter", raw_relative + stale = call(method, {**target, "windowId": secondary["windowId"]}, "STALE_SNAPSHOT") + assert f'read getAccessibilityTree on window {secondary["windowId"]}' in stale["message"], stale call(method, {**other_button, "windowId": primary["windowId"]}, "STALE_SNAPSHOT") call("click", target) wait_state(lambda state: state["count"] == 1, "primary click was not received exactly once") diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 6624bde4b7..e2127a78ab 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index b34c3def7c..6e32a6a9d3 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 494e7d2c1a..b10d4793e0 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -197,7 +197,7 @@ function createApplicationState(socket, record, application, captureBroker, conn ? snapshots.get(params.windowId) ?? snapshots.get(null) : [...snapshots.values()].find(snapshot => snapshot.snapshotId === params.snapshotId) if (!observed) refuse('STALE_SNAPSHOT', 'Read fresh state before acting') - if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', 'Snapshot belongs to another window') + if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', `Snapshot belongs to window ${observed.windowId}; read getAccessibilityTree on window ${params.windowId}`) if (observed.axless && params.elementId !== undefined) refuse('INVALID_ARGUMENT', 'Element id is absent from the selected snapshot') if (method === 'mouseMove') application.hovering = params.elementId === '0' || (params.x >= 20 && params.x <= 40) else if (method === 'click' && params.windowId === 8) application.visualCount++ diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 00451355c7..81450a3782 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index b2abdbb7e7..743dd9cc1f 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. From d17fad9b9ee150e5b1372af2f7c06776568fc726 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 14:43:56 +0800 Subject: [PATCH 022/103] fix(agent): classify closed admission and document migration --- docs/subsystems/core.i18n.yaml | 4 ++-- docs/subsystems/core.md | 12 +++++++----- docs/subsystems/core.zh.md | 12 +++++++----- .../agent-closed-admission/guide.i18n.yaml | 16 ++++++++++++++++ .../v0.2.2-rc.1/agent-closed-admission/guide.md | 17 +++++++++++++++++ .../agent-closed-admission/guide.zh.md | 17 +++++++++++++++++ packages/core/agent-loop/src/index.ts | 7 ++----- packages/core/agent-loop/tests/cancel.spec.ts | 2 +- .../tests/fixtures/serial-created.mjs | 9 +++------ .../agent-loop/tests/input-lifecycle.spec.ts | 17 ++++++++++++----- packages/core/agent/README.i18n.yaml | 4 ++-- packages/core/agent/README.md | 2 ++ packages/core/agent/README.zh.md | 2 ++ packages/core/agent/src/closed-error.ts | 8 ++++---- packages/core/agent/src/runtime-types.ts | 10 +++++----- packages/sdk/server/src/server.ts | 5 ++--- packages/subagent/subagent/src/manager.ts | 3 +-- scripts/smoke-python-runtime.py | 1 - .../python-sdk-single-exe/advanced/result.json | 8 ++++---- .../advanced/session.1.v4.jsonl | 4 ++-- .../advanced/session.2.v4.jsonl | 4 ++-- 21 files changed, 110 insertions(+), 54 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 363584a5fd..c3495dec81 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,8 +12,8 @@ en: d71c669c1a36bf52 zh: 9b335f90c84a894e /core/the-agent-handle: - en: 6ee15fec81bc0686 - zh: b6f3fcd48823ea75 + en: bb0aec7a50800c1e + zh: a58a3392368f644a /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 7b8503cb1a..7e86e6e0d1 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -98,7 +98,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -113,7 +113,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -121,7 +121,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -131,7 +131,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -142,7 +142,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -374,6 +374,8 @@ The cause is a TypeScript-enforced same-process input. An active cancellation ho The [event taxonomy](../architecture.md#events) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits. +`AgentClosedError` extends `HarnessError` with code `AGENT_CLOSED` and the affected `agentId`. Admission closes when the caller cancels creation, the Agent starts disposal, or its factory begins shutdown. The creation signal stops governing admission after creation succeeds. + ## Initiating Agent The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules. diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index 9f0bf51061..c82be05f03 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -102,7 +102,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -117,7 +117,7 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -125,7 +125,7 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -135,7 +135,7 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -146,7 +146,7 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -380,6 +380,8 @@ cause 是由 TypeScript 强制约束的同进程输入。活跃的取消持有 +`AgentClosedError` 继承 `HarnessError`,包含错误码 `AGENT_CLOSED` 和受影响的 `agentId`。调用方取消创建、Agent 开始释放或工厂开始关闭时,Agent 停止接纳新工作。创建成功后,创建信号不再控制工作接纳。 + ## 发起 Agent `ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;[initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.zh.md)定义其生命周期和作用域规则。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml new file mode 100644 index 0000000000..83fa03b9c8 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md +/: + en: e4666ee6e813e7a3 + zh: ab68705b61d0da3c +/handle-agent-input-rejected-during-shutdown: + en: 5ec42a6575141728 + zh: a5174b0e04526c58 +/handle-agent-input-rejected-during-shutdown/change: + en: def59fb50e36f026 + zh: 91e79aad0ea758ad +/handle-agent-input-rejected-during-shutdown/migration: + en: e4c7ffd0e06c01bf + zh: 7fc1f43747209fb7 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md new file mode 100644 index 0000000000..7aaff2efc6 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Agent input and maintenance methods throw AgentClosedError once the Agent stops accepting new work." +--- + +# Handle Agent input rejected during shutdown + +English | [中文](guide.zh.md) + +## Change + +In v0.2.2-rc.1, a retained `Agent` could accept input while teardown was in progress. The Agent now rejects new input and maintenance work with `AgentClosedError` as soon as its lifetime is aborted. It can still appear in the registry while admitted work settles. + +## Migration + +1. In extensions that call `Agent.send`, `followup`, `steer`, `inject`, or `runMaintenance`, handle the synchronous `AgentClosedError` from `@deepseek-ai/dsh-agent` at the call site. Treat code `AGENT_CLOSED` as an unavailable Agent and preserve handling for other failures. +2. Verify by disposing an Agent with a maintenance task still settling. A subsequent input call throws `AgentClosedError` without adding an inbox entry. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md new file mode 100644 index 0000000000..9ee1eb17a1 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md @@ -0,0 +1,17 @@ +--- +kind: upgrade-guide +description: "Agent 停止接纳新工作后,输入和维护方法会抛出 AgentClosedError。" +--- + +# 处理关闭期间被拒绝的 Agent 输入 + +[English](guide.md) | 中文 + +## 变更 + +在 v0.2.2-rc.1 中,调用方持有的 `Agent` 在清理过程中仍可能接收输入。现在,Agent 的生命周期信号一旦中止,就会以 `AgentClosedError` 拒绝新输入和维护工作。已接纳的工作收尾期间,注册表中仍可能找到该 Agent。 + +## 迁移 + +1. 若扩展调用 `Agent.send`、`followup`、`steer`、`inject` 或 `runMaintenance`,请在调用处处理从 `@deepseek-ai/dsh-agent` 导出的同步异常 `AgentClosedError`。收到 `AGENT_CLOSED` 时按 Agent 不可用处理,保留其他失败的处理逻辑。 +2. 在维护任务尚未结束时开始释放 Agent 以验证改动。之后调用输入方法应抛出 `AgentClosedError`,且不向 inbox 添加条目。 diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index a0b02d4eee..ecdafadb9d 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -469,11 +469,8 @@ export class AgentLoop extends Service implements AgentFactory { const id = session.id const loopCtx = this.runtime.ctx - // Deactivation fuses three owners, each with its own reason: the caller's - // cancellation signal, the owner fiber's unload, and factory teardown. - // It is registered BEFORE any resource exists, over mutable slots, so an - // unload arriving while the scope is still minting finds a working - // disposer instead of a leak. + // The caller's signal governs creation. Owner disposal and factory + // shutdown can end the Agent's lifetime both during and after creation. const abort = new AbortController() const onCallerAbort = (): void => { abort.abort(callerSignal?.reason instanceof Error diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 2ca5eb0299..434857afe9 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -324,7 +324,7 @@ describe('Agent.cancel()', () => { send(agent, 'active') await streaming.promise const disposal = handle.dispose() - expect(() =>{ send(agent, 'late wake') }).toThrow(AgentClosedError) + expect(() => { send(agent, 'late wake') }).toThrow(AgentClosedError) await disposal expect(adapter.requests).toHaveLength(1) diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 1295611023..2b27a7f33b 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,11 +6,11 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx, config = {}) { +export function apply(ctx) { const checkedCancellation = new WeakSet() ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { if (checkedCancellation.has(agent) - || (config.checkRootCancellation !== true && agent.session.header.origin !== 'subagent')) return next() + || agent.session.header.origin !== 'subagent') return next() checkedCancellation.add(agent) const pending = { id: randomUUID(), role: 'user', @@ -35,10 +35,7 @@ export function apply(ctx, config = {}) { agent.inbox.remove(pending.id) for (const message of messages) { const ordinary = message.source.kind === 'user' - const restored = message.source.kind === `plugin:${name}` - ? { ...message, content: [{ type: 'text', text: message.content[0].text + ' Queue-clear failures still cancel active work.' }] } - : message - agent.send(restored, ordinary ? 'next-turn' : 'next-step', ordinary) + agent.send(message, ordinary ? 'next-turn' : 'next-step', ordinary) } return next() }) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 560fea3ca1..3e9bb2cf10 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import AgentRegistry, { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -52,7 +52,6 @@ async function harness() { return { ctx, root, adapter, handle, agent: handle.agent } } - it('cancellation still aborts the running request when queue clearing fails', async () => { const { ctx, agent } = await harness() const entered = Promise.withResolvers() @@ -73,6 +72,7 @@ it('cancellation still aborts the running request when queue clearing fails', as }) expect(() => { agent.cancel({ kind: 'user' }) }).toThrow('injected queue clear failure') expect(signal.aborted).toBe(true) + expect(agent.inbox.nextTurn).toEqual([queued]) } finally { stopRejecting() hold() @@ -82,7 +82,6 @@ it('cancellation still aborts the running request when queue clearing fails', as } }) - it('an Agent still in the registry rejects new input while its owner is closing', async () => { const { ctx, agent, handle } = await harness() const release = Promise.withResolvers() @@ -96,6 +95,16 @@ it('an Agent still in the registry rejects new input while its owner is closing' await aborted.promise expect(ctx.agents.get(agent.id)).toBe(agent) const message = input('during closing') + const error = vi.fn((failure: unknown) => failure) + try { + agent.followup(message) + } catch (failure) { + error(failure) + } + expect(error).toHaveBeenCalledWith(expect.objectContaining({ + name: 'AgentClosedError', code: 'AGENT_CLOSED', agentId: agent.id, + })) + expect(error.mock.calls[0]?.[0]).toBeInstanceOf(HarnessError) for (const submit of [() => { agent.followup(message) }, () => { agent.steer(message) }, () => { agent.inject(message) }, () => { agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => { agent.inbox.append('next-turn', message) }, () => { agent.inbox.prepend('next-step', message) }, () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { expect(submit).toThrow(AgentClosedError) } @@ -108,8 +117,6 @@ it('an Agent still in the registry rejects new input while its owner is closing' } }) - - it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { const { ctx, agent, handle } = await harness() const release = Promise.withResolvers() diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index df3e29c8a9..6c21a72d7d 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -27,8 +27,8 @@ en: ff2b530bb20bcfe2 zh: 4f9024c4881a4ba5 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: - en: 2594a1e02adea801 - zh: cae8860369728efb + en: cec57f2cb7ab3a5c + zh: 2896b42eb5310441 /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: en: 371511fb13093dd2 zh: 4be81d246cf299b2 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 9772578fcc..024f69aeef 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -73,6 +73,8 @@ await handle.agent.whenIdle() `Agent.ctx` is the agent's scoped context: registrations made through it (tools, prompt sections, variables, event listeners, restrictions) apply to that agent alone and unwind on disposal. The same mechanism is what agent presets use to give one session a different capability set without affecting its neighbors. +Input and maintenance methods reject closed Agents with `AgentClosedError` (`AGENT_CLOSED`). See [Agent lifetime and admission](../../../docs/subsystems/core.md#the-agent-handle) for the lifecycle rules. + ### Intercept or observe work in flight `agent/request` is deprecated and retained for existing listeners. Do not add new listeners. Provider, model, and optional explicit reasoning effort are fixed at step preparation; listeners must preserve all three, including an absent effort. `AgentOptions.maxTokens` sets the output cap. Other per-request control overrides have no replacement API. See the [migration guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.md) for affected callers. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index b5b2af52d4..693ad615ce 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -73,6 +73,8 @@ await handle.agent.whenIdle() `Agent.ctx` 是该 agent 的作用域上下文:通过它进行的注册(工具、提示词段、变量、事件监听器、限制)只对该 agent 生效,并在 dispose(资源释放)时全部撤销。同一机制也是 agent preset 用来让一个会话获得不同能力集、同时不影响其邻居的方式。 +输入和维护方法会以 `AgentClosedError`(`AGENT_CLOSED`)拒绝已停止接纳新工作的 Agent。生命周期规则见 [Agent 句柄](../../../docs/subsystems/core.zh.md#the-agent-handle)。 + ### 拦截或观察进行中的工作 `agent/request` 已弃用,仅为现有监听器保留。不要添加新监听器。提供方、模型和可选的显式推理强度在步骤准备时固定;监听器必须保留三者,包括未指定强度的状态。`AgentOptions.maxTokens` 设置输出上限。其他逐请求控制参数覆盖没有替代 API。受影响的调用方参见[迁移指南](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.zh.md)。 diff --git a/packages/core/agent/src/closed-error.ts b/packages/core/agent/src/closed-error.ts index abcb335320..a4ca452887 100644 --- a/packages/core/agent/src/closed-error.ts +++ b/packages/core/agent/src/closed-error.ts @@ -1,15 +1,15 @@ /** Rejection of new work after an Agent starts closing. @module @deepseek-ai/dsh-agent/closed-error */ +import { HarnessError } from '@deepseek-ai/dsh-llm' import type { SessionId } from '@deepseek-ai/dsh-session' -/** An Agent has stopped accepting new input and maintenance work. */ -export class AgentClosedError extends Error { +/** An Agent has stopped accepting new input and maintenance work (`AGENT_CLOSED`). */ +export class AgentClosedError extends HarnessError { /** * @param agentId - closing Agent identity. * @param options - original lifecycle cancellation, when available. */ constructor(readonly agentId: SessionId, options?: ErrorOptions) { - super(`agent "${agentId}" is closing`, options) - this.name = 'AgentClosedError' + super(`agent "${agentId}" is closing`, 'AGENT_CLOSED', options) } } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index aa5efe6d0a..39b15064dc 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -226,7 +226,7 @@ declare module './types.ts' { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError after disposal begins, or an Error when another activity owns the agent. + * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -241,7 +241,7 @@ declare module './types.ts' { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -249,7 +249,7 @@ declare module './types.ts' { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -259,7 +259,7 @@ declare module './types.ts' { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -270,7 +270,7 @@ declare module './types.ts' { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError after disposal begins; no input is inserted. + * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index bccfa6634e..46cda8d44b 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -263,9 +263,8 @@ export class HarnessSdkJsonRpcServer { if (!this.initialized) throw new Error('SDK server is not initialized') const rec = await this.getOrCreateSession(params.sessionId) this.lifetime.signal.throwIfAborted() - // An agent-loop-only reload disposes the loop's agents while this record - // survives; a retained agent accepts followup() silently, so validate the - // record against the live registry before delivery. + // An agent-loop reload can dispose the Agent while the SDK still retains + // this record. Reject stale records before admitting prompt attachments. this.assertLiveAgent(rec, params.sessionId) const content = await durablePromptContent(this.ctx, params.contentBlocks) this.lifetime.signal.throwIfAborted() diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index f4a2a3d652..1f9108edae 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -10,8 +10,7 @@ import { randomUUID } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' -import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' -import { AgentClosedError } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent, type AgentOptions, type CreateAgentOptions } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' diff --git a/scripts/smoke-python-runtime.py b/scripts/smoke-python-runtime.py index d9baf1d7f9..92611f23bc 100644 --- a/scripts/smoke-python-runtime.py +++ b/scripts/smoke-python-runtime.py @@ -1787,7 +1787,6 @@ def smoke_sdk_snapshot_mode( {"insert": [{ "id": "serial-created-fixture", "name": str(Path(__file__).resolve().parents[1] / "packages/core/agent-loop/tests/fixtures/serial-created.mjs"), - "config": {"checkRootCancellation": False}, }]}, ]) with DeepSeekHarness( diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/result.json b/scripts/snapshots/python-sdk-single-exe/advanced/result.json index c5568f5a18..8aaf44b0b6 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/result.json +++ b/scripts/snapshots/python-sdk-single-exe/advanced/result.json @@ -2941,7 +2941,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -3127,7 +3127,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -3967,7 +3967,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { @@ -4149,7 +4149,7 @@ "content": [ { "type": "text", - "text": "Serial agent creation completed. Queue-clear failures still cancel active work." + "text": "Serial agent creation completed." } ], "source": { diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl index 1a64fcd142..ee9fbfd3cb 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.1.v4.jsonl @@ -10,7 +10,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} @@ -18,7 +18,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly DIRECT_CHILD_OK and nothing else."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} diff --git a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl index 7f4bf22ad4..6fb5ebae1f 100644 --- a/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl +++ b/scripts/snapshots/python-sdk-single-exe/advanced/session.2.v4.jsonl @@ -10,7 +10,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} -{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"}]}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} {"type":"turn/start","data":{"turn":2}} @@ -18,7 +18,7 @@ {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} {"type":"step/start","data":{"turn":2,"step":1}} {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{messageId}}"}},"surfaceOp":"append"} -{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Queue-clear failures still cancel active work."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} +{"type":"user/message","data":{"id":"{{messageId}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly WORKFLOW_CHILD_OK and nothing else."}],"source":{"kind":"user"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"smoke-model","reasoningEffort":"high","maxTokens":256000},"adapterDefaults":{"maxTokens":true},"tools":["cordis_inspect_list","cordis_inspect_query","job_kill","job_list","job_output","snapshot_double","subagent","workflow","working_directory"]},"reason":"initial"}} From 3b677fdf1a448dc184779a095790170ead64405d Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:44:04 +0800 Subject: [PATCH 023/103] Exercise stale window recovery through the CUA object API --- .../experimental/cua-macos/tests/loader-composition.spec.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/experimental/cua-macos/tests/loader-composition.spec.ts b/packages/experimental/cua-macos/tests/loader-composition.spec.ts index cfd7fe4883..e92f138d87 100644 --- a/packages/experimental/cua-macos/tests/loader-composition.spec.ts +++ b/packages/experimental/cua-macos/tests/loader-composition.spec.ts @@ -181,6 +181,11 @@ it.skipIf(process.platform === 'win32')('shares one application between retained const screenshot = await peerWindow.getScreenshot({ emit: false }) expect(screenshot).toMatchObject({ mimeType: 'image/png', pixelWidth: 1, pixelHeight: 1, windowId: 7 }) expect(Buffer.from(screenshot.bytes).toString('base64')).toBe(png) + await peerApp.getWindow(8) + const recovery = 'Snapshot belongs to window 8; read getAccessibilityTree on window 7' + await expect(peerWindow.click(element('0'))).rejects.toThrow(recovery) + await expect(peerWindow.mouseMove(element('0'))).rejects.toThrow(recovery) + expect(await peerWindow.getAccessibilityTree({ emit: false })).toContain('Count: 1') await peerWindow.click(element('0')) expect(await retainedWindow.getAccessibilityTree({ emit: false })).toContain('Count: 2') const sharedEvents = await readEvents() From 84bd8fd7bafb0bfaaa00515c4a9be6686b03e954 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:46:50 +0800 Subject: [PATCH 024/103] Check the file panel after its Open button becomes actionable --- .../cua-macos/native/tests/e2e.py | 31 ++++++++++--------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 92fd5bed9f..830f767d80 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -43,18 +43,12 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state raise AssertionError(description + ": " + observed["tree"]) time.sleep(0.025) - document = wait_observation(lambda observed: any(e["identifier"] == "OKButton" for e in observed["elements"]), - "File panel control did not appear in the document tree", primary_params) - sheet_id = document["focusedWindowId"] - assert sheet_id is not None and sheet_id != primary["windowId"], document - button = next(e for e in document["elements"] if e["identifier"] == "OKButton") - for method in ("click", "mouseMove"): - error = call(method, {**owner, "windowId": primary["windowId"], "snapshotId": document["snapshotId"], - "elementId": button["elementId"]}, "STALE_SNAPSHOT") - assert f"window {sheet_id}; select that window" in error["message"], error + sheet = wait_observation(lambda observed: any(e["identifier"] == "open-panel" for e in observed["elements"]), + "File panel did not appear") + sheet_id = sheet["focusedWindowId"] + assert sheet_id is not None and sheet_id != primary["windowId"], sheet scoped = call("getState", {**primary_params, "windowId": sheet_id}) assert any(e["role"] == "AXSheet" for e in scoped["elements"]), scoped - assert any(e["identifier"] == "OKButton" for e in scoped["elements"]), scoped assert "Increment primary" not in scoped["tree"], scoped panel = next(e for e in scoped["elements"] if e["identifier"] == "open-panel") call("performAction", {**owner, "snapshotId": scoped["snapshotId"], "elementId": panel["elementId"], "action": "AXRaise"}) @@ -78,10 +72,19 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state wait_observation(lambda observed: any(e["identifier"] == "PathTextField" and e["value"] == str(selected_file) for e in observed["elements"]), "Panel text input did not arrive") call("pressKey", {**owner, "key": "Return"}) - ready = wait_observation(lambda observed: not any(e["identifier"] == "PathTextField" for e in observed["elements"]) - and any(e["identifier"] == "OKButton" and e["enabled"] for e in observed["elements"]), - "Go to folder did not select the requested file", {**primary_params, "windowId": sheet_id}) - open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton") + def open_button_ready(observed): + return (not any(e["identifier"] == "PathTextField" for e in observed["elements"]) + and any(e["identifier"] == "OKButton" and e["enabled"] for e in observed["elements"])) + + document = wait_observation(open_button_ready, "Selected file did not enable Open in the document tree", + {**primary_params, "maxElements": 2000, "maxDepth": 25}) + button = next(e for e in document["elements"] if e["identifier"] == "OKButton") + for method in ("click", "mouseMove"): + error = call(method, {**owner, "windowId": primary["windowId"], "snapshotId": document["snapshotId"], + "elementId": button["elementId"]}, "STALE_SNAPSHOT") + assert f"window {sheet_id}; select that window" in error["message"], error + ready = call("getState", {**owner, "windowId": sheet_id, "maxElements": 2000, "maxDepth": 25}) + open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton" and e["enabled"]) assert call("invoke", {**owner, "windowId": sheet_id, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] wait_state(lambda state: bool(state["selectedFile"]) and Path(state["selectedFile"]).samefile(selected_file), "File picker did not return the intended file") From eba321d9185bd7d5d3c4dddd64744c0a0feb8860 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 14:48:28 +0800 Subject: [PATCH 025/103] Open the fixture sheet through its button action before testing pointer scope --- packages/experimental/cua-macos/native/tests/e2e.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 830f767d80..95776b4031 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -20,7 +20,7 @@ from native_test_support import ROOT, NativeHelper, line, run_cleanup, stop def check_file_panel(call, owner, primary_params, primary, directory, wait_state, button_target): selected_file = Path(directory) / "sheet-target.txt" selected_file.write_text("Owned file picker fixture\n") - call("click", button_target(call("getState", primary_params), "Open fixture file")) + assert call("invoke", button_target(call("getState", primary_params), "Open fixture file"))["dispatched"] # A remote AX traversal can consume the helper's 15-second response budget. # Allow two completed observations rather than timing out after the first. From ad5fab1a1c57323920355b1280cfbe543517bb84 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 15:10:01 +0800 Subject: [PATCH 026/103] fix(agent): contain input rejection during shutdown --- .../goal/goal-round-driver/README.i18n.yaml | 4 ++-- packages/goal/goal-round-driver/README.md | 2 +- packages/goal/goal-round-driver/README.zh.md | 2 +- packages/goal/goal-round-driver/src/index.ts | 3 ++- .../tests/goal-round-driver.spec.ts | 16 +++++++++++++++- .../session/working-directory/README.i18n.yaml | 4 ++-- packages/session/working-directory/README.md | 2 +- .../session/working-directory/README.zh.md | 2 +- .../session/working-directory/src/index.ts | 3 ++- .../tests/working-directory.spec.ts | 18 ++++++++++++++++++ 10 files changed, 45 insertions(+), 11 deletions(-) diff --git a/packages/goal/goal-round-driver/README.i18n.yaml b/packages/goal/goal-round-driver/README.i18n.yaml index 19e3ebc68a..18af868300 100644 --- a/packages/goal/goal-round-driver/README.i18n.yaml +++ b/packages/goal/goal-round-driver/README.i18n.yaml @@ -24,8 +24,8 @@ en: a1312339977f1127 zh: 57450327ff7e7d83 /deepseek-ai-dsh-goal-round-driver/use-this-package/when-continuation-stops: - en: f3cb23a11176dc4f - zh: de7aa54d5c93445d + en: 7c4d150d79e55ba4 + zh: be24cd1956894787 /deepseek-ai-dsh-goal-round-driver/use-this-package/after-resume-fork-or-unload: en: 85d5470b1b330330 zh: e761f9046ba7af8a diff --git a/packages/goal/goal-round-driver/README.md b/packages/goal/goal-round-driver/README.md index 1302bc6fdc..2998c3f8fe 100644 --- a/packages/goal/goal-round-driver/README.md +++ b/packages/goal/goal-round-driver/README.md @@ -50,7 +50,7 @@ With an exact live agent idle, an active armed goal, and remaining capacity, the ### When continuation stops -A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. +A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. If Agent shutdown rejects a queued round, the goal stays active. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. ### After resume, fork, or unload diff --git a/packages/goal/goal-round-driver/README.zh.md b/packages/goal/goal-round-driver/README.zh.md index 05905c7043..65cc9c1b77 100644 --- a/packages/goal/goal-round-driver/README.zh.md +++ b/packages/goal/goal-round-driver/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" ### 何时停止续行 -Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 +Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 关闭期间拒绝轮次入队时,goal 保持 active。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 ### resume、fork 或卸载之后 diff --git a/packages/goal/goal-round-driver/src/index.ts b/packages/goal/goal-round-driver/src/index.ts index d3ddfda4cc..461a874f08 100644 --- a/packages/goal/goal-round-driver/src/index.ts +++ b/packages/goal/goal-round-driver/src/index.ts @@ -6,7 +6,7 @@ import { isDeepStrictEqual } from 'node:util' import { FiberState } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' -import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent' import type { GoalMessageSource, GoalRef, GoalView } from '@deepseek-ai/dsh-goal' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -208,6 +208,7 @@ export function apply(ctx: Context): void { agent.followup(message) } catch (error: unknown) { state.attempt = undefined + if (error instanceof AgentClosedError) return ctx.logger.warn(`goal-round-driver: could not queue round ${round} for agent "${agent.id}": ${renderThrown(error)}`) const latest = currentGoal(state) if (latest !== undefined && latest.id === goal.id && latest.revision === goal.revision diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index d9f97df07d..c9be135ea1 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' -import { agentEvents } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' @@ -727,6 +727,20 @@ describe('same-session goal driving', () => { expect(goal?.roundsStarted).toBe(1) }) + it('keeps the goal active when the Agent closes before queue admission', async () => { + const test = await harness([]) + const admission = Promise.withResolvers() + vi.spyOn(test.agent, 'followup').mockImplementation(() => { + admission.resolve(undefined) + throw new AgentClosedError(test.agent.id) + }) + test.ctx.goals.create(test.agent, { objective: 'resume after shutdown' }) + await admission.promise + + expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', roundsStarted: 0 }) + expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/blocked')).toBe(false) + }) + it('blocks the goal when a custom agent rejects the otherwise valid follow-up', async () => { const test = await harness([]) // Reject only the goal-sourced round follow-up, not the state-change injection diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index fd50066fe2..4ed48e75cc 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: e65405026debde7c zh: e12a648eb10ed16b /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: f0458147d29631b1 - zh: 6a288670dd084ffb + en: c0681d6879ece29d + zh: 42bf039fc1bbdaf5 /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 44ed9ba9dc..9506cfa788 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory. It warns unless the Agent is closing. The next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 9561d73972..1df1f5673b 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录。Agent 正在关闭时无需告警。下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index 62c3750c2c..be0c9e5187 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -7,7 +7,7 @@ import { isAbsolute } from 'node:path' import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' -import type { Agent } from '@deepseek-ai/dsh-agent' +import { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' @@ -217,6 +217,7 @@ export class WorkingDirectoryService extends Service { try { agent.inject(notice) } catch (error) { + if (error instanceof AgentClosedError) return this.ctx.logger.warn(`working-directory: committed ${JSON.stringify(directory)}, but could not queue its notice: ${String(error)}`) } } diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index 22fb99af47..d05bf06f10 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import WorkingDirectory, { type Config as WorkingDirectoryConfig } from '@deepseek-ai/dsh-working-directory' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -314,6 +315,23 @@ describe('Session working directories', () => { } }) + it('keeps the committed directory when the Agent closes before accepting its notice', async () => { + await using f = await fixture() + const child = join(f.root, 'child') + await mkdir(child) + const inject = vi.spyOn(f.agent, 'inject').mockImplementation(() => { throw new AgentClosedError(f.agent.id) }) + const warn = vi.spyOn(f.ctx.logger, 'warn') + try { + await expect(f.ctx.workingDirectory.set(f.agent, child)).resolves.toBe(child) + expect(f.ctx.workingDirectory.get(f.agent.session)).toBe(child) + expect(inject).toHaveBeenCalledOnce() + expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('could not queue its notice')) + } finally { + inject.mockRestore() + warn.mockRestore() + } + }) + it('returns committed state and warns when the notice cannot be queued', async () => { await using f = await fixture() const child = join(f.root, 'child') From 43b006af2a7eedfcedda8838a8bf2da844764fbe Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 15:17:46 +0800 Subject: [PATCH 027/103] test(goal): assert the durable blocking operation --- packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index c9be135ea1..35b2d0c3ee 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -738,7 +738,7 @@ describe('same-session goal driving', () => { await admission.promise expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', roundsStarted: 0 }) - expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/blocked')).toBe(false) + expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/change' && event.data.operation === 'block')).toBe(false) }) it('blocks the goal when a custom agent rejects the otherwise valid follow-up', async () => { From 09b90ed11272465df53a5aa7f988ba41e515b7c8 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:20:30 +0800 Subject: [PATCH 028/103] Keep macOS hover off the system pointer by default and route file panel clicks --- .../2026-10-13-cua-continuous-hover.i18n.yaml | 4 +- .../2026-10-13-cua-continuous-hover.md | 2 +- .../2026-10-13-cua-continuous-hover.zh.md | 2 +- ...cua-hover-routes-and-coordinates.i18n.yaml | 4 +- ...-10-13-cua-hover-routes-and-coordinates.md | 2 +- ...-13-cua-hover-routes-and-coordinates.zh.md | 2 +- docs/config-catalog.md | 2 + docs/config-catalog.zh.md | 2 + .../cua-hover-ax-only/guide.i18n.yaml | 16 ++++++ .../v0.2.2-rc.1/cua-hover-ax-only/guide.md | 18 ++++++ .../v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md | 18 ++++++ .../experimental/cua-macos/README.i18n.yaml | 8 +-- packages/experimental/cua-macos/README.md | 13 +++-- packages/experimental/cua-macos/README.zh.md | 13 +++-- .../cua-macos/native/README.i18n.yaml | 8 +-- .../experimental/cua-macos/native/README.md | 8 +-- .../cua-macos/native/README.zh.md | 8 +-- .../native/Sources/CuaNative/AXAccess.swift | 56 +++++++++++-------- .../native/Sources/CuaNative/AXHover.swift | 6 ++ .../native/Sources/CuaNative/AXWorker.swift | 17 +++++- .../CuaNative/NativeProtocol.generated.swift | 2 +- .../CuaNative/RequestCoordinator.swift | 2 +- .../cua-macos/native/generate-protocol.ts | 2 + .../cua-macos/native/protocol.schema.json | 6 ++ .../cua-macos/native/tests/e2e.py | 16 +++++- .../cua-macos/native/tests/electron_e2e.py | 8 ++- .../native/tests/swift/SystemHoverTests.swift | 11 ++++ .../experimental/cua-macos/src/guidance.ts | 2 +- packages/experimental/cua-macos/src/index.ts | 4 ++ .../cua-macos/tests/guidance.spec.ts | 3 + .../tests/protocol-generation.spec.ts | 1 + .../tests/provider-lifecycle.spec.ts | 14 ++++- packages/experimental/cua/src/guidance.ts | 6 +- packages/experimental/cua/src/index.ts | 3 + .../experimental/cua/src/native-schema.ts | 6 +- packages/experimental/cua/src/types.ts | 12 ++-- .../session/cua-native/replay.override.json | 33 +++++++++++ .../cua-native/system-prompt.expected.md | 8 +-- .../cua-native/workspace/native-helper.mjs | 12 +++- .../session/cua-ptc/system-prompt.expected.md | 8 +-- .../system-prompt.expected.md | 8 +-- 41 files changed, 278 insertions(+), 98 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml index dba92660c8..04a78f70d3 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.i18n.yaml @@ -9,8 +9,8 @@ en: cdc04139c8d69415 zh: a3fe3e78ada08d95 /agent-note-continuous-cua-hover-without-cross-call-ownership/decision: - en: d1ea8fdc05927896 - zh: d3039bbb82bc949c + en: 125c860c1c568960 + zh: 8a2ece1101358200 /agent-note-continuous-cua-hover-without-cross-call-ownership/alternatives-considered: en: 18d917ee2e909b93 zh: 5b5ad0530f138cda diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md index 1cc8db5f81..2cce428cff 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md @@ -10,7 +10,7 @@ Hover interactions span movement, delayed content, observation and input inside ## Decision -An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before falling back to system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check. +An explicit Window exposes `mouseMove` for coordinates or an observed element ID. The result reports `hoverRoute` and `systemPointerMoved`. It never presses a mouse button; disabled controls can use system-pointer movement with `systemPointerHover` enabled. Completion, AX reads and screenshots do not restore a previous pointer position. Successive calls can visit intermediate points before entering a popup. Clicks deliver button events at their target without an off-window priming click. The [input-routing decision](2026-10-13-cua-hover-routes-and-coordinates.md) selects AX alternate UI before allowing opt-in system movement with foreground and mouse-hit checks. It never activates or raises the app implicitly. Other input or window changes can race that check. The [shared helper](2026-10-09-cua-shared-native-helper.md) serializes complete individual operations. It grants no application ownership across calls. Earlier arrival, a retained app object and Session lifetime do not establish task priority. Waiting for the model does not reserve the application. Explicit task coordination determines any required execution order. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md index 2f5ef0ce36..cc2457a70a 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,禁用控件可使用系统鼠标移动路径。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,再回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。 +显式窗口提供 `mouseMove`,接受窗口坐标或已观察元素的字符串 ID,结果用 `hoverRoute` 和 `systemPointerMoved` 报告执行路径。悬停不按下鼠标按钮,启用 `systemPointerHover` 后可通过系统鼠标悬停禁用控件。调用结束、AX 读取和截图不恢复先前的鼠标位置。进入浮层前可连续调用并经过中间位置。点击只在目标位置发送按键事件,不先在窗口外点击。 [输入路径决定](2026-10-13-cua-hover-routes-and-coordinates.zh.md)优先选择 AX 替代界面,只有启用该配置时才回退到经过前台和鼠标命中检查的系统移动,不隐式激活或抬起应用。其他输入或窗口变化仍可能与检查交错。 [共享 helper](2026-10-09-cua-shared-native-helper.zh.md)串行执行完整的单次操作,不分配跨调用的应用所有权。先发起请求、持有 app 对象和 Session 寿命均不代表任务优先级。等待模型期间不占用应用。需要确定执行顺序时,由明确的任务协调决定。 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml index 8259c024fb..9775baf3a4 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.i18n.yaml @@ -9,8 +9,8 @@ en: f96bf1ebc0719fb0 zh: e9a1144f0e76572d /agent-note-background-hover-and-screenshot-coordinates/decision: - en: 6ac0b77bea25fcf7 - zh: e50fec9049926fdc + en: bdf4d3386521ce00 + zh: 96db93177ad96a76 /agent-note-background-hover-and-screenshot-coordinates/alternatives-considered: en: 5fc4beaf79761c50 zh: 4948333b0020be28 diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md index 1091fcaf5e..c385525731 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.md @@ -10,7 +10,7 @@ Hover-only controls can sometimes be revealed without moving the user's pointer. ## Decision -Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route falls back to the real system pointer. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md). +Native hover first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Entering its revealed descendants preserves the parent UI; leaving restores it. An unavailable route returns `HOVER_UNAVAILABLE` by default. Enabling `systemPointerHover` permits the real system pointer fallback. An AX action failure propagates because received effects may be uncertain. The result records the route and whether the system pointer moved. System movement requires the selected foreground app and AppKit's mouse hit test, which excludes input-transparent overlays. No route grants [cross-call ownership](2026-10-13-cua-continuous-hover.md). Model-facing coordinate input defaults to pixels in the returned screenshot. `relative: true` accepts integer thousandths from 0 to 999 for `click`, `mouseMove`, `scroll` and `drag`; it does not apply to opaque element IDs. The Host owns the mapping to native window points. An application-wide observation refreshes its inventory; a scoped observation preserves other windows' image mappings. Window resizing invalidates the old image, while movement preserves local coordinates. Relative endpoints remain inside the window and do not depend on screenshot resolution. diff --git a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md index 2344d61c95..0d3db32400 100644 --- a/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md +++ b/.agents/notes/implemented/architecture/2026-10-13-cua-hover-routes-and-coordinates.zh.md @@ -10,7 +10,7 @@ Status: implemented ## 决策 -原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时回退到真实系统鼠标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。 +原生悬停优先寻找同一窗口内同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入其展开区域的子控件时保持父控件展开,离开后恢复。没有可用路径时默认返回 `HOVER_UNAVAILABLE`。启用 `systemPointerHover` 后才允许移动系统光标。AX 动作失败直接返回,因为已产生的效果可能不确定。结果记录实际路径及是否移动系统鼠标。系统移动要求所选应用处于前台,并使用 AppKit 的鼠标命中查询排除不接收输入的覆盖窗口。所有路径都遵守[跨调用不分配所有权](2026-10-13-cua-continuous-hover.zh.md)的决定。 面向模型的坐标默认使用返回截图中的像素。`click`、`mouseMove`、`scroll` 和 `drag` 传入 `relative: true` 时接受 0~999 的千分比整数,仅用于坐标目标。Host 负责换算原生窗口 point。应用级观察刷新窗口清单,单窗口观察保留其他窗口的图片映射。窗口尺寸变化使旧图片失效,移动窗口保留局部坐标。相对坐标的端点保持在窗口内,不随截图分辨率改变。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..e6fafb2ae4 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1119,6 +1119,8 @@ export interface Config { export interface Config extends CuaConfig { /** Interval in milliseconds between permission and position checks while the native guide is open. */ permissionPollIntervalMs: number + /** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */ + systemPointerHover: boolean /** * Source-build signing: `ad-hoc` (default) binds grants to the code hash; * an object selects an existing certificate in an explicitly configured keychain. diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..7aa0c7245c 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1121,6 +1121,8 @@ export interface Config { export interface Config extends CuaConfig { /** Interval in milliseconds between permission and position checks while the native guide is open. */ permissionPollIntervalMs: number + /** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */ + systemPointerHover: boolean /** * Source-build signing: `ad-hoc` (default) binds grants to the code hash; * an object selects an existing certificate in an explicitly configured keychain. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml new file mode 100644 index 0000000000..69471af235 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md +/: + en: 5ebb4c8a6b20b644 + zh: 22a8983d06fa5789 +/macos-hover-keeps-the-system-pointer-in-place-by-default: + en: 6833a7851486f10d + zh: 22983f326fb725ce +/macos-hover-keeps-the-system-pointer-in-place-by-default/change: + en: 55c3070b24b4ad39 + zh: 2555d127b0f4e4a0 +/macos-hover-keeps-the-system-pointer-in-place-by-default/migration: + en: bfa15519fd2afb89 + zh: b350e3a7aa2aaa7a diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md new file mode 100644 index 0000000000..fdd3d811eb --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "macOS mouseMove requires AX alternate UI by default and returns HOVER_UNAVAILABLE instead of moving the user's cursor." +--- + +# macOS hover keeps the system pointer in place by default + +English | [中文](guide.zh.md) + +## Change + +On macOS, `win.mouseMove(target)` uses an enabled element or ancestor that advertises both `AXShowAlternateUI` and `AXShowDefaultUI`. Without that route, previous versions moved the visible system cursor. The default now returns `HOVER_UNAVAILABLE` before sending input. + +## Migration + +1. For an available control, use its advertised action or click it directly. Use browser tools for web content that requires page hover. +2. To restore visible pointer movement, set `systemPointerHover: true` in the `config` of the macOS provider entry (`id: cua`) in your profile's `cordis.patch.yml`. Preserve the entry's other settings. Restart the profile. +3. Call `win.mouseMove` on a foreground, unobscured control without AX alternate UI. The opt-in result reports `hoverRoute: "system-pointer"` and `systemPointerMoved: true`. Keep the default to avoid disturbing the user's cursor. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md new file mode 100644 index 0000000000..7202988db2 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "macOS 的 mouseMove 默认要求控件支持 AX 备用界面,否则返回 HOVER_UNAVAILABLE,保留用户的光标位置。" +--- + +# macOS 悬停默认保留系统光标位置 + +[English](guide.md) | 中文 + +## 变更 + +在 macOS 上,`win.mouseMove(target)` 会查找已启用且同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的控件或祖先。找不到时,旧版会移动系统光标,新版默认在发送输入前返回 `HOVER_UNAVAILABLE`。 + +## 迁移 + +1. 对已经可用的控件,可执行它声明的动作或直接点击。需要网页悬停时可用浏览器工具。 +2. 要恢复可见光标移动,在 profile 的 `cordis.patch.yml` 中,给 macOS 提供方条目(`id: cua`)的 `config` 添加 `systemPointerHover: true`。保留该条目的其他设置,重启 profile。 +3. 对前台未受遮挡且不提供 AX 备用界面的控件调用 `win.mouseMove`。启用配置时,结果为 `hoverRoute: "system-pointer"` 和 `systemPointerMoved: true`。要保留用户的光标位置,使用默认配置。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 76c65f408d..37458210d5 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,11 +15,11 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 7fdb7c0462275417 - zh: 0a4a9562f4a82945 + en: 533ed4dd11af5126 + zh: 03036e8c949d6aca /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 740031b2bf73b350 - zh: 30c4929c5bb6baeb + en: 0da6d36bdf117089 + zh: 0d3692ab25ac2923 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 7a96cac17e..ce128bab4f 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -64,6 +64,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates | `buildTimeoutMs` | `300000` | Maximum native preparation time. | | `timeoutMs` | `30000` | Per-operation deadline; cancellation can leave partial input. | | `connectTimeoutMs` | `5000` | Deadline for connecting to or starting the shared helper. | +| `systemPointerHover` | `false` | Allow `mouseMove` to move the visible cursor when AX hover is unavailable. | | `permissionPollIntervalMs` | `1000` | Interval in milliseconds between permission and position checks while the native guide is open. | | `screenshotTimeoutMs` | `5000` | Screenshot deadline including queue time, capped by `timeoutMs`. | | `axTimeoutMs` | `3000` | Deadline per Accessibility system call, configured independently of the complete operation. | @@ -114,7 +115,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` `getWindow` reads its initial tree silently. An owned window without an AX surface returns an empty snapshot and remains available for screenshots and coordinate input. Within one API instance, the facade keeps one current accessibility snapshot per application handle, shared by every app and window object for that handle, including repeated selections. Reading any window replaces that snapshot; element operations use the latest snapshot ID, so use IDs from the latest tree and do not assume an older ID still identifies the same control. A failed read publishes no partial snapshot; read again without repeating the preceding input. Window objects own screenshots and pointer input. Keyboard methods stay on `app` because input follows the app’s current focus. -`mouseMove(target)` first reveals advertised AX alternate UI without moving the system cursor. Entering a revealed descendant preserves its parent UI, and leaving restores the default UI. When unavailable, the call moves the visible system cursor to an AX element center or window-local point without pressing a button, including over disabled controls. It requires the selected app to be foreground and the target point unobscured; otherwise `FOREGROUND_REQUIRED` requires explicit activation or raising and a fresh observation. Completion, AX reads and screenshots do not restore the previous point. Wait for the application’s hover delay, observe the revealed content, then hover into it and click; successive calls can visit intermediate points. Other input or application changes can interrupt the interaction. [Continuous-interaction rationale](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.md). +`mouseMove(target)` defaults to AX hover. An enabled target or ancestor must advertise both `AXShowAlternateUI` and `AXShowDefaultUI`. Moving into its descendants keeps the UI open, and leaving restores it. Without an AX route the helper returns `HOVER_UNAVAILABLE` before sending input. Click a visible control or use `performAction` with an advertised action. For browser content without these AX actions, use browser tools. Enable `systemPointerHover` only when moving the user’s visible cursor is acceptable. That route requires a foreground, unobscured target and leaves the cursor at the destination. `paste(text, { format: "text" | "html" })` temporarily publishes the requested clipboard format and invokes the application’s enabled standard Paste menu command. It keeps the temporary format until a pasteboard reader requests its data, then restores every captured original format while it still owns the clipboard, preserving a later copy. Paste operations share a cross-process lock and cancellation joins helper cleanup. A forced process exit can prevent restoration. Unsupported Paste commands fail without typing fallback; `typeText` remains separate key-event input. @@ -122,7 +123,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Screenshot capture requires an attachment store and a resolved model route declaring image input. The shared attachment admission validates canonical Base64, the raster and its configured capacity, then stores the image once. Native data remains available to programmatic callers; model content carries coordinate metadata and the durable image reference. Response byte limits apply before parsing. -Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. Use `invoke(id)` to activate a control through accessibility, for example the Open button in a system file panel or a menu item in the app tree. +Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. Prefer `invoke(id)` for a background control’s default action. For mouse input, activate the application and observe the target first. Mouse clicks on system Open and Save sheets are routed to their verified panel-service window. Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; `scroll` uses named `x` and `y`. All use pixels in the latest returned screenshot. Pass `relative: true` for integer thousandths of window width and height, from 0 to 999; omission or `false` uses pixels. Relative input can use a successful AX read or screenshot, while absolute input requires a screenshot. The Host maps the delivered image to native points, including attachment and model-request resizing. A value of 999 remains inside the window edge. Coordinate options do not apply to element IDs. A width or height change since the latest observation returns `WINDOW_CHANGED` before input, including raw coordinate calls without a snapshot ID; read fresh AX or take a new screenshot before proceeding. Window movement alone preserves window-local coordinates. Capture and pointer input reject known disagreement between the selected window’s accessibility frame and displayed bounds with `WINDOW_CHANGED`, before posting pointer events. This includes Stage Manager transformations when AX retains the full window frame. Read fresh state; any activation or window raise remains explicit. Advertised AX actions remain available. Missing AX geometry retains the AXless path and does not establish that a transformed window can be operated. @@ -175,7 +176,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -209,12 +210,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index ca39bab33c..2801e0ccbc 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -64,6 +64,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. | `buildTimeoutMs` | `300000` | 原生组件准备的最长时间。 | | `timeoutMs` | `30000` | 单次操作截止时间,取消后可能已发生部分输入。 | | `connectTimeoutMs` | `5000` | 连接或启动共享 helper 的截止时间。 | +| `systemPointerHover` | `false` | AX 悬停不可用时,允许 `mouseMove` 移动可见光标。 | | `permissionPollIntervalMs` | `1000` | 原生引导打开期间检查权限和窗口位置的间隔,单位为毫秒。 | | `screenshotTimeoutMs` | `5000` | 截图总期限,包含排队时间,且不超过 `timeoutMs`。 | | `axTimeoutMs` | `3000` | 每次 Accessibility 系统调用的截止时间,与完整操作截止独立配置。 | @@ -114,7 +115,7 @@ void await window.getScreenshot() `getWindow` 静默读取初始树。已确认归属但没有 AX 界面的窗口返回空快照,仍可截图和发送坐标输入。在单个 API 实例内,门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享它,包括重复选择。读取任一窗口都会替换该快照;元素操作使用最新快照 ID,因此应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。读取失败不会发布部分快照;可以重新读取,但不要重复此前的输入。窗口对象负责截图和指针输入。键盘方法保留在 `app` 上,因为输入跟随应用的当前焦点。 -`mouseMove(target)` 优先通过控件声明的 AX 动作展开替代界面,不移动系统鼠标。进入展开区域的子控件时保持父控件展开,离开后恢复默认界面。没有这条路径时,该方法将可见系统鼠标移到 AX 元素中心或窗口内坐标,不按鼠标按钮,也可用于禁用控件。所选应用必须在前台,且目标点未被遮挡,否则返回 `FOREGROUND_REQUIRED`,调用方需显式激活或抬起窗口并重新观察。调用结束、AX 读取和截图不恢复先前的位置。等待应用的悬停延迟后,观察出现的内容,再移入并点击;连续调用可经过中间位置。其他输入或应用自身变化可能中断交互。[连续交互的设计理由](../../../.agents/notes/implemented/architecture/2026-10-13-cua-continuous-hover.zh.md)。 +`mouseMove(target)` 默认通过 AX 悬停。目标或其祖先必须已启用,并同时声明 `AXShowAlternateUI` 和 `AXShowDefaultUI`。进入子控件会保持展开,离开后恢复默认界面。如果没有可用的 AX 路径,helper 返回 `HOVER_UNAVAILABLE`,不发送输入。可点击已经可见的控件,或用 `performAction` 执行控件声明的动作。浏览器内容缺少这些 AX 动作时,请使用浏览器工具。只有允许移动用户可见光标时才开启 `systemPointerHover`。这条路径要求目标在前台且未被遮挡,操作后光标停在目标位置。 `paste(text, { format: "text" | "html" })` 临时提供指定格式的剪贴板内容,并调用应用已启用的标准 Paste 菜单命令。临时格式保留到剪贴板读取方请求其数据,然后只在仍持有剪贴板时恢复保存的全部原格式,保留期间产生的新复制内容。粘贴操作共用跨进程锁,取消会等待辅助进程清理。强制终止进程可能阻止恢复。应用不支持 Paste 命令时明确失败,不自动改成逐字输入;`typeText` 仍单独提供按键事件输入。 @@ -122,7 +123,7 @@ void await window.getScreenshot() 截图要求附件服务可用,并确认当前模型支持图片输入。共享附件接入校验规范 Base64、图像数据及配置容量,然后保存一次图片。程序调用方仍可取得原生数据,模型内容包含坐标元数据和持久图片引用。响应字节上限在解析前执行。 -`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。要通过辅助功能触发控件的默认动作,可用 `invoke(id)`,例如系统文件面板的“打开”按钮,或应用树中的菜单项。 +`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。后台控件优先用 `invoke(id)` 执行默认动作。需要鼠标输入时,先激活应用并重新观察目标。系统打开或保存面板的鼠标点击投递给已核实的文件面板服务窗口。 `mouseMove`、`click` 和 `drag` 的绝对坐标使用 `[x, y]` 元组;`scroll` 使用命名的 `x` 和 `y`。它们都使用最近返回截图中的像素。传入 `relative: true` 时使用 0~999 的千分比整数;省略或传入 `false` 时使用像素。相对坐标可基于成功的 AX 读取或截图,绝对坐标必须先截图。Host 根据实际送入模型的图片尺寸换算原生 point,包含附件归一化和模型请求阶段的缩放。999 映射到窗口边缘以内。坐标选项不适用于元素 ID。窗口宽高与最近一次观察不同时,在输入前返回 `WINDOW_CHANGED`,即使原始坐标调用不传快照 ID 也会检查;重新读取 AX 或截图后再操作。单纯移动窗口不使窗口内坐标失效。截图和鼠标输入会核对所选窗口的辅助功能框与显示边界;已知两者不一致时,在发送任何鼠标事件前返回 `WINDOW_CHANGED`。当 AX 保留完整窗口框时,这也会拦住 Stage Manager 变换后的窗口。需要重新读取状态;激活应用或抬起窗口仍须显式调用。元素声明的 AX 动作保持可用。缺少 AX 几何时保留无 AX 路径,不代表变换后的窗口一定可以操作。 @@ -175,7 +176,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -209,12 +210,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 89135ddfbe..25d5fb8952 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,11 +18,11 @@ en: 1435672513328c05 zh: 11e7a1e672410c10 /dsh-cua-native-helper/request-protocol: - en: 20be674c0592d66d - zh: e26112b908187acc + en: 88a59904ca4ebedc + zh: 14f2b666d7382145 /dsh-cua-native-helper/observation-and-input: - en: 2408e0c0e9c873a2 - zh: e06236fc32efc4fa + en: da6a1c45fd166818 + zh: 7f378d5409a6085d /dsh-cua-native-helper/verification: en: 49f4cce2a4cc3114 zh: e9d65c92ef35fe24 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index c01b273d1b..bdb844e806 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -83,7 +83,7 @@ Successful `activate` returns `dispatched` and `foregroundChanged`. A known chan Every app-targeted operation requires `appHandle` from `getApp` in the same helper. The helper pins the PID and kernel process start time, and invalidates the handle and all of its snapshots after process exit or PID reuse. Calling `getApp` can acquire the replacement process without reactivating old handles. A random per-helper namespace prevents handles from a terminated helper matching those of its replacement. Repeated acquisition of the same live process shares its handle. A post-launch inspection failure invalidates the pending handle and preserves the original error. It does not terminate a process already started; launchApp cannot reuse the failed handle. -Stable error codes are `INVALID_REQUEST` (malformed envelope), `INVALID_ARGUMENT` (invalid parameters), `UNSUPPORTED` (unknown operation), `APP_UNAVAILABLE`, `APP_PATH_UNAVAILABLE`, `PROCESS_INSPECTION_FAILED`, `AMBIGUOUS_APP`, `STALE_APP`, `STALE_SNAPSHOT`, `WINDOW_UNAVAILABLE`, `WINDOW_CHANGED`, `PERMISSION_DENIED`, `FOREGROUND_REQUIRED` (hover target is not the unobscured foreground window), `PANEL_NOT_READY` (system panel recipient unavailable before input), and `NATIVE_ERROR` (remaining operating-system failures). An error never promises that a partially dispatched input was rolled back. The host must not retry input automatically. +Stable error codes are `INVALID_REQUEST` (malformed envelope), `INVALID_ARGUMENT` (invalid parameters), `UNSUPPORTED` (unknown operation), `APP_UNAVAILABLE`, `APP_PATH_UNAVAILABLE`, `PROCESS_INSPECTION_FAILED`, `AMBIGUOUS_APP`, `STALE_APP`, `STALE_SNAPSHOT`, `WINDOW_UNAVAILABLE`, `WINDOW_CHANGED`, `PERMISSION_DENIED`, `HOVER_UNAVAILABLE`, `FOREGROUND_REQUIRED` (hover target is not the unobscured foreground window), `PANEL_NOT_READY` (system panel recipient unavailable before input), and `NATIVE_ERROR` (remaining operating-system failures). An error never promises that a partially dispatched input was rolled back. The host must not retry input automatically. Application selection returns an authorization record to the Host: a SHA-256 digest of the case-sensitive bundle identifier prefixed with `macos:bundle-id:`, display name, optional executable path, and persistable flag. All installations with that identifier share consent, including unsigned and ad-hoc-signed applications. Without a nonempty bundle identifier, both running and stopped applications use SHA-256 of `macos:executable-path:` followed by the symlink-resolved executable path and remain eligible for saved consent. A running bundle identifier remains usable when the process path query fails; the record omits executablePath. Available paths must still match the selection. Without either identity, APP_PATH_UNAVAILABLE reports the path query cause, including its errno, before any target operation. PROCESS_INSPECTION_FAILED means the process instance could not be verified; only ESRCH from process inspection is reported as a missing process. Neither failure triggers an automatic retry. Process IDs and start times validate live handles but do not enter the saved identity. The Host strips this record from model results and obtains human consent before launch, observation or input. This pipe protocol is trusted Host transport, not a sandbox against a separately authorized shell process. @@ -111,7 +111,7 @@ Host-only permission controls are `permissionStatus {}`, `requestPermission` and Observation reads each non-layout node’s descriptive properties and children through `AXUIElementCopyMultipleAttributeValues`. Per-attribute errors retain the individual-read rules; unsupported batch APIs use individual reads. Values are retained only during that observation, and input reads live attributes. Application state can change between nodes; a batch does not make the whole tree atomic. -System file-panel keyboard routing resolves the remote recipient through the selected app’s focused AX sheet. Only Apple’s Open and Save Panel Service is accepted, and its focused ancestry must still contain the identified remote window. Element-targeted pointer input follows AX parents to find the enclosing window or sheet. +System file-panel keyboard routing resolves the remote recipient through the selected app’s focused AX sheet. Only Apple’s Open and Save Panel Service is accepted, and its focused ancestry must still contain the identified remote window. For element and coordinate clicks on an Open or Save panel, the recipient is the verified panel-service window. Its frame must match the selected host window. Keyboard modifier names are plain strings. The shared object API passes the names through unchanged; the macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and rejects an unknown name with `INVALID_ARGUMENT`. It does not parse chord strings. @@ -121,9 +121,9 @@ Tree observation and action discovery treat a generic AX failure reading one ele `paste` publishes one plain-text or HTML clipboard format, dispatches the application's enabled standard Paste menu command, and waits for a clipboard data request. It then restores the preserved formats only while its ownership marker and change count still match. The Host serializes its pastes across helpers with a file lock. maxClipboardBytes bounds both input and preserved contents; unsupported menus and oversized data fail before dispatch. A later copy is preserved. Cancellation restores owned clipboard data when possible; forced termination cannot guarantee restoration, and a data request does not prove the target completed editing. After dispatch, `pasteReadTimeoutMs` bounds waiting for clipboard consumption. Expiry returns `PASTE_NOT_CONSUMED`, closes the promised data provider, and restores the original clipboard only while still owned. The failure does not prove the app will never process its queued Paste command; inspect the target before deciding whether to retry. -`mouseMove` accepts an observed element ID or a window-local point and never presses a mouse button. Disabled controls may be hovered. No request completion, AX read or screenshot restores the previous point; subsequent mouseMove calls can enter revealed content. Click sends its button events at the target without an off-window priming click. Individual requests are serialized, but no application is reserved between calls. Other input or application changes can interrupt the interaction. +`mouseMove` reveals or restores alternate UI through an enabled element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Without an AX route it returns `HOVER_UNAVAILABLE` before sending input. The Host supplies the native boolean `allowSystemPointer` from its `systemPointerHover` setting. Omission means false. Only true permits posting a system pointer move after checking the foreground process and window hit. -`mouseMove` first uses a same-window element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Revealed descendants retain the parent UI; leaving restores it once. An AX action failure propagates without trying another input route. Without an applicable AX route, the method moves the visible system cursor through the system input queue after checking the foreground PID and AppKit mouse hit testing at the point. Input-transparent windows and transparent regions do not block the target. A failed check returns `FOREGROUND_REQUIRED` without moving the cursor. The result identifies `hoverRoute` as `accessibility` or `system-pointer` and reports `systemPointerMoved`. The method does not activate, raise or restore focus. Other input or window changes can race the check and dispatch. +The opt-in system pointer route returns `FOREGROUND_REQUIRED` if the target is obscured or belongs to a background app. The result reports the route and whether the visible cursor moved in `hoverRoute` and `systemPointerMoved`. It never presses a button or restores the cursor after a read. Later input may interrupt the hover. Clicks send their button events at the target without an off-window priming click. ----- diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 307d2eaee8..51d6c13c29 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -83,7 +83,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 每个面向应用的操作都要求使用同一 helper 的 `getApp` 返回的 `appHandle`。helper 固定 PID 和内核进程启动时间,进程退出或 PID 被复用后使句柄及其全部快照失效。再次调用 `getApp` 可取得替代进程,不会重新激活旧句柄。随机的 helper 命名空间防止已终止 helper 的句柄与替代实例重合。重复获取同一存活进程会共享句柄。启动后检查失败会使待启动句柄失效,并保留原错误;已经启动的进程不会被终止,launchApp 也不能复用失败的句柄。 -稳定错误码包括 `INVALID_REQUEST`(信封无效)、`INVALID_ARGUMENT`(参数无效)、`UNSUPPORTED`(操作未知)、`APP_UNAVAILABLE`、`APP_PATH_UNAVAILABLE`、`PROCESS_INSPECTION_FAILED`、`AMBIGUOUS_APP`、`STALE_APP`、`STALE_SNAPSHOT`、`WINDOW_UNAVAILABLE`、`WINDOW_CHANGED`、`PERMISSION_DENIED`、`FOREGROUND_REQUIRED`(悬停目标不是未被遮挡的前台窗口)、`PANEL_NOT_READY`(输入前系统面板接收方尚不可用)及 `NATIVE_ERROR`(其余操作系统失败)。错误不保证已分派的部分输入被回滚,Host 不得自动重试输入。 +稳定错误码包括 `INVALID_REQUEST`(信封无效)、`INVALID_ARGUMENT`(参数无效)、`UNSUPPORTED`(操作未知)、`APP_UNAVAILABLE`、`APP_PATH_UNAVAILABLE`、`PROCESS_INSPECTION_FAILED`、`AMBIGUOUS_APP`、`STALE_APP`、`STALE_SNAPSHOT`、`WINDOW_UNAVAILABLE`、`WINDOW_CHANGED`、`PERMISSION_DENIED`、`HOVER_UNAVAILABLE`、`FOREGROUND_REQUIRED`(悬停目标不是未被遮挡的前台窗口)、`PANEL_NOT_READY`(输入前系统面板接收方尚不可用)及 `NATIVE_ERROR`(其余操作系统失败)。错误不保证已分派的部分输入被回滚,Host 不得自动重试输入。 应用选择向 Host 返回授权记录:区分大小写的 Bundle ID 加上 `macos:bundle-id:` 前缀后计算的 SHA-256 摘要、显示名称、可选的可执行路径和可持久化标记。相同标识的所有安装副本共用授权,包括未签名和临时签名的应用。缺少非空 Bundle ID 时,运行中和未启动应用都对 `macos:executable-path:` 与解析符号链接后的可执行路径计算 SHA-256,仍可保存长期授权。进程路径查询失败时,运行中的有效 Bundle ID 仍可用于授权,记录省略 executablePath;路径可取得时仍须与所选目标一致。两种身份均不可用时,在执行目标操作前返回 APP_PATH_UNAVAILABLE,保留路径查询原因和 errno。PROCESS_INSPECTION_FAILED 表示无法验证进程实例,只有进程检查返回 ESRCH 时才报告进程不存在;两种失败都不触发自动重试。进程号和启动时间只校验存活句柄,不进入已保存身份。Host 从模型结果中移除此记录,并在启动、观察和输入前取得用户许可。此管道协议用于可信 Host 传输,无法隔离另一个已获授权的 shell 进程。 @@ -111,7 +111,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 观察通过 `AXUIElementCopyMultipleAttributeValues` 读取每个非布局节点的描述属性和子节点。逐属性错误保留单独读取的规则;不支持批量 API 时使用单独读取。值只在本次观察期间保留,输入读取即时属性。应用状态可能在节点之间变化,批量读取不使整棵树具备原子性。 -系统文件面板的键盘路由通过所选应用的 AX 焦点 sheet 解析远端接收方。只接受 Apple 的 Open and Save Panel Service,且其焦点祖先链仍须包含已识别的远端窗口。按元素发送鼠标事件时,helper 沿 AX 父节点查找所属窗口或 sheet。 +系统文件面板的键盘路由通过所选应用的 AX 焦点 sheet 解析远端接收方。只接受 Apple 的 Open and Save Panel Service,且其焦点祖先链仍须包含已识别的远端窗口。面板的元素点击和坐标点击发送至已核实的系统面板服务窗口。服务窗口的边界必须和所选宿主窗口一致。 键盘修饰键名称是普通字符串。共享对象 API 原样传递名称;macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,未知名称返回 `INVALID_ARGUMENT`。它不解析组合键字符串。 @@ -121,9 +121,9 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `paste` 提供一种纯文本或 HTML 剪贴板格式,调用应用已启用的标准 Paste 菜单命令,并等待剪贴板数据请求。随后仅在所有权标记和修改计数仍匹配时恢复原有格式。Host 通过文件锁串行化不同 helper 的粘贴。maxClipboardBytes 同时限制输入和保留内容,不支持的菜单和过大的数据在分派前失败。后续复制会被保留。取消会尽可能恢复仍持有的剪贴板数据,强制结束不保证恢复,数据请求也不证明目标已完成编辑。 分派完成后,`pasteReadTimeoutMs` 限制等待剪贴板读取的时间。到期返回 `PASTE_NOT_CONSUMED`,关闭延迟数据提供方,并仅在仍持有剪贴板时恢复原内容。该失败不能证明应用以后不会处理已排队的 Paste 命令;决定是否重试前先检查目标内容。 -`mouseMove` 接受已观察的元素 ID 或窗口内坐标,不按下鼠标按钮,也可用于禁用控件。调用结束、AX 读取和截图都不恢复原位置,后续 mouseMove 调用可进入新出现的内容。点击只在目标位置发送按键事件,不先在窗口外点击。单次请求串行执行,不在调用之间保留应用。其他输入或应用变化可能中断交互。 +默认情况下,`mouseMove` 通过同一窗口内启用的控件或祖先声明的 `AXShowAlternateUI` 和 `AXShowDefaultUI` 展开或恢复界面。缺少这条路径时返回 `HOVER_UNAVAILABLE`,不发送输入。Host 根据部署配置 `systemPointerHover` 传入原生布尔参数 `allowSystemPointer`,省略时为 false。只有值为 true 才允许移动全局光标,且须检查前台进程和鼠标命中的窗口。 -`mouseMove` 优先查找同一窗口内声明了 `AXShowAlternateUI` 和 `AXShowDefaultUI` 的元素或祖先。进入展开区域的子控件时保留父控件界面,离开时恢复一次。AX 动作失败直接返回错误,不尝试其他输入路径。没有可用 AX 路径时,该方法核实前台 PID,并通过 AppKit 查询目标点实际接收鼠标输入的窗口后,使用系统输入队列移动可见鼠标。不接收鼠标输入的窗口和透明区域不会阻挡目标。检查失败返回 `FOREGROUND_REQUIRED`,不移动鼠标。结果中的 `hoverRoute` 标明 `accessibility` 或 `system-pointer`,`systemPointerMoved` 标明是否移动系统鼠标。该方法不激活、不抬起窗口,也不恢复焦点。其他输入或窗口变化可能与检查和分派交错。 +开启后,系统指针路线会检查前台应用和坐标命中的窗口,不满足条件时返回 `FOREGROUND_REQUIRED`。返回值 `hoverRoute` 和 `systemPointerMoved` 说明走了哪条路线以及是否移动了可见光标。悬停不会按下鼠标,也不会在读取后还原光标。后续输入可能中断悬停。点击只在目标点发送按键事件,不先在窗口外点击。 ----- diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift index 1a1e4f595b..3b39ab1f02 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXAccess.swift @@ -419,6 +419,10 @@ final class AXAccess { } /// Resolve an exact AX window or sheet without enabling accessibility or traversing its controls. func windowBounds(_ id: UInt32, owner: ProcessIdentity) throws -> WindowBounds? { + guard let node = try windowElement(id, owner: owner) else { return nil } + return try bounds(node) + } + func windowElement(_ id: UInt32, owner: ProcessIdentity) throws -> AXUIElement? { let app = AXUIElementCreateApplication(owner.pid) var windows = try children(app, "AXWindows") if let focused = try element(app, "AXFocusedWindow"), !windows.contains(where: { CFEqual($0, focused) }) { @@ -427,9 +431,9 @@ final class AXAccess { for window in windows { let role = try string(window, "AXRole") guard role == "AXWindow" || role == "AXSheet" else { continue } - if try windowID(window) == id { return try bounds(window) } + if try windowID(window) == id { return window } for sheet in try children(window) where try string(sheet, "AXRole") == "AXSheet" { - if try windowID(sheet) == id { return try bounds(sheet) } + if try windowID(sheet) == id { return sheet } } } return nil @@ -654,6 +658,31 @@ final class AXAccess { } throw NativeFailure(code: "WINDOW_UNAVAILABLE", message: "Pointer input requires an enclosing window or sheet. For a menu item’s default action, use app.invoke(id)") } + /// A system file panel renders in its host window but receives input in the panel service's window. + func filePanelRecipient(_ node: AXUIElement, owner: ProcessIdentity, catalog: ApplicationCatalogSnapshot) throws -> (process: ProcessIdentity, windowID: UInt32)? { + guard ["open-panel", "save-panel"].contains(try string(node, "AXIdentifier") ?? "") else { return nil } + guard let hostID = try windowID(node) else { throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel has no window ID") } + _ = try NativePlatform.ownedWindow(owner.pid, hostID) + var recipient: (ProcessIdentity, UInt32)? + for child in try children(node) { + guard let id = try windowID(child), let window = NativePlatform.windows(allLayers: true).first(where: { $0.windowID == id }), window.pid != owner.pid else { continue } + guard catalog.application(window.pid)?.bundleID == "com.apple.appkit.xpc.openAndSavePanelService" else { + throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel refers to an unsupported remote process") + } + let process = try NativePlatform.identity(window.pid) + if let old = recipient, old.0 != process || old.1 != id { throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel has ambiguous remote recipients") } + recipient = (process, id) + } + guard let (process, id) = recipient else { throw NativeFailure(code: "PANEL_NOT_READY", message: "System file panel has no ready input recipient") } + var focus = try element(AXUIElementCreateApplication(process.pid), "AXFocusedWindow") + for _ in 0..<100 { + guard let focused = focus else { break } + if try windowID(focused) == id { try NativePlatform.verify(process); return (process, id) } + focus = try element(focused, "AXParent") + } + throw NativeFailure(code: "PANEL_NOT_READY", message: "System file panel focus changed; observe fresh state") + } + func keyboardRecipient(_ owner: ProcessIdentity, catalog: ApplicationCatalogSnapshot) throws -> ProcessIdentity { var current = try element(AXUIElementCreateApplication(owner.pid), "AXFocusedWindow") var visited: [AXUIElement] = [] @@ -661,28 +690,7 @@ final class AXAccess { guard let node = current else { return owner } if visited.contains(where: { CFEqual($0, node) }) { break } visited.append(node) - if ["open-panel", "save-panel"].contains(try string(node, "AXIdentifier") ?? "") { - guard let hostID = try windowID(node) else { throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel has no window ID") } - _ = try NativePlatform.ownedWindow(owner.pid, hostID) - var recipient: (ProcessIdentity, UInt32)? - for child in try children(node) { - guard let id = try windowID(child), let window = NativePlatform.windows(allLayers: true).first(where: { $0.windowID == id }), window.pid != owner.pid else { continue } - guard catalog.application(window.pid)?.bundleID == "com.apple.appkit.xpc.openAndSavePanelService" else { - throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel refers to an unsupported remote process") - } - let process = try NativePlatform.identity(window.pid) - if let old = recipient, old.0 != process || old.1 != id { throw NativeFailure(code: "PANEL_NOT_READY", message: "File panel has ambiguous remote recipients") } - recipient = (process, id) - } - guard let (process, id) = recipient else { throw NativeFailure(code: "PANEL_NOT_READY", message: "System file panel has no ready input recipient") } - var focus = try element(AXUIElementCreateApplication(process.pid), "AXFocusedWindow") - for _ in 0..<100 { - guard let focused = focus else { break } - if try windowID(focused) == id { try NativePlatform.verify(process); return process } - focus = try element(focused, "AXParent") - } - throw NativeFailure(code: "PANEL_NOT_READY", message: "System file panel focus changed; observe fresh state") - } + if let panel = try filePanelRecipient(node, owner: owner, catalog: catalog) { return panel.process } current = try element(node, "AXParent") } throw NativeFailure(code: "PANEL_NOT_READY", message: "Focused accessibility ancestry exceeds the traversal limit") diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift index ff398914c7..656aa97a07 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift @@ -2,6 +2,12 @@ import ApplicationServices final class AXHover { + static func requireSystemPointer(allowed: Bool) throws { + guard allowed else { + throw NativeFailure(code: "HOVER_UNAVAILABLE", message: "No enabled element at this target or in its ancestors offers both AXShowAlternateUI and AXShowDefaultUI. System-pointer hover is disabled; this provider has no other pointer-free hover route. No input was sent and the pointer did not move. Use click on an available control or performAction with an action from listActions.") + } + } + private var revealed: (element: AXUIElement, windowID: UInt32)? /// Entering revealed descendants preserves their parent UI; leaving restores it once. diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index ea58f27f7e..f00e63b622 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -349,6 +349,7 @@ actor AXWorker { let window: WindowInfo let point: WindowPoint var hoverElement: AXUIElement? + var elementWindow: AXUIElement? if params.contains("elementId") { guard !params.contains("x"), !params.contains("y") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } let requestedWindow = try params.optionalWindowID() @@ -359,6 +360,7 @@ actor AXWorker { throw NativeFailure(code: "STALE_SNAPSHOT", message: "Element belongs to window \(enclosing.id); select that window and read its tree") } if method == "click" { try ax().requireEnabled(selected) } + elementWindow = enclosing.element hoverElement = selected guard let bounds = try ax().bounds(selected), bounds.width > 0, bounds.height > 0 else { throw NativeFailure(code: "NATIVE_ERROR", message: "Element has no pointer bounds") } window = try WindowGeometry.resolve(owner: identity, windowID: enclosing.id) { try ax().bounds(enclosing.element) } @@ -371,6 +373,7 @@ actor AXWorker { } let route = WindowRoute(owner: identity, windowID: window.windowID, bounds: window.bounds) if method == "mouseMove" { + let allowSystemPointer = try params.optionalBoolean("allowSystemPointer") ?? false try WindowPointerInput.validate(point, in: route) if hoverElement == nil { hoverElement = try ax().element(at: CGPoint(x: window.bounds.x + point.x, y: window.bounds.y + point.y), owner: identity) @@ -381,9 +384,21 @@ actor AXWorker { if try hover.move(to: hoverElement, in: route, access: ax()) { return .result(Self.mouseMoveResult(route: "accessibility", pointerMoved: false)) } + try AXHover.requireSystemPointer(allowed: allowSystemPointer) return .mouseMove(route, point) } - try await inputs().1.click(in: route, at: point, button: button, count: count, modifiers: modifiers, holdMs: holdMs) + var clickRoute = route + if AXIsProcessTrusted(), let node = try elementWindow ?? ax().windowElement(window.windowID, owner: identity), + let panel = try ax().filePanelRecipient(node, owner: identity, catalog: catalog) { + let serviceWindow = try NativePlatform.ownedWindow(panel.process.pid, panel.windowID) + guard serviceWindow.bounds == window.bounds else { + throw NativeFailure(code: "WINDOW_CHANGED", message: "File panel and its input window have different frames; read fresh window state") + } + try NativePlatform.verify(identity) + try NativePlatform.verify(panel.process) + clickRoute = WindowRoute(owner: panel.process, windowID: panel.windowID, bounds: serviceWindow.bounds) + } + try await inputs().1.click(in: clickRoute, at: point, button: button, count: count, modifiers: modifiers, holdMs: holdMs) case "scroll", "drag": let id = try params.windowID() try coordinateSnapshot(handle, params, id) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index a13ca0ab35..0da4e5cb96 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -14,7 +14,7 @@ enum NativeProtocol { "listActions": ["appHandle", "elementId", "snapshotId", "windowId"], "listApps": [], "listWindows": ["appHandle"], - "mouseMove": ["appHandle", "elementId", "snapshotId", "windowId", "x", "y"], + "mouseMove": ["allowSystemPointer", "appHandle", "elementId", "snapshotId", "windowId", "x", "y"], "openPermissionSettings": ["permission", "settingsMessage"], "paste": ["appHandle", "format", "maxClipboardBytes", "maxDepth", "maxElements", "pasteReadTimeoutMs", "text", "windowId"], "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 00a1d709a1..3a778cb8ae 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -165,7 +165,7 @@ import Darwin let params = try RequestParameters(request) try cancellation.check() if request.method == "screenshot" { try capture.requireAvailable() } - let requiresCatalog = ["getApp", "listApps", "findApps", "typeText", "pressKey"].contains(request.method) + let requiresCatalog = ["getApp", "listApps", "findApps", "typeText", "pressKey", "click"].contains(request.method) let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil) let result: JSONValue if request.method == "permissionStatus" { diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 49bfeea38b..398999cc2c 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -1,5 +1,6 @@ /** Generate macOS admission artifacts from the shared CUA operation definitions. */ import { readFile, writeFile } from 'node:fs/promises' +import { z } from 'zod' import { nativeProtocol } from '@deepseek-ai/dsh-cua/native-schema' import { PermissionGuideParameters, PermissionSettingsParameters } from '../src/permission-guide.ts' @@ -9,6 +10,7 @@ import { PermissionGuideParameters, PermissionSettingsParameters } from '../src/ */ export function renderNativeProtocol(): { json: string; swift: string } { const { fields, enums, json } = nativeProtocol({ + mouseMove: z.object({ allowSystemPointer: z.boolean().optional() }), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, }) const quoted = (values: Iterable) => [...values].sort().map(value => JSON.stringify(value)).join(', ') diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index 4dda3c8511..b0d74a84dc 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -488,6 +488,9 @@ "type": "string", "minLength": 1, "description": "Opaque string defined by the platform provider, valid for at least the lifetime of one snapshot." + }, + "allowSystemPointer": { + "type": "boolean" } }, "required": [ @@ -520,6 +523,9 @@ "y": { "type": "number", "minimum": 0 + }, + "allowSystemPointer": { + "type": "boolean" } }, "required": [ diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 95776b4031..03ae9ac2ac 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -85,7 +85,7 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state assert f"window {sheet_id}; select that window" in error["message"], error ready = call("getState", {**owner, "windowId": sheet_id, "maxElements": 2000, "maxDepth": 25}) open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton" and e["enabled"]) - assert call("invoke", {**owner, "windowId": sheet_id, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] + assert call("click", {**owner, "windowId": sheet_id, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] wait_state(lambda state: bool(state["selectedFile"]) and Path(state["selectedFile"]).samefile(selected_file), "File picker did not return the intended file") # AppKit can retain the dismissed panel's hidden WindowServer window after @@ -217,8 +217,18 @@ def main(): call("performAction", {**owner, "snapshotId": current["snapshotId"], "elementId": window_element["elementId"], "action": "AXRaise"}) call("getState", primary_params) + current = call("getState", primary_params) + no_hover = {**button_target(current, "Increment primary"), "windowId": primary["windowId"]} + before = json.loads(state_path.read_text()) + denied = call("mouseMove", no_hover, "HOVER_UNAVAILABLE") + assert "systemPointerMoved" not in denied and "No input was sent" in denied["message"], denied + after = wait_state(lambda s: s["cursorSamples"] > before["cursorSamples"], "Cursor sampling stopped") + assert after["cursorChanges"] == before["cursorChanges"] and not after["hoverVisible"], after + def mouse_move(target): - result = call("mouseMove", target) + result = call("mouseMove", target if args.alternate_hover else {**target, "allowSystemPointer": True}) + if not args.alternate_hover: + assert result["hoverRoute"] == "system-pointer" and result["systemPointerMoved"] is True, result if args.alternate_hover: assert result["hoverRoute"] == "accessibility" and result["systemPointerMoved"] is False, result return result @@ -251,7 +261,7 @@ def main(): mouse_move(target) wait_state(lambda actual: actual["hoverVisible"], "Input-transparent overlay blocked hover") before = cycle_overlay(2) - call("mouseMove", target, "FOREGROUND_REQUIRED") + call("mouseMove", {**target, "allowSystemPointer": True}, "FOREGROUND_REQUIRED") after = wait_state(lambda actual: actual["cursorSamples"] >= before["cursorSamples"] + 2, "Pointer observation did not advance") assert after["cursorChanges"] == before["cursorChanges"], "Rejected hover moved the system pointer" diff --git a/packages/experimental/cua-macos/native/tests/electron_e2e.py b/packages/experimental/cua-macos/native/tests/electron_e2e.py index 0e2b966516..403bb21eba 100644 --- a/packages/experimental/cua-macos/native/tests/electron_e2e.py +++ b/packages/experimental/cua-macos/native/tests/electron_e2e.py @@ -134,7 +134,9 @@ def main(): call('mouseMove', {**owner, 'windowId': window_id, 'x': -1, 'y': 0}, 'INVALID_ARGUMENT') call('mouseMove', {**owner, 'windowId': window_id, 'x': 100000, 'y': 0}, 'INVALID_ARGUMENT') call('mouseMove', {**owner, 'snapshotId': state['snapshotId'], 'elementId': trigger['elementId'], 'x': 0}, 'INVALID_ARGUMENT') - call('mouseMove', {**owner, 'snapshotId': state['snapshotId'], 'elementId': trigger['elementId']}) + hover_target = {**owner, 'snapshotId': state['snapshotId'], 'elementId': trigger['elementId']} + call('mouseMove', hover_target, 'HOVER_UNAVAILABLE') + call('mouseMove', {**hover_target, 'allowSystemPointer': True}) actual = wait_state(lambda actual: actual['popupOpen'], 'Hover did not reveal delayed information') assert actual['pointerDowns'] == baseline and actual['lastMove'] == {'buttons': 0, 'trusted': True}, actual state = observe() @@ -149,13 +151,13 @@ def main(): target = {**owner, 'windowId': window_id, 'x': bounds[0] + bounds[2] / 2 - window['bounds']['x'], 'y': bounds[1] + bounds[3] / 2 - window['bounds']['y']} - call('mouseMove', target) + call('mouseMove', {**target, 'allowSystemPointer': True}) state = observe() assert 'Hover information' in state['tree'], 'Moving into the popup dismissed it' call('click', target) actual = wait_state(lambda actual: actual['popupClicks'] == expected_clicks, 'Popup action did not receive its click') assert actual['popupOpen'] and actual['pointerDowns'] == baseline + 1 and actual['popupClickTrusted'], actual - call('mouseMove', {**owner, 'windowId': window_id, 'x': 10, 'y': 40}) + call('mouseMove', {**owner, 'windowId': window_id, 'x': 10, 'y': 40, 'allowSystemPointer': True}) wait_state(lambda actual: not actual['popupOpen'], 'Leaving the hover region did not close it') hover_sequence() helper.eof() diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift index 38f82ac4a8..8bb26dfdb9 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift @@ -3,6 +3,17 @@ import Testing import CoreGraphics @testable import CuaNative +@Test func unavailableAXHoverRequiresExplicitSystemPointerPermission() throws { + do { + try AXHover.requireSystemPointer(allowed: false) + Issue.record("A default hover without an AX route was allowed to move the pointer") + } catch let failure as NativeFailure { + #expect(failure.code == "HOVER_UNAVAILABLE") + #expect(failure.message.contains("No input was sent")) + } + try AXHover.requireSystemPointer(allowed: true) +} + @Test func systemHoverRequiresTheForegroundUnobscuredTarget() throws { let owner = ProcessIdentity(pid: 42, startedSeconds: 1, startedMicroseconds: 0) let bounds = WindowBounds(x: 100, y: 100, width: 400, height: 300) diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index e2127a78ab..9da4e5f85a 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,7 +2,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 8d88d9c21e..52788c0752 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -32,6 +32,8 @@ export const inject = ['computerUse', 'tools', 'systemPrompt', 'subprocess', 'ag export interface Config extends CuaConfig { /** Interval in milliseconds between permission and position checks while the native guide is open. */ permissionPollIntervalMs: number + /** Allow mouseMove to move the visible system pointer when AX hover is unavailable. Off by default to avoid interrupting the user. */ + systemPointerHover: boolean /** * Source-build signing: `ad-hoc` (default) binds grants to the code hash; * an object selects an existing certificate in an explicitly configured keychain. @@ -42,6 +44,7 @@ export interface Config extends CuaConfig { /** Validate shared operation bounds and macOS source signing before preparing the helper. */ export const Config = Schema.object({ ...CuaConfigFields, + systemPointerHover: Schema.boolean().default(false), permissionPollIntervalMs: Schema.number().step(1).min(100).max(2 ** 31 - 1).default(1000), sourceSigning: Schema.union([ Schema.const('ad-hoc'), @@ -61,6 +64,7 @@ export const Config = Schema.object({ */ export async function apply(ctx: Context, config: Config): Promise { const backend = { createChannel: createSharedNativeChannel, guidance: GUIDANCE, capabilities: CAPABILITIES, + systemPointerHover: config.systemPointerHover, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { if (!isAbsolute(config.helperPath)) throw new Error('dsh-cua helperPath must be absolute') diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f0f5679623..7afb53b84c 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -27,6 +27,9 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('accessibility tree operations are available at app or window level') expect(PLATFORM_GUIDANCE).toContain('Simulated keyboard input is available at app level') expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') + const hover = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) + for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE', 'systemPointerHover']) expect(hover).toContain(term) + expect(COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- click('))).toContain('call app.activate() first') }) it('enumerates every available method once in its catalog entry', () => { diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index dd5a3911c6..aefc6fbee6 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -26,6 +26,7 @@ describe('native protocol generation', () => { { method: 'drag', params: { appHandle: 'app', windowId: 1, fromX: 1, fromY: 1, toX: 2, toY: 2, steps: 1 } }, { method: 'paste', params: { appHandle: 'app', text: 'text', maxClipboardBytes: 1024 } }, { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, + { method: 'mouseMove', params: { appHandle: 'app', windowId: 1, x: 0, y: 0, allowSystemPointer: true } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, { method: 'launchApp', params: { appHandle: 'pending' } }, { method: 'applicationIcons', params: { paths: ['/Applications/Fixture.app'] } }, diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 04f5b0dd80..38e632e6ae 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -61,7 +61,7 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ })) const config = { - permissionPollIntervalMs: 1000, + permissionPollIntervalMs: 1000, systemPointerHover: false, agentPreset: false, helperPath: resolve('fixture-helper'), sourceSigning: 'ad-hoc', buildTimeoutMs: 300_000, timeoutMs: 10_000, connectTimeoutMs: 5000, screenshotTimeoutMs: 5000, axTimeoutMs: 3000, maxRequestBytes: 1024, maxResponseBytes: 4096, maxClipboardBytes: 8192, pasteReadTimeoutMs: 1000, maxAppMatches: 20, graceMs: 10, textEventIntervalMs: 8, maxClickHoldMs: 7000, maxElements: 64, maxDepth: 8, dragDurationMs: 200, dragSteps: 10, @@ -109,7 +109,7 @@ class ImageAdapter extends LlmAdapter { const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } -async function setup(model?: { provider: string; model: string }) { +async function setup(model?: { provider: string; model: string }, systemPointerHover = false) { native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() native.instances.length = 0 @@ -119,7 +119,7 @@ async function setup(model?: { provider: string; model: string }) { await mountAgentLoopTestDependencies(ctx) await ctx.plugin(ComputerUseRegistry) await ctx.plugin(Subprocess, []) - const provider = await ctx.plugin(NativeProvider, config) + const provider = await ctx.plugin(NativeProvider, { ...config, systemPointerHover }) await mountAgentLoopTestHarness(ctx) const handle = await ctx.agents.create({ sessionId: SessionId('native-lifecycle'), ...model ? { agentOptions: model } : {} }) let index = 0 @@ -398,6 +398,14 @@ it.each([false, true])('rejects an ended Agent with prior helper acquisition %s' expect(native.request).toHaveBeenCalledTimes(requests) }) +it.each([false, true])('passes the deployment hover policy (%s) to native input', async (allowed) => { + const f = await setup(undefined, allowed) + await selectApplication(f) + const params = { appHandle: 'app-one', windowId: 7, snapshotId: 's', elementId: '0' } + await f.execute('mouseMove', params) + expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...params, allowSystemPointer: allowed }, expect.any(AbortSignal), expect.any(String)) +}) + it('supplies configured resource bounds and clears registrations on unload', async () => { const f = await setup() await selectApplication(f) diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index adf62b8b5e..1d6d0266d1 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -32,12 +32,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index d6c75f46bc..7cb5177f71 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -126,6 +126,8 @@ export interface CuaBackend { createChannel: NativeChannelFactory guidance: string capabilities: CuaStartupCapabilities + /** macOS deployment policy sent only to the native mouseMove operation. */ + systemPointerHover?: boolean /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -211,6 +213,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient + if (method === 'mouseMove' && backend.systemPointerHover !== undefined) params.allowSystemPointer = backend.systemPointerHover const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' diff --git a/packages/experimental/cua/src/native-schema.ts b/packages/experimental/cua/src/native-schema.ts index c62a5e6b42..bbd52e2591 100644 --- a/packages/experimental/cua/src/native-schema.ts +++ b/packages/experimental/cua/src/native-schema.ts @@ -13,15 +13,15 @@ function variants(schema: Schema): Schema[] { return schema.anyOf ?? schema.oneO /** * Derive native request schemas and admission fields from the shared operation definitions. - * @param permissionFields Platform-specific parameters for user-facing permission controls. + * @param platformFields Platform-specific parameters added by the Host before native dispatch. * @returns Native field and enum tables and the complete wire schema. */ -export function nativeProtocol(permissionFields: Partial> = {}): { +export function nativeProtocol(platformFields: Partial> = {}): { fields: Map> enums: Map>> json: string } { - const resources = new Map(Object.entries({ ...NativeResourceParameters, ...permissionFields })) + const resources = new Map(Object.entries({ ...NativeResourceParameters, ...platformFields })) const schemas = [...Request.options, ...NativeOnlyOperations] .map(schema => z.toJSONSchema(schema)) const fields = new Map>() diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b44e8f4ef6..4e5f1ef0d9 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -190,10 +190,11 @@ export interface CuaWindow extends CuaSurface { */ getScreenshot(options?: CuaObservationOptions): Promise /** - * Reveal advertised AX alternate UI, otherwise move the system cursor without pressing a button. - * The system-pointer route requires the app to be foreground and the point unobscured; never activates or raises it. - * Returning and subsequent observations do not restore the previous pointer position. - * Other input and application changes can interrupt hover; observe before continuing. + * On macOS, prefer an available control's click or advertised accessibility action over hover. + * By default, mouseMove reveals or restores alternate UI on an enabled target or ancestor that advertises + * both AXShowAlternateUI and AXShowDefaultUI. Without an AX route it throws HOVER_UNAVAILABLE before sending input. + * Only the macOS provider's systemPointerHover setting permits moving the visible cursor as a fallback. + * That route requires a foreground app and an unobscured target and leaves the cursor at the destination. * @param target - current element id or screenshot-local [x,y]. * @param options - coordinate mode; applies only to [x,y]. * @returns dispatch evidence and the selected route; observe the resulting UI after its hover delay. @@ -201,7 +202,8 @@ export interface CuaWindow extends CuaSurface { mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions): Promise /** * Click an element or a point in this window. On macOS both forms send mouse-down and mouse-up events. - * Use {@link CuaSurface.invoke} for the element's default accessibility action. + * For a background control, prefer {@link CuaSurface.invoke} for its default action. When a mouse click is needed, + * call app.activate() first and observe the target again. Background apps can ignore dispatched mouse events. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. * @param target - On macOS, an id from the latest tree targets the element center. A coordinate pair targets the given point. * @param options - button, click count, modifiers, optional hold duration and coordinate mode. diff --git a/snapshots/session/cua-native/replay.override.json b/snapshots/session/cua-native/replay.override.json index 42d5c9d7af..b43a6e20f0 100644 --- a/snapshots/session/cua-native/replay.override.json +++ b/snapshots/session/cua-native/replay.override.json @@ -1385,6 +1385,39 @@ } ] }, + { + "kind": "chunks", + "chunks": [ + { + "type": "block-start", + "index": 0, + "blockType": "tool-call" + }, + { + "type": "block-end", + "index": 0, + "block": { + "type": "tool-call", + "id": "cua-hover-unavailable", + "name": "cua", + "arguments": "{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}" + } + }, + { + "type": "usage", + "usage": { + "inputTokens": 3, + "outputTokens": 3 + } + }, + { + "type": "finish", + "reason": { + "kind": "tool-calls" + } + } + ] + }, { "kind": "chunks", "chunks": [ diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 6e32a6a9d3..1738793701 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -67,12 +67,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index b10d4793e0..0786eeefe6 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -199,12 +199,20 @@ function createApplicationState(socket, record, application, captureBroker, conn if (!observed) refuse('STALE_SNAPSHOT', 'Read fresh state before acting') if (params.windowId !== undefined && observed.windowId !== null && observed.windowId !== params.windowId) refuse('STALE_SNAPSHOT', `Snapshot belongs to window ${observed.windowId}; read getAccessibilityTree on window ${params.windowId}`) if (observed.axless && params.elementId !== undefined) refuse('INVALID_ARGUMENT', 'Element id is absent from the selected snapshot') - if (method === 'mouseMove') application.hovering = params.elementId === '0' || (params.x >= 20 && params.x <= 40) + let systemPointerMoved = false + if (method === 'mouseMove') { + const alternate = params.elementId === '0' || (params.x >= 20 && params.x <= 40) + if (!alternate && !application.hovering) { + if (!params.allowSystemPointer) refuse('HOVER_UNAVAILABLE', 'No AX alternate UI at this target. No input was sent and the pointer did not move.') + systemPointerMoved = true + } + application.hovering = alternate + } else if (method === 'click' && params.windowId === 8) application.visualCount++ else if (method === 'click') application.count++ else application.value = params.value record('state', { count: application.count, value: application.value, visualCount: application.visualCount }) - return { dispatched: true, ...method === 'mouseMove' ? { hoverRoute: 'accessibility', systemPointerMoved: false } : {} } + return { dispatched: true, ...method === 'mouseMove' ? { hoverRoute: systemPointerMoved ? 'system-pointer' : 'accessibility', systemPointerMoved } : {} } } if (method === 'pressKey' && params.key === 'Return') observationChanged = true // Fixture-only keys simulate a pending system callback and its eventual completion. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 81450a3782..ff29eddb7f 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -69,12 +69,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 743dd9cc1f..434e92e3f7 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -69,12 +69,12 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — reveal AX alternate UI or move the system pointer without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Use invoke(id) for the default accessibility action. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then call app.activate() and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. From ca163024ab80f64f58532e47235b4bd3aaddd4c3 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:25:22 +0800 Subject: [PATCH 029/103] Replay a refused pointer-free hover after dismissing alternate UI --- snapshots/session/cua-native/session.v4.jsonl | 169 +++++++++--------- 1 file changed, 87 insertions(+), 82 deletions(-) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 29c6f99a65..10a71dc794 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -12,281 +12,286 @@ {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"}} {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947688973,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947688973,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947688973,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949731596,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949731597,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1793949731597,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949731597,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689573,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689573,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689573,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732188,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732188,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949732188,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732188,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-getState"},"toolCallId":"cua-unauthorized-getState","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:7}}"}},"sourceEventSeqs":[19],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689596,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689596,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689596,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732206,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732206,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732206,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732206,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"cua-unauthorized-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-screenshot"},"toolCallId":"cua-unauthorized-screenshot","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:9}}"}},"sourceEventSeqs":[24],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} {"type":"step/start","data":{"turn":1,"step":4}} -{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689615,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689615,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689615,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:10}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732224,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732224,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1793949732224,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732224,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":4,"callId":"cua-unauthorized-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\"}}"}} {"type":"tool/result","data":{"turn":1,"step":4,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-unauthorized-click"},"toolCallId":"cua-unauthorized-click","content":[{"type":"text","text":"Error: APP_ACCESS_REQUIRED: Select the application with getApp and obtain user consent before reading or controlling it"}],"isError":true,"id":"{{message:11}}"}},"sourceEventSeqs":[29],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":4}} {"type":"step/start","data":{"turn":1,"step":5}} -{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689634,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689634,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689634,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732241,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732241,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}}},{"type":"chunk","time":1793949732241,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732241,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":5,"callId":"cua-native-2","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"test.fixture\"}}"}} {"type":"tool/result","data":{"turn":1,"step":5,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-2"},"toolCallId":"cua-native-2","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"name\":\"Fixture\",\"bundleId\":\"test.fixture\",\"running\":true}"}],"isError":false,"id":"{{message:13}}"}},"sourceEventSeqs":[34],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":5}} {"type":"step/start","data":{"turn":1,"step":6}} -{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689657,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689657,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689657,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":6,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:14}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732276,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732276,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}}},{"type":"chunk","time":1793949732276,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732276,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":6,"callId":"cua-native-3","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"includeMenus\":true,\"details\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":6,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-3"},"toolCallId":"cua-native-3","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-1\",\"tree\":\"AX scope=window offsets=UTF-16 bounds=global-points\\n- [0] AXButton \\\"Increment\\\" id=\\\"increment\\\" actions=[\\\"AXPress\\\"] bounds=[60,80,100,20]\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 0\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\n - [3] AXMenuItem \\\"Fixture command\\\"\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:15}}"}},"sourceEventSeqs":[39],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":6}} {"type":"step/start","data":{"turn":1,"step":7}} -{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689683,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689683,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689683,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":7,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:16}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732298,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732298,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}}},{"type":"chunk","time":1793949732298,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732298,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":7,"callId":"cua-native-4","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-1\",\"elementId\":\"0\",\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":7,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-4"},"toolCallId":"cua-native-4","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:17}}"}},"sourceEventSeqs":[44],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":7}} {"type":"step/start","data":{"turn":1,"step":8}} -{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689706,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689706,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689706,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":8,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:18}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732316,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732316,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732316,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732316,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":8,"callId":"cua-native-5","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":8,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-5"},"toolCallId":"cua-native-5","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-2\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:19}}"}},"sourceEventSeqs":[49],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":8}} {"type":"step/start","data":{"turn":1,"step":9}} -{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689729,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689729,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689729,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":9,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:20}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732333,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732333,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732333,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732333,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":9,"callId":"cua-native-6","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":9,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-6"},"toolCallId":"cua-native-6","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:21}}"}},"sourceEventSeqs":[54],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":9}} {"type":"step/start","data":{"turn":1,"step":10}} -{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689792,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689792,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689792,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":10,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:22}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732405,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732405,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949732405,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732405,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":10,"callId":"cua-native-7","name":"cua","arguments":"{\"method\":\"listWindows\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":10,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-7"},"toolCallId":"cua-native-7","content":[{"type":"text","text":"[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true},{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}]"}],"isError":false,"id":"{{message:23}}"}},"sourceEventSeqs":[59],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":10}} {"type":"step/start","data":{"turn":1,"step":11}} -{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689834,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689834,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689834,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":11,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:24}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732424,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732424,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793949732424,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732424,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":11,"callId":"cua-native-8","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":11,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-8"},"toolCallId":"cua-native-8","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:25}}"}},"sourceEventSeqs":[64],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":11}} {"type":"step/start","data":{"turn":1,"step":12}} -{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689861,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689861,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689861,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":12,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:26}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732445,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732445,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793949732445,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732445,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":12,"callId":"cua-native-9","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":12,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-9"},"toolCallId":"cua-native-9","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":8,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:27}}"}},"sourceEventSeqs":[69],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":12}} {"type":"step/start","data":{"turn":1,"step":13}} -{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689896,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689896,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689896,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":13,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:28}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732481,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732481,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}}},{"type":"chunk","time":1793949732481,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732481,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":13,"callId":"cua-native-10","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-3\",\"x\":0,\"y\":0}}"}} {"type":"tool/result","data":{"turn":1,"step":13,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-10"},"toolCallId":"cua-native-10","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:29}}"}},"sourceEventSeqs":[74],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":13}} {"type":"step/start","data":{"turn":1,"step":14}} -{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689918,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689918,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689918,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":14,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:30}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732502,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732502,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}}},{"type":"chunk","time":1793949732502,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732502,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":14,"callId":"cua-native-11","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8}}"}} {"type":"tool/result","data":{"turn":1,"step":14,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-11"},"toolCallId":"cua-native-11","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"tree\":\"\",\"windows\":[{\"windowId\":8,\"appName\":\"Fixture\",\"title\":\"AXless canvas\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:31}}"}},"sourceEventSeqs":[79],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":14}} {"type":"step/start","data":{"turn":1,"step":15}} -{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689940,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689940,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689940,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":15,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:32}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732523,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732523,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732523,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732523,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":15,"callId":"cua-native-show","name":"cua","arguments":"{\"method\":\"show\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":15,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-show"},"toolCallId":"cua-native-show","content":[{"type":"text","text":"{\"dispatched\":true,\"windowId\":7,\"foregroundChanged\":false}"}],"isError":false,"id":"{{message:33}}"}},"sourceEventSeqs":[84],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":15}} {"type":"step/start","data":{"turn":1,"step":16}} -{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689961,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689961,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689961,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":16,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:34}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732546,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732546,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949732546,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732546,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":16,"callId":"cua-native-activate-first","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":16,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-first"},"toolCallId":"cua-native-activate-first","content":[{"type":"text","text":"{\"dispatched\":true,\"foregroundChanged\":true,\"foreground\":{\"requestId\":\"cua-native-activate-first\",\"targetPid\":9,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true}}"}],"isError":false,"id":"{{message:35}}"}},"sourceEventSeqs":[89],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":16}} {"type":"step/start","data":{"turn":1,"step":17}} -{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947689983,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947689983,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947689983,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":17,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:36}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732573,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732573,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949732573,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732573,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":17,"callId":"cua-native-activate-repeat","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} {"type":"tool/result","data":{"turn":1,"step":17,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-activate-repeat"},"toolCallId":"cua-native-activate-repeat","content":[{"type":"text","text":"{\"dispatched\":true,\"foregroundChanged\":false,\"foreground\":{\"requestId\":\"cua-native-activate-repeat\",\"targetPid\":9,\"before\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":false}}"}],"isError":false,"id":"{{message:37}}"}},"sourceEventSeqs":[94],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":17}} {"type":"step/start","data":{"turn":1,"step":18}} -{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690002,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690002,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690002,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":18,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:38}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732598,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732598,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}}},{"type":"chunk","time":1793949732598,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732598,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":18,"callId":"cua-native-transition","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"Return\"}}"}} {"type":"tool/result","data":{"turn":1,"step":18,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-transition"},"toolCallId":"cua-native-transition","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:39}}"}},"sourceEventSeqs":[99],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":18}} {"type":"step/start","data":{"turn":1,"step":19}} -{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690019,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690019,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690019,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":19,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:40}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732622,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732622,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732622,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732622,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":19,"callId":"cua-native-stale-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":19,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-read"},"toolCallId":"cua-native-stale-read","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Accessibility tree changed during observation; read fresh getAccessibilityTree"}],"isError":true,"id":"{{message:41}}"}},"sourceEventSeqs":[104],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":19}} {"type":"step/start","data":{"turn":1,"step":20}} -{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690040,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690040,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690040,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":20,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:42}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732643,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732643,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1793949732643,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732643,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":20,"callId":"cua-native-stale-index","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-2\",\"elementId\":\"0\"}}"}} {"type":"tool/result","data":{"turn":1,"step":20,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-stale-index"},"toolCallId":"cua-native-stale-index","content":[{"type":"text","text":"Error: STALE_SNAPSHOT: Read fresh state before acting"}],"isError":true,"id":"{{message:43}}"}},"sourceEventSeqs":[109],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":20}} {"type":"step/start","data":{"turn":1,"step":21}} -{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690064,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690064,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690064,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":21,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:44}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732663,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732663,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}}},{"type":"chunk","time":1793949732663,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732663,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":21,"callId":"cua-native-other-window","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":8,\"snapshotId\":\"fixture-snapshot-4\",\"x\":0,\"y\":0,\"holdMs\":800}}"}} {"type":"tool/result","data":{"turn":1,"step":21,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-other-window"},"toolCallId":"cua-native-other-window","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:45}}"}},"sourceEventSeqs":[114],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":21}} {"type":"step/start","data":{"turn":1,"step":22}} -{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690087,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690087,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690087,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":22,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:46}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732687,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732687,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732687,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732687,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":22,"callId":"cua-native-fresh-read","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":22,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-read"},"toolCallId":"cua-native-fresh-read","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-5\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 1\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:47}}"}},"sourceEventSeqs":[119],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":22}} {"type":"step/start","data":{"turn":1,"step":23}} -{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690111,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690111,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690111,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":23,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:48}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732710,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732710,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1793949732710,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732710,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":23,"callId":"cua-native-fresh-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-5\",\"elementId\":\"0\"}}"}} {"type":"tool/result","data":{"turn":1,"step":23,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-fresh-click"},"toolCallId":"cua-native-fresh-click","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:49}}"}},"sourceEventSeqs":[124],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":23}} {"type":"step/start","data":{"turn":1,"step":24}} -{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690141,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690141,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690141,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":24,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:50}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732733,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732733,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732733,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732733,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":24,"callId":"cua-native-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":24,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-verify"},"toolCallId":"cua-native-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-6\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:51}}"}},"sourceEventSeqs":[129],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":24}} {"type":"step/start","data":{"turn":1,"step":25}} -{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690162,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690162,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690162,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":25,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:52}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732756,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732756,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793949732756,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732756,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":25,"callId":"cua-native-geometry-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":25,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-observe"},"toolCallId":"cua-native-geometry-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 2\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:53}}"}},"sourceEventSeqs":[134],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":25}} {"type":"step/start","data":{"turn":1,"step":26}} -{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690186,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690186,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690186,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":26,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:54}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732777,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732777,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793949732777,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732777,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":26,"callId":"cua-native-geometry-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":26,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-capture"},"toolCallId":"cua-native-geometry-capture","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:55}}"}},"sourceEventSeqs":[139],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":26}} {"type":"step/start","data":{"turn":1,"step":27}} -{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690221,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690221,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690221,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":27,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:56}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732798,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732798,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}}},{"type":"chunk","time":1793949732798,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732798,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":27,"callId":"cua-native-geometry-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-7\",\"x\":20,\"y\":20,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":27,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-click"},"toolCallId":"cua-native-geometry-click","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:57}}"}},"sourceEventSeqs":[144],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":27}} {"type":"step/start","data":{"turn":1,"step":28}} -{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690248,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690248,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690248,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":28,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:58}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732822,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732822,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}}},{"type":"chunk","time":1793949732822,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732822,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":28,"callId":"cua-native-geometry-scroll","name":"cua","arguments":"{\"method\":\"scroll\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"x\":20,\"y\":20,\"deltaLinesX\":0,\"deltaLinesY\":-1,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":28,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-scroll"},"toolCallId":"cua-native-geometry-scroll","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:59}}"}},"sourceEventSeqs":[149],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":28}} {"type":"step/start","data":{"turn":1,"step":29}} -{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690267,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690267,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690267,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":29,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:60}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732845,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732845,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}}},{"type":"chunk","time":1793949732845,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732845,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":29,"callId":"cua-native-geometry-drag","name":"cua","arguments":"{\"method\":\"drag\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9,\"fromX\":20,\"fromY\":20,\"toX\":30,\"toY\":30,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":29,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-drag"},"toolCallId":"cua-native-geometry-drag","content":[{"type":"text","text":"Error: WINDOW_CHANGED: Window display and accessibility bounds disagree. Read fresh state; if unchanged, use AX actions or explicitly restore the window before capture or coordinate input"}],"isError":true,"id":"{{message:61}}"}},"sourceEventSeqs":[154],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":29}} {"type":"step/start","data":{"turn":1,"step":30}} -{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690294,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690294,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690294,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":30,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:62}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732870,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732870,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1793949732870,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732870,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":30,"callId":"cua-native-geometry-ax","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-7\",\"elementId\":\"0\"}}"}} {"type":"tool/result","data":{"turn":1,"step":30,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-ax"},"toolCallId":"cua-native-geometry-ax","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:63}}"}},"sourceEventSeqs":[159],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":30}} {"type":"step/start","data":{"turn":1,"step":31}} -{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690314,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690314,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690314,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":31,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:64}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732900,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732900,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}}},{"type":"chunk","time":1793949732900,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732900,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":31,"callId":"cua-native-geometry-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":9}}"}} {"type":"tool/result","data":{"turn":1,"step":31,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-geometry-verify"},"toolCallId":"cua-native-geometry-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":9,\"snapshotId\":\"fixture-snapshot-8\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":9,\"appName\":\"Fixture\",\"title\":\"Transformed window\",\"bounds\":{\"x\":16,\"y\":512,\"width\":131,\"height\":145},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:65}}"}},"sourceEventSeqs":[164],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":31}} {"type":"step/start","data":{"turn":1,"step":32}} -{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690340,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690340,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690340,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":32,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:66}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732924,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732924,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}}},{"type":"chunk","time":1793949732924,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732924,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":32,"callId":"cua-capture-busy-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F11\"}}"}} {"type":"tool/result","data":{"turn":1,"step":32,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-arm"},"toolCallId":"cua-capture-busy-arm","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:67}}"}},"sourceEventSeqs":[169],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":32}} {"type":"step/start","data":{"turn":1,"step":33}} -{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690365,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690365,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690365,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":33,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:68}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732947,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732947,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732947,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732947,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":33,"callId":"cua-capture-busy","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":33,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy"},"toolCallId":"cua-capture-busy","content":[{"type":"text","text":"Error: CAPTURE_BUSY: A previous system capture is still pending; other native operations remain available\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-capture-busy\",\"stage\":\"helper.failed\",\"elapsedMs\":1,\"errorCode\":\"CAPTURE_BUSY\"}"}],"isError":true,"id":"{{message:69}}"}},"sourceEventSeqs":[174],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":33}} {"type":"step/start","data":{"turn":1,"step":34}} -{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690394,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690394,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690394,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":34,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:70}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732969,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732969,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949732969,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732969,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":34,"callId":"cua-capture-busy-ax","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":34,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-busy-ax"},"toolCallId":"cua-capture-busy-ax","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-9\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:71}}"}},"sourceEventSeqs":[179],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":34}} {"type":"step/start","data":{"turn":1,"step":35}} -{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690414,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690414,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690414,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":35,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:72}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732988,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732988,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}}},{"type":"chunk","time":1793949732988,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732988,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":35,"callId":"cua-capture-callback","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F10\"}}"}} {"type":"tool/result","data":{"turn":1,"step":35,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-callback"},"toolCallId":"cua-capture-callback","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:73}}"}},"sourceEventSeqs":[184],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":35}} {"type":"step/start","data":{"turn":1,"step":36}} -{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690434,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690434,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690434,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":36,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:74}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733007,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733007,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733007,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733007,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":36,"callId":"cua-capture-recovered","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":36,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-capture-recovered"},"toolCallId":"cua-capture-recovered","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:75}}"}},"sourceEventSeqs":[189],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":36}} {"type":"step/start","data":{"turn":1,"step":37}} -{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690466,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690466,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690466,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":37,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementId\":\"0\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:76}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733041,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733041,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementId\":\"0\"}}"}}},{"type":"chunk","time":1793949733041,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733041,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":37,"callId":"cua-hover-enter","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"snapshotId\":\"fixture-snapshot-9\",\"elementId\":\"0\"}}"}} {"type":"tool/result","data":{"turn":1,"step":37,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-enter"},"toolCallId":"cua-hover-enter","content":[{"type":"text","text":"{\"dispatched\":true,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:77}}"}},"sourceEventSeqs":[194],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":37}} {"type":"step/start","data":{"turn":1,"step":38}} -{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690495,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690495,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690495,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":38,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:78}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733060,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733060,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733060,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733060,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":38,"callId":"cua-hover-observe","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":38,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-observe"},"toolCallId":"cua-hover-observe","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 3\\\"\\n- AXStaticText \\\"Hover information\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:79}}"}},"sourceEventSeqs":[199],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":38}} {"type":"step/start","data":{"turn":1,"step":39}} -{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690517,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690517,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690517,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":39,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:80}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733087,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733087,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733087,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733087,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":39,"callId":"cua-hover-capture","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} {"type":"tool/result","data":{"turn":1,"step":39,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-capture"},"toolCallId":"cua-hover-capture","content":[{"type":"text","text":"{\"pixelWidth\":1,\"pixelHeight\":1,\"windowId\":7,\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"coordinateSpace\":\"screenshot-pixels\"}"},{"type":"image","attachment":{"attachmentId":"sha256:999f1d1527ee7e79266f16add5430fff76b1225d742464a5b1ff1f02971bb8ee","mediaType":"image/png","width":1,"height":1,"bytes":90}}],"isError":false,"id":"{{message:81}}"}},"sourceEventSeqs":[204],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":39}} {"type":"step/start","data":{"turn":1,"step":40}} -{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690565,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690565,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690565,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":40,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:82}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733130,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733130,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793949733130,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733130,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":40,"callId":"cua-hover-popup","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":40,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-popup"},"toolCallId":"cua-hover-popup","content":[{"type":"text","text":"{\"dispatched\":true,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:83}}"}},"sourceEventSeqs":[209],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":40}} {"type":"step/start","data":{"turn":1,"step":41}} -{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690590,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690590,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690590,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":41,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:84}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733147,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733147,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793949733147,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733147,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":41,"callId":"cua-hover-click","name":"cua","arguments":"{\"method\":\"click\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-10\",\"x\":100,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":41,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-click"},"toolCallId":"cua-hover-click","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:85}}"}},"sourceEventSeqs":[214],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":41}} {"type":"step/start","data":{"turn":1,"step":42}} -{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690613,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690613,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690613,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":42,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:86}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733164,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733164,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793949733164,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733164,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":42,"callId":"cua-hover-exit","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} {"type":"tool/result","data":{"turn":1,"step":42,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-exit"},"toolCallId":"cua-hover-exit","content":[{"type":"text","text":"{\"dispatched\":true,\"hoverRoute\":\"accessibility\",\"systemPointerMoved\":false}"}],"isError":false,"id":"{{message:87}}"}},"sourceEventSeqs":[219],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":42}} {"type":"step/start","data":{"turn":1,"step":43}} -{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690633,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690633,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690633,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":43,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:88}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733183,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733183,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}}},{"type":"chunk","time":1793949733183,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733183,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":43,"callId":"cua-hover-unavailable","name":"cua","arguments":"{\"method\":\"mouseMove\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7,\"x\":0,\"y\":200,\"relative\":true}}"}} +{"type":"tool/result","data":{"turn":1,"step":43,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-unavailable"},"toolCallId":"cua-hover-unavailable","content":[{"type":"text","text":"Error: HOVER_UNAVAILABLE: No AX alternate UI at this target. No input was sent and the pointer did not move."}],"isError":true,"id":"{{message:89}}"}},"sourceEventSeqs":[224],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":43}} {"type":"step/start","data":{"turn":1,"step":44}} -{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690653,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690653,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690653,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":44,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:90}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733201,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733201,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733201,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733201,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":44,"callId":"cua-hover-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":44,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-hover-verify"},"toolCallId":"cua-hover-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-11\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:91}}"}},"sourceEventSeqs":[229],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":44}} {"type":"step/start","data":{"turn":1,"step":45}} -{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690672,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690672,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690672,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":45,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:92}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733220,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733220,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}}},{"type":"chunk","time":1793949733220,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733220,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":45,"callId":"cua-paste-background","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F9\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":45,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-background"},"toolCallId":"cua-paste-background","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:93}}"}},"sourceEventSeqs":[234],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":45}} {"type":"step/start","data":{"turn":1,"step":46}} -{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690696,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690696,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690696,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":46,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:94}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733238,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733238,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793949733238,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733238,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":46,"callId":"cua-paste-unread","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":46,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-unread"},"toolCallId":"cua-paste-unread","content":[{"type":"text","text":"Error: PASTE_NOT_CONSUMED: Paste command was dispatched, but clipboard data was not requested within the read deadline. Bring the target app to the foreground and focus its text input. Inspect the contents before deciding whether to retry; a delayed paste may still run."}],"isError":true,"id":"{{message:95}}"}},"sourceEventSeqs":[239],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":46}} {"type":"step/start","data":{"turn":1,"step":47}} -{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690714,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690714,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690714,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"foregroundChanged\":true,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"targetPid\":9,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true}}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":47,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:96}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733260,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733260,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733260,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733260,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":47,"callId":"cua-paste-inspect","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":47,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-inspect"},"toolCallId":"cua-paste-inspect","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-12\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:97}}"}},"sourceEventSeqs":[244],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":47}} {"type":"step/start","data":{"turn":1,"step":48}} -{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690734,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690734,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690734,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":48,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:98}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733280,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733280,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949733280,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733280,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":48,"callId":"cua-paste-activate","name":"cua","arguments":"{\"method\":\"activate\",\"params\":{\"appHandle\":\"fixture-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":48,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-activate"},"toolCallId":"cua-paste-activate","content":[{"type":"text","text":"{\"dispatched\":true,\"foregroundChanged\":true,\"foreground\":{\"requestId\":\"cua-paste-activate\",\"targetPid\":9,\"before\":{\"frontPid\":42,\"focusedWindowId\":7,\"frontWindowId\":99,\"frontWindowPid\":42},\"after\":{\"frontPid\":9,\"focusedWindowId\":7,\"frontWindowId\":7,\"frontWindowPid\":9},\"activationRequested\":true}}"}],"isError":false,"id":"{{message:99}}"}},"sourceEventSeqs":[249],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":48}} {"type":"step/start","data":{"turn":1,"step":49}} -{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690757,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690757,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690757,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":49,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:100}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733300,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733300,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733300,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733300,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":49,"callId":"cua-paste-focus","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":49,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-focus"},"toolCallId":"cua-paste-focus","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-13\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:101}}"}},"sourceEventSeqs":[254],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":49}} {"type":"step/start","data":{"turn":1,"step":50}} -{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690778,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690778,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690778,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":50,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:102}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733320,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733320,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}}},{"type":"chunk","time":1793949733320,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733320,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":50,"callId":"cua-paste-consumed","name":"cua","arguments":"{\"method\":\"paste\",\"params\":{\"appHandle\":\"fixture-app\",\"text\":\"fixture paste\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":50,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-consumed"},"toolCallId":"cua-paste-consumed","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:103}}"}},"sourceEventSeqs":[259],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":50}} {"type":"step/start","data":{"turn":1,"step":51}} -{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690801,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690801,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690801,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":51,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:104}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733340,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733340,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733340,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733340,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":51,"callId":"cua-paste-verify","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":51,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-paste-verify"},"toolCallId":"cua-paste-verify","content":[{"type":"text","text":"{\"appHandle\":\"fixture-app\",\"windowId\":7,\"snapshotId\":\"fixture-snapshot-14\",\"tree\":\"AX scope=window offsets=UTF-16\\n- [0] AXButton \\\"Increment\\\"\\n- [1] AXTextField valueWritable=true selectionWritable=true value=\\\"fixture paste\\\" placeholder=\\\"Fixture text\\\"\\n- AXStaticText \\\"Count: 4\\\"\\n- [2] AXMenuBarItem \\\"File\\\"\\nMenu contents omitted; request includeMenus=true to expand.\",\"windows\":[{\"windowId\":7,\"appName\":\"Fixture\",\"title\":\"CUA fixture\",\"bounds\":{\"x\":40,\"y\":60,\"width\":320,\"height\":200},\"isOnScreen\":true,\"onCurrentSpace\":true}],\"truncated\":false}"}],"isError":false,"id":"{{message:105}}"}},"sourceEventSeqs":[264],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":51}} {"type":"step/start","data":{"turn":1,"step":52}} -{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690821,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690821,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690821,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} -{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":52,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:106}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733361,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733361,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}}},{"type":"chunk","time":1793949733361,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733361,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":52,"callId":"cua-debug-arm","name":"cua","arguments":"{\"method\":\"pressKey\",\"params\":{\"appHandle\":\"fixture-app\",\"key\":\"F12\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":52,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-arm"},"toolCallId":"cua-debug-arm","content":[{"type":"text","text":"{\"dispatched\":true}"}],"isError":false,"id":"{{message:107}}"}},"sourceEventSeqs":[269],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":52}} {"type":"step/start","data":{"turn":1,"step":53}} -{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947690852,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947690852,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947690852,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":53,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:108}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733379,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733379,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}}},{"type":"chunk","time":1793949733379,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733379,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":53,"callId":"cua-debug-screenshot","name":"cua","arguments":"{\"method\":\"screenshot\",\"params\":{\"appHandle\":\"fixture-app\",\"windowId\":7}}"}} +{"type":"tool/result","data":{"turn":1,"step":53,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-debug-screenshot"},"toolCallId":"cua-debug-screenshot","content":[{"type":"text","text":"Error: NATIVE_PROTOCOL: Helper returned an invalid response; acquire fresh application handles\nScreenshot diagnostics:\n[cua-screenshot] {\"requestId\":\"cua-debug-screenshot\",\"stage\":\"capture-image.begin\",\"elapsedMs\":1}"}],"isError":true,"id":"{{message:109}}"}},"sourceEventSeqs":[274],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":53}} {"type":"step/start","data":{"turn":1,"step":54}} -{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691022,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"name\":\"Revocable Fixture\",\"running\":true}"}],"isError":false,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":54,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:110}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733403,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733403,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}}},{"type":"chunk","time":1793949733403,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733403,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":54,"callId":"cua-consent-denied","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Denied Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":54,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-denied"},"toolCallId":"cua-consent-denied","content":[{"type":"text","text":"Error: APP_ACCESS_DENIED: The user denied access to Denied Fixture. Do not retry or use another tool to bypass this decision."}],"isError":true,"id":"{{message:111}}"}},"sourceEventSeqs":[279],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":54}} {"type":"step/start","data":{"turn":1,"step":55}} -{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691192,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1791947691192,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691192,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} -{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} -{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":55,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:112}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733577,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733577,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}}},{"type":"chunk","time":1793949733577,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733577,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":55,"callId":"cua-consent-revocable","name":"cua","arguments":"{\"method\":\"getApp\",\"params\":{\"selector\":\"Revocable Fixture\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":55,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revocable"},"toolCallId":"cua-consent-revocable","content":[{"type":"text","text":"{\"appHandle\":\"revoked-app\",\"name\":\"Revocable Fixture\",\"running\":true}"}],"isError":false,"id":"{{message:113}}"}},"sourceEventSeqs":[284],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":55}} {"type":"step/start","data":{"turn":1,"step":56}} -{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791947691212,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1791947691212,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791947691212,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"assistant/message","data":{"turn":1,"step":56,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:114}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733745,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949733745,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}}},{"type":"chunk","time":1793949733745,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733745,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} +{"type":"tool/call","data":{"turn":1,"step":56,"callId":"cua-consent-revoked","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"revoked-app\"}}"}} +{"type":"tool/result","data":{"turn":1,"step":56,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-consent-revoked"},"toolCallId":"cua-consent-revoked","content":[{"type":"text","text":"Error: APP_ACCESS_REVOKED: Application access was revoked; stop using this application"}],"isError":true,"id":"{{message:115}}"}},"sourceEventSeqs":[289],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":56}} +{"type":"step/start","data":{"turn":1,"step":57}} +{"type":"assistant/message","data":{"turn":1,"step":57,"message":{"role":"assistant","content":[{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:116}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949733763,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"chunk","time":1793949733763,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"Observed Count: 4 after hovering, observing and clicking the revealed control. Moving away dismissed the hover information. Geometry conflicts rejected capture and coordinate gestures; the advertised AX button action remained available. No automatic activation or input retry was requested."}}},{"type":"chunk","time":1793949733763,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949733763,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":1,"step":57}} {"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} From 54387e9278a71fb5a441ed3ec5fa27dbeffb2ae9 Mon Sep 17 00:00:00 2001 From: yudshj Date: Fri, 6 Nov 2026 15:30:04 +0800 Subject: [PATCH 030/103] =?UTF-8?q?feat(open-in-app):=20=E6=9F=90=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E7=AC=AC=E4=B8=80=E6=AC=A1=E5=8F=B3=E9=94=AE=E6=97=B6?= =?UTF-8?q?=E6=9C=80=E5=A4=9A=E7=AD=89=20300=20ms=20=E5=85=B3=E8=81=94?= =?UTF-8?q?=E5=BA=94=E7=94=A8=E5=86=8D=E5=BC=B9=E5=87=BA=E8=8F=9C=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A file type without a recorded association answer now holds the file menu until the background query settles, 300 ms pass, or the menu closes, so the application row usually opens already named instead of changing after the menu appears. Later openings of the type still show the recorded answer at once and refresh in the background. Open menus track the answer they last applied per verification, so answers for other types never re-resolve them. README documents the wait and its first-opening delay. --- .../client/ui-open-in-app/README.i18n.yaml | 12 ++-- packages/client/ui-open-in-app/README.md | 5 +- packages/client/ui-open-in-app/README.zh.md | 5 +- .../src/client/context-menus.tsx | 67 ++++++++++++++----- .../ui-open-in-app/src/client/open-path.ts | 8 ++- .../tests/context-menu-actions.client.spec.ts | 51 +++++++++++++- 6 files changed, 116 insertions(+), 32 deletions(-) diff --git a/packages/client/ui-open-in-app/README.i18n.yaml b/packages/client/ui-open-in-app/README.i18n.yaml index a38fe57e45..60b0cb137d 100644 --- a/packages/client/ui-open-in-app/README.i18n.yaml +++ b/packages/client/ui-open-in-app/README.i18n.yaml @@ -18,11 +18,11 @@ en: b149da9963eb9837 zh: 2426ea37fbd0f8b7 /deepseek-ai-dsh-client-ui-open-in-app/use-this-package/what-to-expect: - en: 53d5d74d5b1d9b66 - zh: bdd9806dca51e957 + en: c9022effccebd157 + zh: 54e76ec13b5c1029 /deepseek-ai-dsh-client-ui-open-in-app/understand-the-implementation: - en: c26d8937f5d38119 - zh: d353c2377b9747aa + en: 423b66c7f36f7c40 + zh: 9b891fb7c8a8d240 /deepseek-ai-dsh-client-ui-open-in-app/further-exploration: en: 720527877e452a97 zh: b2241c7a336a3eeb @@ -33,8 +33,8 @@ en: ca75c51c89c2c9b0 zh: c2241315dc0c89c9 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work: - en: f206d2fefa52f81d - zh: 51025a6e19d01295 + en: 31af13d29ff76a1c + zh: 6a08bd80d71c6434 /deepseek-ai-dsh-client-ui-open-in-app/known-limitations-and-deferred-work/dev-note: en: 84f92568fc74adf1 zh: 286b47e6b5b1a556 diff --git a/packages/client/ui-open-in-app/README.md b/packages/client/ui-open-in-app/README.md index 5ab8a3894f..5664376801 100644 --- a/packages/client/ui-open-in-app/README.md +++ b/packages/client/ui-open-in-app/README.md @@ -43,7 +43,7 @@ Mounted controls with the same association reader and file share one query and i Workspace context menus reveal the captured folder through the shared directory application catalog. File-tree directories expose native reveal and Copy folder path; they do not offer file preview or save. -Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata, then name the application recorded for the file’s type without waiting for the Host. Until the Host first answers for that type, the row reads “Open in default application” and opens the file through its OS association. Each opening re-queries the Host in the background; a changed answer updates the open menu in place, and a failed query keeps the recorded answer. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. +Context menus contribute file preview, native application opening, original-file reveal, and URL navigation and copying through [ui-context-menu](../ui-context-menu/README.md). Session submenus resolve the captured Session ID’s directory rather than the main view, and observe application, operation, Session-list, and locale changes. Native operations report through the feature’s global toast after menu dismissal or target changes, without a second registry toast. Native file actions resolve Session paths through authorized metadata, then name the application recorded for the file’s type without waiting for the Host. A type’s first opening on the page waits up to 300 ms for the Host’s answer; if none arrives by then, the row reads “Open in default application” and opens the file through its OS association. Each opening re-queries the Host in the background; a changed answer updates the open menu in place, and a failed query keeps the recorded answer. Missing files disable path actions; image reveal requires an actual Host file and always targets that original. [ui-file-actions](../ui-file-actions/README.md) owns copy, download, save-as, and their completion feedback, including revealing the saved destination from its toast. File menus copy absolute paths without line numbers; URL copying preserves query and fragment. Image files also expose image copy and original download, alongside the existing file actions. Successful downloads and saves show the shared Toast; picker cancellation is silent. @@ -59,7 +59,7 @@ A file menu offers “Open in sidebar” and “Open in floating panel”, which [`session-open-with.ts`](src/client/session-open-with.ts) shares one resolver across the shared context-menu package’s `session` and `sessionHeader` targets; other contributions do not cross between those targets. The file-tree slot uses `OpenInAppAction` with its owner’s `absolutePath`; there is no independent Session-header opener slot. A page-lifetime [`controller`](src/client/controller.ts) owns availability, persisted choice, and launch POST state. Menu observers and injected component hooks read those same sources. Document-relative routes and payload types come from the Host’s browser-safe `@deepseek-ai/dsh-host-open-in-app/shared` subpath. Adapters resolve native and transport failures to named outcomes; skipped requests announce nothing. -The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening or plugin unload cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot; when its own file type’s answer changes, it re-resolves synchronously from the path its opening verified, so the context-menu registry keeps the other rows while the application row changes. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation. +The directory and file adapters supply application metadata and operations to [`OpenTargetButton`](src/client/OpenTargetButton.tsx), which owns menu ordering, default markers, icons, and sizing. Its injected reporter sends outcomes to one feature-owned `shell.overlay` toast, so switching Sessions or closing the initiating preview cannot discard the result. The file header and empty state share `FileOpenTarget`, while `OpenPathInjected.applications` queries `session.workspacePathApplications` through [`open-path.ts`](src/client/open-path.ts). The same controller keeps the page’s answers by association class, runs one background refresh at a time, which the next opening or plugin unload cancels, and publishes a new snapshot only when an answer changes. The file menu observes that snapshot; when its own file type’s answer changes, it re-resolves synchronously from the path its opening verified, so the context-menu registry keeps the other rows while the application row changes. A type without a recorded answer holds the file contribution until its refresh settles, 300 ms pass, or the menu closes; the registry opens the menu once every contribution is ready, so the whole menu waits. Opening uses `session.openWorkspacePath`; the Host revalidates an explicitly selected handler before launch. The directory adapter keeps the existing catalog routes. `FileRouteAction` supplies the same control to delivery cards and change review through `deliverables.file.actions` and `deliverables.review.file.actions`; their authenticated routes retain Session file authorization. A failed or unavailable file query therefore needs no platform-specific UI implementation.
@@ -94,6 +94,7 @@ The Host verifies the path through the composed filesystem before opening or rev - **The dictionaries gate the menu.** A host catalog extension without a matching `app.` entry in both dictionaries stays invisible instead of showing a raw id; extending the catalog means extending [`dsh-host-open-in-app`](../../host/open-in-app/README.md) and this package's locales together. - **Availability is read once per page.** An application installed while the page is open appears after a reload (and, host-side, after a host restart); the desktop answer behind the file controls is read once per page as well. - **File associations are cached by type for the page.** Files sharing a final name extension share one answer; extensions that differ only in case, such as `.PNG` and `.png`, are separate types. A per-document override, such as a macOS “Open with” choice for one file, can therefore show the type’s previous answer until the background query corrects the open menu. Linux content sniffing and multi-part extensions such as `.tar.gz` have the same effect, and one file’s empty answer shows the row disabled for the type’s other files the same way. Choosing the row before the correction opens the application that answer named. Names without an extension are recorded per path. Records, with one icon per application, grow with the file types seen and end with the page. +- **A type’s first file menu can open late.** The whole menu waits up to 300 ms for that type’s first answer on the page, and a slower answer still changes the row after opening. - **One background refresh at a time.** Opening another file menu cancels the previous menu’s unanswered query, so that type keeps its earlier answer, or none, until its next opening. - **One reveal label for every platform.** The Session Remote reports whether a desktop exists, not which file manager it runs, so the menu says "Show file location" rather than naming Finder or File Explorer as the delivery cards do. - **The delivery cards keep their own opener.** [`ui-deliverables`](../ui-deliverables/README.md) still opens declared files through its own Session-and-event routes; folding those cards onto the file controls here remains deferred. diff --git a/packages/client/ui-open-in-app/README.zh.md b/packages/client/ui-open-in-app/README.zh.md index dd65ffdb58..69598cbc60 100644 --- a/packages/client/ui-open-in-app/README.zh.md +++ b/packages/client/ui-open-in-app/README.zh.md @@ -43,7 +43,7 @@ kind: "package-reference" 工作区右键菜单通过共享的目录应用列表定位被点击的文件夹。文件树目录提供原生定位与复制文件夹路径,不提供文件预览或保存。 -右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,然后直接显示该文件类型已记录的应用,不等待 Host。Host 首次回答该类型之前,这一项显示“使用默认应用打开”,通过系统的文件关联打开文件。每次打开菜单都会在后台重新查询 Host;回答有变化时,已打开的菜单原地更新,查询失败则保留已记录的回答。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 +右键菜单通过 [ui-context-menu](../ui-context-menu/README.zh.md) 贡献文件预览、原生应用打开、原文件定位以及链接导航与复制。会话子菜单解析被捕获会话 ID 的目录,不使用主视图,并观察应用、操作、会话列表及语言变化。原生操作在菜单关闭或目标切换后仍通过本功能的全局 toast 报告,不产生第二个注册表提示。原生文件操作先通过授权元数据解析会话路径,然后直接显示该文件类型已记录的应用,不等待 Host。某个类型在本页面第一次打开菜单时,最多等待 Host 回答 300 毫秒;到时仍未回答,这一项显示“使用默认应用打开”,通过系统的文件关联打开文件。每次打开菜单都会在后台重新查询 Host;回答有变化时,已打开的菜单原地更新,查询失败则保留已记录的回答。文件不存在时禁用路径操作;图片定位要求实际 Host 文件,并始终针对原文件。[ui-file-actions](../ui-file-actions/README.zh.md) 负责复制、下载、另存为及完成提示,包括通过提示定位保存目标。 文件菜单复制不含行号的绝对路径;网址复制保留查询参数与锚点。图片文件在既有文件操作之外,还提供复制图片与下载原图。下载和保存成功后显示共享 Toast,取消选择器时不提示。 @@ -59,7 +59,7 @@ kind: "package-reference" [`session-open-with.ts`](src/client/session-open-with.ts) 为共享右键菜单包声明的 `session` 和 `sessionHeader` 目标共用一个解析器;其他贡献不会在这两种目标间扩散。文件树插槽通过所属组件的 `absolutePath` 使用 `OpenInAppAction`;会话头部没有独立打开按钮插槽。页面生命周期的 [`controller`](src/client/controller.ts) 持有可用性、持久化偏好与启动 POST 状态。菜单观察器和组件注入 hooks 读取同一组源。文档相对路由与载荷类型来自 Host 的浏览器安全子路径 `@deepseek-ai/dsh-host-open-in-app/shared`。适配器将原生操作及传输失败解析为具名结果;跳过的请求不播报。 -目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单或插件卸载会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照;只有本文件类型的回答变化时,才基于本次打开时验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。 +目录和文件适配器把应用信息与操作交给 [`OpenTargetButton`](src/client/OpenTargetButton.tsx),由它统一管理菜单顺序、默认标记、图标和尺寸。注入的回调将结果交给本功能在 `shell.overlay` 中持有的唯一 toast,因此切换会话或关闭发起操作的预览不会丢失结果。文件标题栏和空态共用 `FileOpenTarget`,`OpenPathInjected.applications` 通过 [`open-path.ts`](src/client/open-path.ts) 查询 `session.workspacePathApplications`。同一控制器按关联类别保存本页面的回答,同一时间只运行一次后台刷新(下一次打开菜单或插件卸载会取消尚未完成的刷新),只在回答变化时发布新快照。文件菜单观察该快照;只有本文件类型的回答变化时,才基于本次打开时验证的路径同步重新解析,因此右键菜单注册表保留其他各项,只有应用这一项原地变化。尚无记录的类型会让文件菜单项等到这次刷新结束、满 300 毫秒或菜单关闭;注册表在所有菜单项都就绪后才打开菜单,所以整个菜单都会等待。打开操作使用 `session.openWorkspacePath`,Host 在启动前重新验证指定的关联应用。`FileRouteAction` 通过 `deliverables.file.actions` 和 `deliverables.review.file.actions` 为交付卡片和变更对比页提供同一控件,其认证路由保留会话文件校验。目录适配器继续使用已有的应用列表路由,文件查询失败或不可用时无需增加平台专用的界面实现。
@@ -94,6 +94,7 @@ Host 在打开或定位前通过当前文件系统验证路径。没有对应 Ho - **词典把守菜单。** 主机目录的新条目若在两份词典中没有对应的 `app.` 条目,将保持不可见而不是显示裸 id;扩展目录意味着同时扩展 [`dsh-host-open-in-app`](../../host/open-in-app/README.zh.md) 与本包的 locale。 - **可用性每页只读一次。** 页面打开期间安装的应用要重新加载页面后才出现(主机侧还需主机重启);文件控件背后的桌面回答同样每页只读一次。 - **文件关联按类型在页面内缓存。** 最后一个扩展名相同的文件共用一个回答;只有大小写不同的扩展名(如 `.PNG` 和 `.png`)算作不同类型。因此单个文件的单独设置(例如 macOS 中只针对某个文件的“打开方式”)可能先显示该类型之前的回答,再由后台查询更正已打开的菜单。Linux 的内容嗅探和 `.tar.gz` 这类多段扩展名也有同样的效果;某个文件的空回答也会以同样的方式,让同类型其他文件的这一项先显示为禁用。在更正之前选择这一项,会用该回答中的应用打开。没有扩展名的文件按路径记录。记录以及每个应用的一份图标随出现过的文件类型增长,并在页面关闭时释放。 +- **某个类型的第一次文件菜单可能打开得较慢。** 整个菜单最多等待该类型在本页面的第一个回答 300 毫秒;回答更慢时,菜单打开后这一项仍会原地变化。 - **同一时间只有一次后台刷新。** 打开另一个文件的菜单会取消前一个菜单尚未返回的查询,该类型保留之前的回答(或仍没有回答),直到下次打开。 - **所有平台共用一个定位标签。** Session Remote 只报告有没有桌面,不报告它跑的是哪个文件管理器,所以菜单写「显示文件位置」,而不像交付卡片那样点名访达或文件资源管理器。 - **交付卡片保留自己的打开器。** [`ui-deliverables`](../ui-deliverables/README.zh.md) 仍通过自己按 Session 与事件定位的路由打开声明过的文件;把这些卡片并到这里的文件控件上仍属延期工作。 diff --git a/packages/client/ui-open-in-app/src/client/context-menus.tsx b/packages/client/ui-open-in-app/src/client/context-menus.tsx index 76e518ae3d..aa69108391 100644 --- a/packages/client/ui-open-in-app/src/client/context-menus.tsx +++ b/packages/client/ui-open-in-app/src/client/context-menus.tsx @@ -9,12 +9,38 @@ import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type {} from '@deepseek-ai/dsh-api-workspace-files/remote' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-browser/client' import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SessionWorkspacePathApplication } from '@deepseek-ai/dsh-api-session-controller/types' import type { OpenInAppController } from './controller.ts' import { fileAddressFor, resolveWorkspacePath } from '@deepseek-ai/dsh-util-workspace-path' import type { OpenInAppPathController } from './open-path.ts' import type { OpenInAppKey } from './locales.ts' import type { OpenInAppToastSource } from './open-toast.tsx' +type Applications = readonly SessionWorkspacePathApplication[] +/** A file menu's verified Host path and the association answer its resolution showed. */ +interface Verification { readonly absolutePath: string; readonly shown: Applications | undefined } + +/** + * How long a file menu waits for the first association answer of its file type before opening with the + * unnamed default-application row; most first answers arrive sooner, so the row rarely changes after opening. + */ +const FIRST_ANSWER_WAIT_MS = 300 + +/** + * @param pending - settles without rejecting. + * @param ms - longest wait. + * @param signal - ends the wait early. + * @returns settles when `pending` settles, after `ms`, or on abort, whichever comes first; the timer never outlives it. + */ +function settleWithin(pending: Promise, ms: number, signal: AbortSignal): Promise { + return new Promise((settle) => { + const done = (): void => { clearTimeout(timer); signal.removeEventListener('abort', done); settle() } + const timer = setTimeout(done, ms) + signal.addEventListener('abort', done, { once: true }) + void pending.then(done) + }) +} + /** * Register native opening, original-path reveal, and URL actions. * @param ctx - declared plugin dependencies. @@ -109,10 +135,10 @@ export function registerContextMenus( } }, ] } - // The Host path from each file target's latest successful stat, shared by menus open on one target object at once. - // A stat clears it while running; answers arriving meanwhile need no re-resolution, as that stat's resolution reads - // the newest answers. - const verified = new WeakMap() + // The Host path from each file target's latest successful stat and the answer its menu showed, shared by menus open + // on one target object at once. A stat clears it while running; answers arriving meanwhile need no re-resolution, as + // that stat's resolution reads the newest answers. + const verified = new WeakMap() // The target whose changed association answer is being applied; only that re-resolution reuses the verified path, // so every opening runs its own stat. The in-place update relies on the registry re-resolving synchronously from // the notification, without which the menu stats again, and on a synchronous resolution replacing rows without @@ -123,32 +149,39 @@ export function registerContextMenus( observe: target => [{ getSnapshot: paths.associations.getSnapshot.bind(paths.associations), subscribe: (listener: () => void) => { - // Answers for other file types leave this menu unchanged. - let shown: ReturnType + // The answer this subscription last applied for a verification; answers for other file types leave it unchanged. + let applied: { readonly verification: Verification; readonly applications: Applications | undefined } | undefined return paths.associations.subscribe(() => { - const absolutePath = verified.get(target) - if (absolutePath === undefined) return - const applications = paths.cachedApplications(absolutePath) - if (applications === shown) return - shown = applications + const verification = verified.get(target) + if (verification === undefined) return + const applications = paths.cachedApplications(verification.absolutePath) + const current = applied?.verification === verification ? applied.applications : verification.shown + if (applications === current) return + applied = { verification, applications } answering = target try { listener() } finally { answering = undefined } }) }, }], resolve: (target, signal) => { - const verifiedPath = answering === target ? verified.get(target) : undefined - if (verifiedPath !== undefined) return fileMenu(target, verifiedPath) + const reused = answering === target ? verified.get(target) : undefined + if (reused !== undefined) return fileMenu(target, reused.absolutePath) verified.delete(target) return (async () => { await paths.load() const absolutePath = await resolvePath(target.sessionId, target.path, signal) signal.throwIfAborted() - if (absolutePath !== undefined) { - verified.set(target, absolutePath) - // A cached answer shows at once; every opening re-queries so a changed association reaches this menu. - if (paths.desktop.getSnapshot() === true) paths.refreshApplications(absolutePath) + if (absolutePath === undefined) return fileMenu(target, undefined) + if (paths.desktop.getSnapshot() === true) { + // Every opening re-queries so a changed association reaches this menu; a type's first opening waits for it briefly. + const unanswered = paths.cachedApplications(absolutePath) === undefined + const refreshed = paths.refreshApplications(absolutePath) + if (unanswered) { + await settleWithin(refreshed, FIRST_ANSWER_WAIT_MS, signal) + signal.throwIfAborted() + } } + verified.set(target, { absolutePath, shown: paths.cachedApplications(absolutePath) }) return fileMenu(target, absolutePath) })() }, diff --git a/packages/client/ui-open-in-app/src/client/open-path.ts b/packages/client/ui-open-in-app/src/client/open-path.ts index ba17321fca..85ea703b5d 100644 --- a/packages/client/ui-open-in-app/src/client/open-path.ts +++ b/packages/client/ui-open-in-app/src/client/open-path.ts @@ -139,13 +139,15 @@ export class OpenInAppPathController { * Re-query a file's associations in the background. One refresh runs at a time: it outlives the * requesting menu and ends with its answer, the next refresh, which cancels it, or {@link dispose}. * @param path - absolute Host path of the file. + * @returns settles without rejecting when this refresh's query settles, after any answer is recorded; + * already settled after {@link dispose}. */ - refreshApplications(path: string): void { - if (this.lifetime.signal.aborted) return + refreshApplications(path: string): Promise { + if (this.lifetime.signal.aborted) return Promise.resolve() this.refresh?.abort() const refresh = new AbortController() this.refresh = refresh - void this.applications(path, AbortSignal.any([this.lifetime.signal, refresh.signal])) + return this.applications(path, AbortSignal.any([this.lifetime.signal, refresh.signal])).then(() => {}) } /** Cancel background refreshes and refuse new ones; recorded answers stay readable. */ diff --git a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts index 85a92ccac3..4a0e8963ae 100644 --- a/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts +++ b/packages/client/ui-open-in-app/tests/context-menu-actions.client.spec.ts @@ -122,7 +122,7 @@ it('routes file actions through an explicit host, the line, native association a const simple = { kind: 'file', value: { sessionId: SessionId('absent'), path: '/file.unknown' } } as const h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) const menu = await h.resolve(simple) - // Without an answer the row opens through the association; the Host's empty answer then disables it in place. + // The Host's empty answer arrives within the first-answer wait, so the row opens disabled. await vi.waitFor(() => { expect(menu.source.getSnapshot().find(item => item.id.endsWith('/open'))?.disabled).toBe(true) }) expect(menu.source.getSnapshot().some(item => item.id.endsWith('/copyImage'))).toBe(false) expect(menu.source.getSnapshot().filter(item => item.id.startsWith('file-actions.')).map(item => item.id)) @@ -136,7 +136,47 @@ it('routes file actions through an explicit host, the line, native association a expect(h.sidebar.openResourceIn).toHaveBeenLastCalledWith(SessionId('absent'), expect.any(String), { destination: 'float' }) }) -it('opens file menus before the Host answers and changes only the application row in place', async () => { +it('names the application when the first answer of a file type arrives within the wait', async () => { + const h = await boot() + // The answer arrives a macrotask later, after a resolution that did not wait would have published its rows. + h.remote.session.workspacePathApplications.mockImplementationOnce(() => new Promise((answer) => { + setTimeout(() => { answer({ ok: true, value: [{ id: 'preview', name: 'Preview', default: true, icon: null }] }) }, 10) + })) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + const labels: (string | undefined)[] = [] + const stop = menu.source.subscribe(() => { + labels.push(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')?.label) + }) + await menu.ready + stop() + expect(labels.filter(label => label !== undefined)).toEqual(['open.title']) + menu.dispose() +}) + +it('waits for the first answer of a file type at most 300 ms, and a dismissal ends the wait', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + onTestFinished(() => { vi.useRealTimers() }) + const h = await boot() + h.remote.session.workspacePathApplications.mockImplementation(() => new Promise(() => {})) + const menu = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'notes.txt' } }) + let ready = false + void menu.ready.then(() => { ready = true }) + await vi.advanceTimersByTimeAsync(299) + expect(ready).toBe(false) + await vi.advanceTimersByTimeAsync(1) + expect(ready).toBe(true) + expect(menu.source.getSnapshot().find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: false }) + menu.dispose() + const dismissed = h.registry.resolve({ kind: 'file', value: { sessionId, path: 'todo.md' } }) + await vi.advanceTimersByTimeAsync(100) + expect(vi.getTimerCount()).toBe(1) + dismissed.dispose() + await dismissed.ready + expect(vi.getTimerCount()).toBe(0) + expect(h.failure).not.toHaveBeenCalled() +}) + +it('opens file menus after the first-answer wait and changes only the application row in place', async () => { const h = await boot() const answers: ((answer: RemoteResult) => void)[] = [] h.remote.session.workspacePathApplications.mockImplementation(() => new Promise((answer) => { answers.push(answer) })) @@ -228,6 +268,13 @@ it('re-resolves an open file menu only when its own file type answers differentl await h.paths.applications('/workspace/other.md', new AbortController().signal) expect(h.paths.cachedApplications('/workspace/other.md')).toHaveLength(1) expect(menu.source.getSnapshot()).toBe(shown) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/todo.txt', new AbortController().signal) + const changed = menu.source.getSnapshot() + expect(changed.find(item => item.id === 'open-in-app.file/open')).toMatchObject({ label: 'menu.defaultApp', disabled: true }) + h.remote.session.workspacePathApplications.mockResolvedValueOnce({ ok: true, value: [] }) + await h.paths.applications('/workspace/other.md', new AbortController().signal) + expect(menu.source.getSnapshot()).toBe(changed) menu.dispose() }) From 0c2fbb031dd6b1e96a1b4ad971567342db34c85a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:31:55 +0800 Subject: [PATCH 031/103] Capture the selected macOS window without its attached window group --- .../cua-macos/native/Sources/CuaNative/WindowCapture.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowCapture.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowCapture.swift index a61960d2ea..0d167f4cab 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/WindowCapture.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/WindowCapture.swift @@ -115,6 +115,8 @@ final class WindowCapture: @unchecked Sendable { configuration.width = pixelsWide configuration.height = pixelsHigh configuration.showsCursor = false + // Attached sheets can otherwise capture the entire document window scaled to the sheet's dimensions. + if #available(macOS 14.2, *) { configuration.includeChildWindows = false } configuration.ignoreShadowsSingleWindow = true configuration.ignoreGlobalClipSingleWindow = true trace?.mark("capture-config.end") From c07035b4ef6211be5ebf4529d701eb3936f33d23 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:34:32 +0800 Subject: [PATCH 032/103] Check the rendered file panel button against its AX bounds --- .../experimental/cua-macos/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- .../native/tests/CheckScreenshotLabel.swift | 19 +++++++++++++++++++ .../cua-macos/native/tests/e2e.py | 9 +++++++++ 5 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 packages/experimental/cua-macos/native/tests/CheckScreenshotLabel.swift diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 37458210d5..0d83c6e538 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -18,8 +18,8 @@ en: 533ed4dd11af5126 zh: 03036e8c949d6aca /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: - en: 0da6d36bdf117089 - zh: 0d3692ab25ac2923 + en: b734a0907747580e + zh: 8110c5951b70e100 /deepseek-ai-dsh-experimental-cua-macos/understand-the-implementation: en: 4e82b85a5aa72eee zh: 4e004b7a205d8688 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index ce128bab4f..742e218285 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -123,7 +123,7 @@ Use the `cua` API to discover and select the application (`listApps`, `getState` Screenshot capture requires an attachment store and a resolved model route declaring image input. The shared attachment admission validates canonical Base64, the raster and its configured capacity, then stores the image once. Native data remains available to programmatic callers; model content carries coordinate metadata and the durable image reference. Response byte limits apply before parsing. -Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. Prefer `invoke(id)` for a background control’s default action. For mouse input, activate the application and observe the target first. Mouse clicks on system Open and Save sheets are routed to their verified panel-service window. +Use `win.click(id)` to send mouse events at the center of an element, or `win.click([x, y])` to click a point. For both `click(id)` and `mouseMove(id)`, the element must belong to the selected window. Prefer `invoke(id)` for a background control’s default action. For mouse input, activate the application and observe the target first. Mouse clicks on system Open and Save sheets are routed to their verified panel-service window. On macOS 14.2 and later, a window screenshot excludes its attached window group so the image uses the selected window’s bounds. Absolute coordinates for `mouseMove`, `click`, and `drag` use `[x, y]` tuples; `scroll` uses named `x` and `y`. All use pixels in the latest returned screenshot. Pass `relative: true` for integer thousandths of window width and height, from 0 to 999; omission or `false` uses pixels. Relative input can use a successful AX read or screenshot, while absolute input requires a screenshot. The Host maps the delivered image to native points, including attachment and model-request resizing. A value of 999 remains inside the window edge. Coordinate options do not apply to element IDs. A width or height change since the latest observation returns `WINDOW_CHANGED` before input, including raw coordinate calls without a snapshot ID; read fresh AX or take a new screenshot before proceeding. Window movement alone preserves window-local coordinates. Capture and pointer input reject known disagreement between the selected window’s accessibility frame and displayed bounds with `WINDOW_CHANGED`, before posting pointer events. This includes Stage Manager transformations when AX retains the full window frame. Read fresh state; any activation or window raise remains explicit. Advertised AX actions remain available. Missing AX geometry retains the AXless path and does not establish that a transformed window can be operated. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 2801e0ccbc..276baf2131 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -123,7 +123,7 @@ void await window.getScreenshot() 截图要求附件服务可用,并确认当前模型支持图片输入。共享附件接入校验规范 Base64、图像数据及配置容量,然后保存一次图片。程序调用方仍可取得原生数据,模型内容包含坐标元数据和持久图片引用。响应字节上限在解析前执行。 -`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。后台控件优先用 `invoke(id)` 执行默认动作。需要鼠标输入时,先激活应用并重新观察目标。系统打开或保存面板的鼠标点击投递给已核实的文件面板服务窗口。 +`win.click(id)` 向元素中心发送鼠标事件,`win.click([x, y])` 向给定位置发送鼠标事件。`click(id)` 和 `mouseMove(id)` 使用的元素须属于所选窗口。后台控件优先用 `invoke(id)` 执行默认动作。需要鼠标输入时,先激活应用并重新观察目标。系统打开或保存面板的鼠标点击投递给已核实的文件面板服务窗口。在 macOS 14.2 及以上版本,截图只包含所选窗口,图像按该窗口的边界对齐。 `mouseMove`、`click` 和 `drag` 的绝对坐标使用 `[x, y]` 元组;`scroll` 使用命名的 `x` 和 `y`。它们都使用最近返回截图中的像素。传入 `relative: true` 时使用 0~999 的千分比整数;省略或传入 `false` 时使用像素。相对坐标可基于成功的 AX 读取或截图,绝对坐标必须先截图。Host 根据实际送入模型的图片尺寸换算原生 point,包含附件归一化和模型请求阶段的缩放。999 映射到窗口边缘以内。坐标选项不适用于元素 ID。窗口宽高与最近一次观察不同时,在输入前返回 `WINDOW_CHANGED`,即使原始坐标调用不传快照 ID 也会检查;重新读取 AX 或截图后再操作。单纯移动窗口不使窗口内坐标失效。截图和鼠标输入会核对所选窗口的辅助功能框与显示边界;已知两者不一致时,在发送任何鼠标事件前返回 `WINDOW_CHANGED`。当 AX 保留完整窗口框时,这也会拦住 Stage Manager 变换后的窗口。需要重新读取状态;激活应用或抬起窗口仍须显式调用。元素声明的 AX 动作保持可用。缺少 AX 几何时保留无 AX 路径,不代表变换后的窗口一定可以操作。 diff --git a/packages/experimental/cua-macos/native/tests/CheckScreenshotLabel.swift b/packages/experimental/cua-macos/native/tests/CheckScreenshotLabel.swift new file mode 100644 index 0000000000..4b6b566c0f --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/CheckScreenshotLabel.swift @@ -0,0 +1,19 @@ +// Verify a screenshot against an AX control using text recognized from the captured pixels. +import Foundation +import Vision + +let args = Array(CommandLine.arguments.dropFirst()) +guard args.count == 6, let x = Double(args[2]), let y = Double(args[3]), + let width = Double(args[4]), let height = Double(args[5]) else { + fatalError("Expected PNG path, label and normalized top-left AX bounds") +} +let expected = CGRect(x: x, y: y, width: width, height: height) +let request = VNRecognizeTextRequest() +request.recognitionLevel = .accurate +request.automaticallyDetectsLanguage = true +try VNImageRequestHandler(url: URL(fileURLWithPath: args[0]), options: [:]).perform([request]) +let matches = (request.results ?? []).filter { $0.topCandidates(1).first?.string.caseInsensitiveCompare(args[1]) == .orderedSame } +guard matches.contains(where: { expected.contains(CGPoint(x: $0.boundingBox.midX, y: 1 - $0.boundingBox.midY)) }) else { + fputs("The screenshot does not show the control label inside its AX bounds.\n", stderr) + exit(1) +} diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 03ae9ac2ac..8697b6d781 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -85,6 +85,15 @@ def check_file_panel(call, owner, primary_params, primary, directory, wait_state assert f"window {sheet_id}; select that window" in error["message"], error ready = call("getState", {**owner, "windowId": sheet_id, "maxElements": 2000, "maxDepth": 25}) open_button = next(e for e in ready["elements"] if e["identifier"] == "OKButton" and e["enabled"]) + image = call("screenshot", {**owner, "windowId": sheet_id}) + png = Path(directory) / "open-sheet.png" + png.write_bytes(base64.b64decode(image["data"], validate=True)) + x, y, width, height = open_button["bounds"] + frame = image["bounds"] + expected = ((x - frame["x"]) / frame["width"], (y - frame["y"]) / frame["height"], + width / frame["width"], height / frame["height"]) + subprocess.run(["swift", str(ROOT / "tests/CheckScreenshotLabel.swift"), str(png), + open_button["title"], *map(str, expected)], check=True) assert call("click", {**owner, "windowId": sheet_id, "snapshotId": ready["snapshotId"], "elementId": open_button["elementId"]})["dispatched"] wait_state(lambda state: bool(state["selectedFile"]) and Path(state["selectedFile"]).samefile(selected_file), "File picker did not return the intended file") From 344e8a91a58ab8cda5d5f7debff27de6169b2d6a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:35:37 +0800 Subject: [PATCH 033/103] Resolve element hover before checking geometry for pointer delivery --- .../native/Sources/CuaNative/AXHover.swift | 6 ++-- .../native/Sources/CuaNative/AXWorker.swift | 35 ++++++++++++------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift index 656aa97a07..ecab67f6d7 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift @@ -11,7 +11,7 @@ final class AXHover { private var revealed: (element: AXUIElement, windowID: UInt32)? /// Entering revealed descendants preserves their parent UI; leaving restores it once. - func move(to target: AXUIElement?, in route: WindowRoute, access: AXAccess) throws -> Bool { + func move(to target: AXUIElement?, in windowID: UInt32, access: AXAccess) throws -> Bool { var current = target var visited: [AXUIElement] = [] var alternate: AXUIElement? @@ -20,7 +20,7 @@ final class AXHover { throw NativeFailure(code: "NATIVE_ERROR", message: "Accessibility hover ancestry contains a cycle; read fresh state") } visited.append(node) - if let revealed, revealed.windowID == route.windowID, CFEqual(revealed.element, node) { return true } + if let revealed, revealed.windowID == windowID, CFEqual(revealed.element, node) { return true } let actions = try access.actions(node) if alternate == nil, actions.contains("AXShowAlternateUI"), actions.contains("AXShowDefaultUI"), try access.boolean(node, "AXEnabled") != false { alternate = node } @@ -35,7 +35,7 @@ final class AXHover { } if let alternate { try access.perform(alternate, "AXShowAlternateUI") - revealed = (alternate, route.windowID) + revealed = (alternate, windowID) return true } return leaving diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index f00e63b622..73e8e78fd9 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -104,6 +104,14 @@ actor AXWorker { access = created return created } + private func moveUsingAX(_ element: AXUIElement?, windowID: UInt32, handle: String, params: RequestParameters) throws -> Bool { + let allowSystemPointer = try params.optionalBoolean("allowSystemPointer") ?? false + let hover = hovers[handle] ?? AXHover() + hovers[handle] = hover + if try hover.move(to: element, in: windowID, access: ax()) { return true } + try AXHover.requireSystemPointer(allowed: allowSystemPointer) + return false + } private func inputs() -> (KeyboardInput, WindowPointerInput) { if let keyboard, let pointer { return (keyboard, pointer) } let poster = PIDEventPoster() @@ -348,7 +356,6 @@ actor AXWorker { let modifiers = try params.modifiers() let window: WindowInfo let point: WindowPoint - var hoverElement: AXUIElement? var elementWindow: AXUIElement? if params.contains("elementId") { guard !params.contains("x"), !params.contains("y") else { throw RequestParameters.invalid("Element and coordinate targets cannot be combined") } @@ -359,9 +366,15 @@ actor AXWorker { if let requestedWindow, enclosing.id != requestedWindow { throw NativeFailure(code: "STALE_SNAPSHOT", message: "Element belongs to window \(enclosing.id); select that window and read its tree") } - if method == "click" { try ax().requireEnabled(selected) } + if method == "mouseMove" { + _ = try NativePlatform.ownedWindow(identity.pid, enclosing.id) + if try moveUsingAX(selected, windowID: enclosing.id, handle: handle, params: params) { + return .result(Self.mouseMoveResult(route: "accessibility", pointerMoved: false)) + } + } else { + try ax().requireEnabled(selected) + } elementWindow = enclosing.element - hoverElement = selected guard let bounds = try ax().bounds(selected), bounds.width > 0, bounds.height > 0 else { throw NativeFailure(code: "NATIVE_ERROR", message: "Element has no pointer bounds") } window = try WindowGeometry.resolve(owner: identity, windowID: enclosing.id) { try ax().bounds(enclosing.element) } point = WindowPoint(x: bounds.x + bounds.width / 2 - window.bounds.x, y: bounds.y + bounds.height / 2 - window.bounds.y) @@ -373,18 +386,14 @@ actor AXWorker { } let route = WindowRoute(owner: identity, windowID: window.windowID, bounds: window.bounds) if method == "mouseMove" { - let allowSystemPointer = try params.optionalBoolean("allowSystemPointer") ?? false try WindowPointerInput.validate(point, in: route) - if hoverElement == nil { - hoverElement = try ax().element(at: CGPoint(x: window.bounds.x + point.x, y: window.bounds.y + point.y), owner: identity) - if let hit = hoverElement, try ax().windowID(hit) != window.windowID { hoverElement = nil } + if elementWindow == nil { + var hit = try ax().element(at: CGPoint(x: window.bounds.x + point.x, y: window.bounds.y + point.y), owner: identity) + if let target = hit, try ax().windowID(target) != window.windowID { hit = nil } + if try moveUsingAX(hit, windowID: window.windowID, handle: handle, params: params) { + return .result(Self.mouseMoveResult(route: "accessibility", pointerMoved: false)) + } } - let hover = hovers[handle] ?? AXHover() - hovers[handle] = hover - if try hover.move(to: hoverElement, in: route, access: ax()) { - return .result(Self.mouseMoveResult(route: "accessibility", pointerMoved: false)) - } - try AXHover.requireSystemPointer(allowed: allowSystemPointer) return .mouseMove(route, point) } var clickRoute = route From eba9e768e65e9c578d71b1663227afb076b605ec Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 15:39:00 +0800 Subject: [PATCH 034/103] fix(ui-goal): order goal actions edit, clear, pause and tighten icon gaps Refs #8024 Co-authored-by: Yifffan <133629972+Yifffan@users.noreply.github.com> --- .../expected/goal-bar/active.expected.md | 2 +- .../expected/goal-bar/blocked.expected.md | 2 +- .../expected/goal-bar/inactive.expected.md | 2 +- .../src/client/queue/QueueDock.module.css | 2 +- packages/client/ui-goal/README.i18n.yaml | 4 +-- packages/client/ui-goal/README.md | 2 +- packages/client/ui-goal/README.zh.md | 2 +- .../ui-goal/src/client/GoalBar.module.css | 2 +- .../client/ui-goal/src/client/GoalBar.tsx | 34 +++++++++---------- .../ui-goal/tests/goalbar.client.spec.tsx | 6 ++-- .../web/queue-actions/goal-stop.expected.md | 2 +- .../web/queue-actions/layout.expected.md | 2 +- 12 files changed, 32 insertions(+), 30 deletions(-) diff --git a/apps/web/tests/expected/goal-bar/active.expected.md b/apps/web/tests/expected/goal-bar/active.expected.md index cf3227ee51..423676465d 100644 --- a/apps/web/tests/expected/goal-bar/active.expected.md +++ b/apps/web/tests/expected/goal-bar/active.expected.md @@ -1,4 +1,4 @@ - text: Ongoing Goal guard rapid clear clicks -- button "Pause goal" - button "Edit goal" - button "Clear goal" +- button "Pause goal" diff --git a/apps/web/tests/expected/goal-bar/blocked.expected.md b/apps/web/tests/expected/goal-bar/blocked.expected.md index dbfcf5563b..b61a46559d 100644 --- a/apps/web/tests/expected/goal-bar/blocked.expected.md +++ b/apps/web/tests/expected/goal-bar/blocked.expected.md @@ -1,4 +1,4 @@ - text: Blocked Goal retry with the edited plan -- button "Resume goal" - button "Edit goal" - button "Clear goal" +- button "Resume goal" diff --git a/apps/web/tests/expected/goal-bar/inactive.expected.md b/apps/web/tests/expected/goal-bar/inactive.expected.md index 729dbd1dd9..64258bf74b 100644 --- a/apps/web/tests/expected/goal-bar/inactive.expected.md +++ b/apps/web/tests/expected/goal-bar/inactive.expected.md @@ -1,4 +1,4 @@ - text: Inactive Goal guard rapid clear clicks -- button "Resume goal" - button "Edit goal" - button "Clear goal" +- button "Resume goal" diff --git a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css index d80240c6b2..1783694789 100644 --- a/packages/client/ui-conversation/src/client/queue/QueueDock.module.css +++ b/packages/client/ui-conversation/src/client/queue/QueueDock.module.css @@ -206,7 +206,7 @@ display: flex; flex: none; align-items: center; - gap: 10px; + gap: 8px; } .status { diff --git a/packages/client/ui-goal/README.i18n.yaml b/packages/client/ui-goal/README.i18n.yaml index 815b11e50f..00694a134b 100644 --- a/packages/client/ui-goal/README.i18n.yaml +++ b/packages/client/ui-goal/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-goal/use-this-package: - en: 7f6620a84a087d07 - zh: 80071126cc64b3e5 + en: a70a68194ca0c799 + zh: 3830bcebfa1879a9 /deepseek-ai-dsh-client-ui-goal/use-this-package/the-command-input-bubble: en: 05f0360b6c6dd3e9 zh: d14c3f15dc4cea5b diff --git a/packages/client/ui-goal/README.md b/packages/client/ui-goal/README.md index 986e5c6811..bbada420cd 100644 --- a/packages/client/ui-goal/README.md +++ b/packages/client/ui-goal/README.md @@ -25,7 +25,7 @@ The Web GUI goal surface shows both the durable goal state and its current proce ## Use this package -Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. An armed active goal offers pause; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. +Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. The strip orders its actions edit, clear, then pause or resume, matching the Queue rows' edit and remove positions. An armed active goal offers pause; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. ### The command-input bubble diff --git a/packages/client/ui-goal/README.zh.md b/packages/client/ui-goal/README.zh.md index 36e47153d9..9cece977c8 100644 --- a/packages/client/ui-goal/README.zh.md +++ b/packages/client/ui-goal/README.zh.md @@ -25,7 +25,7 @@ Web GUI 的 goal 界面同时显示持久 goal 状态及当前的进程本地激 ## 使用本包 -与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。已 armed 的 active goal 提供暂停动作;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 +与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。条带的动作按编辑、清除、暂停或恢复的顺序排列,与 Queue 行的编辑和移除位置一致。已 armed 的 active goal 提供暂停动作;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 ### 指令输入气泡 diff --git a/packages/client/ui-goal/src/client/GoalBar.module.css b/packages/client/ui-goal/src/client/GoalBar.module.css index 798cd0d9f6..9d7c99716c 100644 --- a/packages/client/ui-goal/src/client/GoalBar.module.css +++ b/packages/client/ui-goal/src/client/GoalBar.module.css @@ -100,7 +100,7 @@ .actions { display: flex; align-items: center; - gap: 10px; + gap: 8px; flex: none; } diff --git a/packages/client/ui-goal/src/client/GoalBar.tsx b/packages/client/ui-goal/src/client/GoalBar.tsx index 120538c3c4..025bf51b8a 100644 --- a/packages/client/ui-goal/src/client/GoalBar.tsx +++ b/packages/client/ui-goal/src/client/GoalBar.tsx @@ -1,9 +1,9 @@ /** * GoalBar: the goal indicator docked above the message composer (input dock * strip). A present goal shows a goal glyph, a phase label, the truncated - * objective, and icon actions — resume when active-disarmed, paused, or - * blocked, edit (inline form in the same strip), and clear. Goal creation - * lives on the `/goal` command, not here: loading (undefined), no goal + * objective, and icon actions — edit (inline form in the same strip), clear, + * then pause when armed or resume when active-disarmed, paused, or blocked. + * Goal creation lives on the `/goal` command, not here: loading (undefined), no goal * (null), and complete goals render nothing. Durable state arrives as the projected whole snapshot; * process-local activation arrives through the injected activation hook. */ @@ -137,20 +137,6 @@ export function GoalBar({ goal, activation, onEdit, onPause, onResume, onClear, {goal.objective} {actionError !== null && {actionError}}
- {goal.phase === 'active' && activation === 'armed' && ( - - - - )} - {showResume && ( - - - - )} + {goal.phase === 'active' && activation === 'armed' && ( + + + + )} + {showResume && ( + + + + )}
diff --git a/packages/client/ui-goal/tests/goalbar.client.spec.tsx b/packages/client/ui-goal/tests/goalbar.client.spec.tsx index cc9dda1c67..32947a6b9d 100644 --- a/packages/client/ui-goal/tests/goalbar.client.spec.tsx +++ b/packages/client/ui-goal/tests/goalbar.client.spec.tsx @@ -146,9 +146,10 @@ describe('GoalBar', () => { expect(screen.getByRole('textbox', { name: '目标内容' })).toBeTruthy() }) - it('active goal: the pause action pauses', () => { + it('active goal: the pause action follows edit and clear, and pauses', () => { const actions = makeActions() render() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '暂停目标']) fireEvent.click(screen.getByRole('button', { name: '暂停目标' })) expect(actions.onPause).toHaveBeenCalledTimes(1) }) @@ -163,10 +164,11 @@ describe('GoalBar', () => { expect(screen.queryByRole('button', { name: '暂停目标' })).toBeNull() }) - it('paused goal: "已暂停的目标" with a resume action before edit', () => { + it('paused goal: "已暂停的目标" with a resume action after edit and clear', () => { const actions = makeActions() render() expect(screen.getByText('已暂停的目标')).toBeTruthy() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '恢复目标']) fireEvent.click(screen.getByRole('button', { name: '恢复目标' })) expect(actions.onResume).toHaveBeenCalledTimes(1) }) diff --git a/snapshots/web/queue-actions/goal-stop.expected.md b/snapshots/web/queue-actions/goal-stop.expected.md index 92a11037e0..19018fd989 100644 --- a/snapshots/web/queue-actions/goal-stop.expected.md +++ b/snapshots/web/queue-actions/goal-stop.expected.md @@ -45,9 +45,9 @@ - button "Bad response" - button "Branch into a new conversation" - text: {{clock}} Inactive Goal Keep working after Stop -- button "Resume goal" - button "Edit goal" - button "Clear goal" +- button "Resume goal" - textbox "Message or run a task, / commands, @ files or sessions" - button "Add files or run commands" - 'button "Access mode, current: Workspace Write"': Workspace Write diff --git a/snapshots/web/queue-actions/layout.expected.md b/snapshots/web/queue-actions/layout.expected.md index b79770e640..9c4352daf7 100644 --- a/snapshots/web/queue-actions/layout.expected.md +++ b/snapshots/web/queue-actions/layout.expected.md @@ -21,9 +21,9 @@ - region "To-dos": - button "To-dos 1 completed · 1 in progress" - text: Ongoing Goal Keep the composer context panels aligned -- button "Pause goal" - button "Edit goal" - button "Clear goal" +- button "Pause goal" - button "2 queued messages" - textbox "Cmd/Ctrl+Enter steers all queued messages" - button "Add files or run commands" From 0d6c614164c2f0835b5fba5af0243e2a923900f0 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:40:54 +0800 Subject: [PATCH 035/103] Establish the file panel keyboard target and compare hover state across refusal --- packages/experimental/cua-macos/native/tests/e2e.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 8697b6d781..4e30375a81 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -18,6 +18,7 @@ from native_test_support import ROOT, NativeHelper, line, run_cleanup, stop def check_file_panel(call, owner, primary_params, primary, directory, wait_state, button_target): + call("activate", owner) selected_file = Path(directory) / "sheet-target.txt" selected_file.write_text("Owned file picker fixture\n") assert call("invoke", button_target(call("getState", primary_params), "Open fixture file"))["dispatched"] @@ -232,7 +233,7 @@ def main(): denied = call("mouseMove", no_hover, "HOVER_UNAVAILABLE") assert "systemPointerMoved" not in denied and "No input was sent" in denied["message"], denied after = wait_state(lambda s: s["cursorSamples"] > before["cursorSamples"], "Cursor sampling stopped") - assert after["cursorChanges"] == before["cursorChanges"] and not after["hoverVisible"], after + assert (after["cursorChanges"], after["hoverVisible"]) == (before["cursorChanges"], before["hoverVisible"]), after def mouse_move(target): result = call("mouseMove", target if args.alternate_hover else {**target, "allowSystemPointer": True}) From 1fd66fd75f3dcaf03c92b712fe1dd288628db6cb Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 15:43:06 +0800 Subject: [PATCH 036/103] Measure refused hover in the cursor-stability fixture --- .../experimental/cua-macos/native/tests/e2e.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua-macos/native/tests/e2e.py b/packages/experimental/cua-macos/native/tests/e2e.py index 4e30375a81..2a16b54b49 100644 --- a/packages/experimental/cua-macos/native/tests/e2e.py +++ b/packages/experimental/cua-macos/native/tests/e2e.py @@ -226,14 +226,14 @@ def main(): window_element = next(element for element in current["elements"] if element["role"] == "AXWindow") call("performAction", {**owner, "snapshotId": current["snapshotId"], "elementId": window_element["elementId"], "action": "AXRaise"}) - call("getState", primary_params) current = call("getState", primary_params) - no_hover = {**button_target(current, "Increment primary"), "windowId": primary["windowId"]} - before = json.loads(state_path.read_text()) - denied = call("mouseMove", no_hover, "HOVER_UNAVAILABLE") - assert "systemPointerMoved" not in denied and "No input was sent" in denied["message"], denied - after = wait_state(lambda s: s["cursorSamples"] > before["cursorSamples"], "Cursor sampling stopped") - assert (after["cursorChanges"], after["hoverVisible"]) == (before["cursorChanges"], before["hoverVisible"]), after + if args.alternate_hover: + no_hover = {**button_target(current, "Increment primary"), "windowId": primary["windowId"]} + before = json.loads(state_path.read_text()) + denied = call("mouseMove", no_hover, "HOVER_UNAVAILABLE") + assert "systemPointerMoved" not in denied and "No input was sent" in denied["message"], denied + after = wait_state(lambda s: s["cursorSamples"] > before["cursorSamples"], "Cursor sampling stopped") + assert (after["cursorChanges"], after["hoverVisible"]) == (before["cursorChanges"], before["hoverVisible"]), after def mouse_move(target): result = call("mouseMove", target if args.alternate_hover else {**target, "allowSystemPointer": True}) From a8fb5eb9fa2e64b97ed474098c0275836cec6899 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:07:17 +0800 Subject: [PATCH 037/103] fix(ui-goal): keep goal action positions while activation loads Co-authored-by: Yifffan <133629972+Yifffan@users.noreply.github.com> --- apps/web/tests/goal-bar.e2e.ts | 8 ++--- packages/client/ui-goal/README.i18n.yaml | 4 +-- packages/client/ui-goal/README.md | 2 +- packages/client/ui-goal/README.zh.md | 2 +- .../client/ui-goal/src/client/GoalBar.tsx | 32 +++++++++---------- .../ui-goal/tests/goalbar.client.spec.tsx | 7 ++++ 6 files changed, 31 insertions(+), 24 deletions(-) diff --git a/apps/web/tests/goal-bar.e2e.ts b/apps/web/tests/goal-bar.e2e.ts index 132d44569b..348a7520a6 100644 --- a/apps/web/tests/goal-bar.e2e.ts +++ b/apps/web/tests/goal-bar.e2e.ts @@ -53,9 +53,9 @@ describe('web e2e: goal bar clear convergence', () => { const bar = page.locator('[data-goal-bar]') await bar.waitFor({ timeout: 10_000 }) const pause = bar.getByRole('button', { name: 'Pause goal' }) - await expect.poll(() => pause.count(), { + await expect.poll(() => pause.isEnabled(), { timeout: 10_000, - }).toBe(1) + }).toBe(true) await pause.hover() const pauseTooltip = page.getByRole('tooltip', { name: 'Pause goal', exact: true }) await pauseTooltip.waitFor() @@ -120,7 +120,7 @@ describe('web e2e: goal bar clear convergence', () => { await input.fill('/goal retry after a blocker') await input.press('Enter') const bar = page.locator('[data-goal-bar]') - await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 }) + await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true) const agents = scaffold.ctx.agents.list() expect(agents).toHaveLength(1) @@ -140,7 +140,7 @@ describe('web e2e: goal bar clear convergence', () => { await compareOrRefreshGolden(BLOCKED_EXPECTED, blocked, MODE) await bar.getByRole('button', { name: 'Resume goal' }).click() - await bar.getByRole('button', { name: 'Pause goal' }).waitFor({ timeout: 10_000 }) + await expect.poll(() => bar.getByRole('button', { name: 'Pause goal' }).isEnabled(), { timeout: 10_000 }).toBe(true) expect(scaffold.ctx.goals.get(agent)).toMatchObject({ phase: 'active', activation: 'armed', objective: 'retry with the edited plan', }) diff --git a/packages/client/ui-goal/README.i18n.yaml b/packages/client/ui-goal/README.i18n.yaml index 00694a134b..809bbef816 100644 --- a/packages/client/ui-goal/README.i18n.yaml +++ b/packages/client/ui-goal/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-goal/use-this-package: - en: a70a68194ca0c799 - zh: 3830bcebfa1879a9 + en: 796ed31dda615e5a + zh: b797d7bd3d3f34bc /deepseek-ai-dsh-client-ui-goal/use-this-package/the-command-input-bubble: en: 05f0360b6c6dd3e9 zh: d14c3f15dc4cea5b diff --git a/packages/client/ui-goal/README.md b/packages/client/ui-goal/README.md index bbada420cd..cadad96470 100644 --- a/packages/client/ui-goal/README.md +++ b/packages/client/ui-goal/README.md @@ -25,7 +25,7 @@ The Web GUI goal surface shows both the durable goal state and its current proce ## Use this package -Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. The strip orders its actions edit, clear, then pause or resume, matching the Queue rows' edit and remove positions. An armed active goal offers pause; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. +Mount this plugin alongside `ui-conversation` and the goal domain package; the strip then appears as the second card in the composer-context stack (after Todo, before Queue) whenever the session has a goal. Todo and Goal use the same panel elevation above the composer. The strip orders its actions edit, clear, then pause or resume, matching the Queue rows' edit and remove positions. An armed active goal offers pause, shown disabled until its activation is known; an active-but-disarmed, paused, or blocked goal offers resume; edit rewrites the objective in the ui-primitives `InlineEditor`, so multi-line objectives survive editing; clear removes the goal and suppresses the strip until the projection catches up. ### The command-input bubble diff --git a/packages/client/ui-goal/README.zh.md b/packages/client/ui-goal/README.zh.md index 9cece977c8..9d96d3fa0b 100644 --- a/packages/client/ui-goal/README.zh.md +++ b/packages/client/ui-goal/README.zh.md @@ -25,7 +25,7 @@ Web GUI 的 goal 界面同时显示持久 goal 状态及当前的进程本地激 ## 使用本包 -与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。条带的动作按编辑、清除、暂停或恢复的顺序排列,与 Queue 行的编辑和移除位置一致。已 armed 的 active goal 提供暂停动作;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 +与 `ui-conversation` 及 goal 领域包一起挂载本插件;只要会话存在目标,条带就会作为 composer 上下文堆栈的第二张卡片出现(位于 Todo 之后、Queue 之前)。Todo 与 Goal 使用相同的面板 elevation,使其位于 composer 层级之上。条带的动作按编辑、清除、暂停或恢复的顺序排列,与 Queue 行的编辑和移除位置一致。已 armed 的 active goal 提供暂停动作,激活状态未知时暂停按钮显示为禁用;active-but-disarmed、paused 或 blocked 的 goal 提供恢复;编辑在 ui-primitives 的 `InlineEditor` 中重写目标文本,多行目标编辑后仍保留换行;清除移除目标,并在投影追上之前抑制条带。 ### 指令输入气泡 diff --git a/packages/client/ui-goal/src/client/GoalBar.tsx b/packages/client/ui-goal/src/client/GoalBar.tsx index 025bf51b8a..c6bb31711b 100644 --- a/packages/client/ui-goal/src/client/GoalBar.tsx +++ b/packages/client/ui-goal/src/client/GoalBar.tsx @@ -2,7 +2,8 @@ * GoalBar: the goal indicator docked above the message composer (input dock * strip). A present goal shows a goal glyph, a phase label, the truncated * objective, and icon actions — edit (inline form in the same strip), clear, - * then pause when armed or resume when active-disarmed, paused, or blocked. + * then pause when armed (disabled until activation is known) or resume when + * active-disarmed, paused, or blocked. * Goal creation lives on the `/goal` command, not here: loading (undefined), no goal * (null), and complete goals render nothing. Durable state arrives as the projected whole snapshot; * process-local activation arrives through the injected activation hook. @@ -128,7 +129,8 @@ export function GoalBar({ goal, activation, onEdit, onPause, onResume, onClear, const title = goal.phase === 'blocked' ? goal.blockedReason?.message : undefined const label = goal.phase === 'active' ? activeLabel(activation, t) : t(PHASE_LABELS[goal.phase]) - const showResume = goal.phase !== 'active' || activation === 'disarmed' + const resume = goal.phase !== 'active' || activation === 'disarmed' + const toggleLabel = t(resume ? 'action.resume' : 'action.pause') return (
@@ -153,20 +155,18 @@ export function GoalBar({ goal, activation, onEdit, onPause, onResume, onClear, - {goal.phase === 'active' && activation === 'armed' && ( - - - - )} - {showResume && ( - - - - )} + {/* Until activation arrives, an active goal keeps a disabled pause so edit and clear stay in place. */} + + +
diff --git a/packages/client/ui-goal/tests/goalbar.client.spec.tsx b/packages/client/ui-goal/tests/goalbar.client.spec.tsx index 32947a6b9d..0016781fbb 100644 --- a/packages/client/ui-goal/tests/goalbar.client.spec.tsx +++ b/packages/client/ui-goal/tests/goalbar.client.spec.tsx @@ -154,6 +154,13 @@ describe('GoalBar', () => { expect(actions.onPause).toHaveBeenCalledTimes(1) }) + it('active goal with unknown activation: keeps a disabled pause after edit and clear', () => { + const actions = makeActions() + render() + expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '暂停目标']) + expect((screen.getByRole('button', { name: '暂停目标' }) as HTMLButtonElement).disabled).toBe(true) + }) + it('active disarmed goal: "待继续的目标" with a resume action instead of pause', () => { const actions = makeActions() render() From 94336c6b3ddcfca9c4562183978dd308414a198f Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 16:15:24 +0800 Subject: [PATCH 038/103] fix(forge): pin change request diffs to the polled head and count every review thread ForgeProvider.diff now takes the head commit it must describe. The GitHub provider reads headRefOid before and after `gh pr diff` and returns the new ForgeFailure code `stale` when either read names another commit, so the forge panel never caches a patch under a head it does not describe. A stale read polls the change request at once, and the changes view waits for the next status before reading again. Status polling pages reviewThreads up to the new `maxReviewThreads` setting (default 1,000) instead of counting only the first 100, and sets ChangeRequestSnapshot.threadsTruncated when the count is a lower bound. --- apps/web/tests/forge-panel.e2e.ts | 14 +- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- docs/subsystems/forge.i18n.yaml | 4 +- docs/subsystems/forge.md | 29 ++- docs/subsystems/forge.zh.md | 29 ++- .../forge-pinned-diff/guide.i18n.yaml | 16 ++ .../v0.2.2-rc.1/forge-pinned-diff/guide.md | 26 +++ .../v0.2.2-rc.1/forge-pinned-diff/guide.zh.md | 26 +++ .../client-ui-forge/README.i18n.yaml | 8 +- .../experimental/client-ui-forge/README.md | 6 +- .../experimental/client-ui-forge/README.zh.md | 6 +- .../src/client/ChangeRequestCard.tsx | 9 +- .../client-ui-forge/src/client/ChangesTab.tsx | 16 +- .../experimental/client-ui-forge/src/index.ts | 17 +- .../experimental/client-ui-forge/src/types.ts | 6 +- .../tests/change-request-card.client.spec.tsx | 2 + .../tests/changes-tab.client.spec.tsx | 36 ++++ .../tests/client-fixtures.client.ts | 1 + .../tests/controller.host.spec.ts | 33 +++- .../client-ui-forge/tests/harness.ts | 6 +- .../forge-github/README.i18n.yaml | 8 +- packages/experimental/forge-github/README.md | 10 +- .../experimental/forge-github/README.zh.md | 10 +- .../experimental/forge-github/src/graphql.ts | 175 ++++++++++++++---- .../experimental/forge-github/src/index.ts | 9 +- .../experimental/forge-github/src/provider.ts | 119 +++++++++--- .../forge-github/tests/fixtures.ts | 14 +- .../forge-github/tests/graphql.spec.ts | 133 +++++++++++-- .../forge-github/tests/plugin.spec.ts | 2 + .../forge-github/tests/provider.spec.ts | 125 +++++++++++-- .../forge-github/tests/review.spec.ts | 4 +- .../forge-session/tests/fixtures.ts | 1 + .../tests/loader-composition.spec.ts | 3 +- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 +- packages/experimental/forge/README.zh.md | 2 +- packages/experimental/forge/src/index.ts | 15 +- packages/experimental/forge/src/types.ts | 17 +- .../experimental/forge/tests/fake-provider.ts | 5 +- .../forge/tests/lifecycle.spec.ts | 4 +- .../experimental/forge/tests/registry.spec.ts | 6 +- .../experimental/forge/tests/watch.spec.ts | 21 +++ .../extensions/tool-cordis/src/api-catalog.ts | 16 +- 44 files changed, 812 insertions(+), 191 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 44f24a6a58..656f5b91e4 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -120,25 +120,31 @@ if (args[0] === 'api' && args[1] === 'graphql') { }) const pulls = { 7: { - number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, + id: 'pull-7', number: 7, url: 'https://github.com/octo/demo/pull/7', title: 'Add the pull request panel', state: 'OPEN', isDraft: false, updatedAt: '2026-10-09T00:00:00Z', closedAt: null, author: { login: 'octo' }, headRefName: 'feat', headRefOid: 'a'.repeat(40), baseRefName: 'main', additions: 128, deletions: 14, mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', - reviewThreads: { nodes: [{ isResolved: false }] }, + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ isResolved: false }] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-7', state: 'FAILURE', contexts: { pageInfo: { hasNextPage: true, endCursor: 'checks-100' }, nodes: Array.from({ length: 100 }, (_, i) => check('lint', 'FAILURE', '2026-10-08T00:00:42Z', i + 1)), } } } }] }, }, 9: { - number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', + id: 'pull-9', number: 9, url: 'https://github.com/octo/demo/pull/9', title: 'Add the merge button', state: state.mergedAt === null ? 'OPEN' : 'MERGED', isDraft: !state.ready, updatedAt: '2026-10-09T00:00:00Z', closedAt: state.mergedAt, author: { login: 'octo' }, headRefName: 'feat/merge', headRefOid: state.head ?? 'b'.repeat(40), baseRefName: 'main', additions: 30, deletions: 2, mergeable: 'MERGEABLE', - mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', reviewThreads: { nodes: [] }, + mergeStateStatus: state.ready ? 'CLEAN' : 'BLOCKED', reviewDecision: 'APPROVED', + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-9', state: 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [check('lint', 'SUCCESS', '2026-10-09T00:00:42Z')], } } } }] }, }, } + if (query.includes('pullRequest(number: $number)')) { + const number = Number(args.find(arg => arg.startsWith('number=')).slice('number='.length)) + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: pulls[number].headRefOid } } } })) + process.exit(0) + } if (query.includes('node(id: $id)')) { process.stdout.write(JSON.stringify({ data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..0e37afca2b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1142,7 +1142,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1178,6 +1178,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + maxReviewThreads?: number } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..ccf14207de 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1144,7 +1144,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:239`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1180,6 +1180,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + maxReviewThreads?: number } ``` diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 3f4994aa39..f60794a506 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -18,5 +18,5 @@ en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: dbc28e731f357edf - zh: a1977fafc0651427 + en: 8182a3120b2d4aa3 + zh: 68b6631047cb0f48 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f36141ea1b..591e9d47f4 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -68,8 +68,12 @@ interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** Read the changes of a change request as the host computes them, as one unified patch with `a/` and `b/` path prefixes. */ - diff(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes of a change request at head commit `headSha` as the host computes them, as one unified + * patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the + * head is another commit, the read resolves to a `stale` failure. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ @@ -176,8 +180,10 @@ interface ChangeRequestSnapshot { readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean - /** Number of review threads that are not resolved. */ + /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number + /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ + readonly threadsTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -191,9 +197,10 @@ interface ForgeFailure { /** * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails - * the same way; `unavailable`: any other failure. + * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of + * a later status can succeed; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -568,7 +575,7 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. +The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, which returns a patch only for that head commit; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. When the head moved past the latest status, the provider returns `stale` and `ctx.forge.diff` polls the change request at once; `changeRequestDiff` rejects with `forgePanel/stale-head` and caches nothing, and the changes view keeps loading until a later status arrives, then reads again at that status's head. Review comments therefore always address the commit whose lines the view shows. ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -814,13 +821,16 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * Read the changes of a change request as its host computes them. + * Read the changes of a change request at one head commit as its host + * computes them. A `stale` failure polls the change request again at once + * when it is watched, so its next status names the current head. * @param ref - change request served by a registered provider. + * @param headSha - head commit the patch must describe, usually the head of the latest status. * @param signal - cancellation of the read. - * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`. * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. */ -async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise +async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** * Publish one comment or a completed review, then refresh the watched status. @@ -1015,6 +1025,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param signal - request cancellation. * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. */ diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 61c53fbd6c..e73f9a6713 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -68,8 +68,12 @@ interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** Read the changes of a change request as the host computes them, as one unified patch with `a/` and `b/` path prefixes. */ - diff(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes of a change request at head commit `headSha` as the host computes them, as one unified + * patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the + * head is another commit, the read resolves to a `stale` failure. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ @@ -176,8 +180,10 @@ interface ChangeRequestSnapshot { readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean - /** Number of review threads that are not resolved. */ + /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number + /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ + readonly threadsTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -191,9 +197,10 @@ interface ForgeFailure { /** * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails - * the same way; `unavailable`: any other failure. + * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of + * a later status can succeed; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -568,7 +575,7 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 +变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更,提供方只返回描述该 head 提交的补丁;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。head 已越过最新状态时,提供方返回 `stale`,`ctx.forge.diff` 立即重新轮询该变更请求;`changeRequestDiff` 以 `forgePanel/stale-head` 拒绝且不缓存任何内容,变更视图保持加载,直到更新的状态到达后按该状态的 head 重新读取。因此评审评论始终指向视图所显示行的那个提交。 ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -814,13 +821,16 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise /** - * Read the changes of a change request as its host computes them. + * Read the changes of a change request at one head commit as its host + * computes them. A `stale` failure polls the change request again at once + * when it is watched, so its next status names the current head. * @param ref - change request served by a registered provider. + * @param headSha - head commit the patch must describe, usually the head of the latest status. * @param signal - cancellation of the read. - * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`. * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. */ -async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise +async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** * Publish one comment or a completed review, then refresh the watched status. @@ -1015,6 +1025,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param signal - request cancellation. * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. */ diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml new file mode 100644 index 0000000000..ffe417704a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md +/: + en: ad1c3c4e42227656 + zh: 286eac73122ddbef +/forge-diffs-read-one-head-commit: + en: c017d657e5d9eb08 + zh: d0eb2aef480e7753 +/forge-diffs-read-one-head-commit/change: + en: 669f43ccd2364c5a + zh: 97190faaa338da51 +/forge-diffs-read-one-head-commit/migration: + en: 04cf41940f9fa126 + zh: edf52bd1d8882bf9 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md new file mode 100644 index 0000000000..e1d3c890ef --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ForgeProvider.diff and ctx.forge.diff take the head commit to read, ForgeFailure gains the stale code, and ChangeRequestSnapshot gains threadsTruncated." +--- + +# Forge diffs read one head commit + +English | [中文](guide.zh.md) + +## Change + +`ForgeProvider.diff(ref, signal)` becomes `diff(ref, headSha, signal)`, and `ctx.forge.diff(ref, signal)` becomes `ctx.forge.diff(ref, headSha, signal)`. A provider returns a patch only when it describes `headSha`; when the change request's head is another commit, it resolves to a `ForgeFailure` whose code is the new `stale`. `ctx.forge.diff` then polls the change request again at once when it is watched. The GitHub provider reads the head before and after `gh pr diff` and returns `stale` when either read names another commit. + +`ForgeFailure['code']` gains `stale`. `ChangeRequestSnapshot` gains the required `threadsTruncated: boolean`, which marks `unresolvedThreads` as a lower bound when the provider counted only some review threads. + +The `forgePanel.changeRequestDiff` Remote rejects with `forgePanel/stale-head` instead of returning a patch read at another head. + +This affects third-party `ForgeProvider` implementations registered with `ctx.forge.register`, code that calls `ctx.forge.diff` or `forgePanel.changeRequestDiff`, code that builds `ChangeRequestSnapshot` values, and code that switches exhaustively over `ForgeFailure['code']`. All types come from `@deepseek-ai/dsh-experimental-forge`. + +## Migration + +1. In a `ForgeProvider`, add the `headSha: string` parameter to `diff` before `signal`. Return the patch only when the host computed it at `headSha`; otherwise return `{ code: 'stale', message }`. A host whose diff endpoint takes no commit can read the head before and after the diff, as [`GitHubProvider.diff`](../../../../packages/experimental/forge-github/src/provider.ts) does. +2. Pass the head commit to every `ctx.forge.diff` call, usually `ctx.forge.latest(ref)`'s `snapshot.headSha`. On `stale`, wait for a later status and read again at its head; do not cache the result under the old head. +3. Set `threadsTruncated` in every `ChangeRequestSnapshot` a provider builds: `false` when `unresolvedThreads` counts every review thread. +4. Handle `stale` wherever code switches exhaustively over `ForgeFailure['code']`, and `forgePanel/stale-head` wherever a caller of `forgePanel.changeRequestDiff` distinguishes Remote error codes. +5. Run your type check; it succeeds when every `diff` implementation and call passes a head commit, every snapshot sets `threadsTruncated`, and no `ForgeFailure` code is unhandled. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md new file mode 100644 index 0000000000..e5549364ec --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/forge-pinned-diff/guide.zh.md @@ -0,0 +1,26 @@ +--- +kind: upgrade-guide +description: "ForgeProvider.diff 与 ctx.forge.diff 需要传入要读取的 head 提交,ForgeFailure 新增 stale 代码,ChangeRequestSnapshot 新增 threadsTruncated。" +--- + +# Forge diff 读取指定的 head 提交 + +[English](guide.md) | 中文 + +## 变更 + +`ForgeProvider.diff(ref, signal)` 改为 `diff(ref, headSha, signal)`,`ctx.forge.diff(ref, signal)` 改为 `ctx.forge.diff(ref, headSha, signal)`。提供方只在补丁描述 `headSha` 时返回补丁;变更请求的 head 已是其他提交时,resolve 为代码为新增 `stale` 的 `ForgeFailure`。此时若该变更请求正被 watch,`ctx.forge.diff` 会立即重新轮询它。GitHub 提供方在 `gh pr diff` 前后各读一次 head,任一次不是该提交时返回 `stale`。 + +`ForgeFailure['code']` 新增 `stale`。`ChangeRequestSnapshot` 新增必填字段 `threadsTruncated: boolean`;提供方只统计了部分评审讨论时,它表示 `unresolvedThreads` 只是下限。 + +`forgePanel.changeRequestDiff` Remote 以 `forgePanel/stale-head` 拒绝,不再返回在其他 head 读到的补丁。 + +受影响的是用 `ctx.forge.register` 注册的第三方 `ForgeProvider` 实现、调用 `ctx.forge.diff` 或 `forgePanel.changeRequestDiff` 的代码、构造 `ChangeRequestSnapshot` 的代码,以及对 `ForgeFailure['code']` 做穷尽分支的代码。这些类型都来自 `@deepseek-ai/dsh-experimental-forge`。 + +## 迁移 + +1. 在 `ForgeProvider` 的 `diff` 中,于 `signal` 之前加入 `headSha: string` 参数。只有托管平台在 `headSha` 处计算出补丁时才返回补丁,否则返回 `{ code: 'stale', message }`。若托管平台的 diff 接口不接受提交参数,可以像 [`GitHubProvider.diff`](../../../../packages/experimental/forge-github/src/provider.ts) 那样在读取 diff 前后各读一次 head。 +2. 每次调用 `ctx.forge.diff` 都传入 head 提交,通常是 `ctx.forge.latest(ref)` 的 `snapshot.headSha`。收到 `stale` 时,等待更新的状态并按其 head 重新读取;不要把结果缓存在旧 head 下。 +3. 提供方构造的每个 `ChangeRequestSnapshot` 都要设置 `threadsTruncated`:`unresolvedThreads` 统计了全部评审讨论时为 `false`。 +4. 凡对 `ForgeFailure['code']` 做穷尽分支的地方都处理 `stale`;凡区分 `forgePanel.changeRequestDiff` Remote 错误代码的调用方都处理 `forgePanel/stale-head`。 +5. 运行类型检查;所有 `diff` 实现与调用都传入 head 提交、所有快照都设置 `threadsTruncated`、没有未处理的 `ForgeFailure` 代码时,检查通过。 diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 203cd3e907..9c2c5d288b 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 1101418b5621ba9d - zh: 4d66052d4708d02c + en: 458a6d3447c33aa2 + zh: 5af3eb9439840b73 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0c2dd86b5f6b489d - zh: 2f0fce0affa48f59 + en: 04b6519156ba47de + zh: 84c4683f3762c22c /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 29afc7d4e6..84f9b90c78 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -36,9 +36,9 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Code review and changes** — on the right-sidebar start page, opens the same change request tab as the Session header button. - **Header button** — appears when the Session has bound change requests or its directory is inside a Git checkout, and shows or hides the tab. A red dot marks an open change request with failed checks, requested changes, or conflicts. - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. -- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. +- **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again once a later status arrives, at its head. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. @@ -67,7 +67,7 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index f45d0c2568..4c6cc8f5ed 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -36,9 +36,9 @@ kind: "package-reference" - **代码审查和变更**——右侧栏起始页中的入口,与会话标题栏按钮打开同一个变更请求标签页。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 -- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 +- **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等更新的状态到达后按其 head 重新读取。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -67,7 +67,7 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx index 9795e3558c..0397991ad0 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangeRequestCard.tsx @@ -75,6 +75,7 @@ const FAILURE: Record = { 'not-found': 'change.failure.notFound', 'unauthenticated': 'change.failure.unauthenticated', 'too-large': 'change.failure.unavailable', + 'stale': 'change.failure.unavailable', 'unavailable': 'change.failure.unavailable', } @@ -89,6 +90,12 @@ const CHECK_RANK: Record = { failure: 0, pending: 1, success: 2, neutral: 3, skipped: 3, cancelled: 3, } +/** The unresolved thread count, with `+` when the provider counted only some threads. */ +function threadCount(snapshot: ChangeRequestSnapshot, locale: string): string { + const count = snapshot.unresolvedThreads.toLocaleString(locale) + return snapshot.threadsTruncated ? `${count}+` : count +} + function failureOf(entry: ForgePanelChangeRequest): ForgeFailure | undefined { return entry.update !== null && 'failure' in entry.update ? entry.update.failure : undefined } @@ -434,7 +441,7 @@ function Details({ entry, snapshot, name, now, actions, locale, t }: { {t('change.row.review')} - {snapshot.unresolvedThreads > 0 ? t('change.review.threads', { review, count: snapshot.unresolvedThreads }) : review} + {snapshot.unresolvedThreads > 0 ? t('change.review.threads', { review, count: threadCount(snapshot, locale) }) : review}
diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 983c6b58a3..a65edc8570 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -462,11 +462,23 @@ export function ChangesTab({ // Names the read the inputs ask for; it is in flight until `finished` matches it. const read = version === null ? null : `${dataKey}\n${navigation.revision}\n${attempt}\n${version}` const [finished, setFinished] = useState(null) + // A change request read refused because the head moved past its status stays in flight until a later status arrives. + const statusAt = entry?.update?.fetchedAt ?? null + const latestStatusAt = useRef(statusAt) + useEffect(() => { latestStatusAt.current = statusAt }, [statusAt]) + const [refused, setRefused] = useState<{ readonly read: string; readonly statusAt: number | null } | null>(null) + const waiting = refused !== null && refused.read === read && refused.statusAt === statusAt useEffect(() => { - if (!tab.visible || read === null || read === finished) return + if (!tab.visible || read === null || read === finished || waiting) return const controller = new AbortController() + const readAt = latestStatusAt.current void readChanges(source, localScope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { if (controller.signal.aborted) return + if (!result.ok && result.error.code === 'forgePanel/stale-head') { + setRefused({ read, statusAt: readAt }) + setFailure(null) + return + } setFinished(read) if (result.ok) { setLoaded({ key: dataKey, data: result.value }) @@ -476,7 +488,7 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, source, localScope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, waiting, source, localScope, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 6800a70b34..bb2dfdc334 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -15,6 +15,7 @@ import type {} from '@deepseek-ai/dsh-session-projection-cache' import type {} from '@deepseek-ai/dsh-session-query' import { MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import { assertNever } from '@deepseek-ai/dsh-util-values' import { gitIn, inspectCheckout, listBranches } from './git.ts' import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' @@ -334,6 +335,7 @@ export class ForgePanelController extends TypertRemoteService { * @param signal - request cancellation. * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/stale-head` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. */ @@ -349,7 +351,7 @@ export class ForgePanelController extends TypertRemoteService { const version = JSON.stringify([headSha, baseBranch]) let patch = this.patches.get(key, version) if (patch === undefined) { - const read = await this.home.forge.diff(ref, signal) + const read = await this.home.forge.diff(ref, headSha, signal) if (typeof read !== 'string') throw readError(read) this.patches.set(key, version, read) patch = read @@ -719,10 +721,19 @@ export class ForgePanelController extends TypertRemoteService { /** * Report why the code host did not provide a diff or file. * @param failure - the provider's failure. - * @returns `forgePanel/diff-too-large` for an answer over a size limit, else `forgePanel/diff-failed`, with the provider's message. + * @returns `forgePanel/diff-too-large` for an answer over a size limit, `forgePanel/stale-head` for a head that moved, + * else `forgePanel/diff-failed`, with the provider's message. */ function readError(failure: ForgeFailure): RemoteError { - return new RemoteError(failure.code === 'too-large' ? 'forgePanel/diff-too-large' : 'forgePanel/diff-failed', failure.message, {}) + switch (failure.code) { + case 'too-large': return new RemoteError('forgePanel/diff-too-large', failure.message, {}) + case 'stale': return new RemoteError('forgePanel/stale-head', failure.message, {}) + case 'not-found': + case 'unauthenticated': + case 'unavailable': return new RemoteError('forgePanel/diff-failed', failure.message, {}) + /* v8 ignore next -- closed ForgeFailure code union exhaustiveness guard */ + default: return assertNever(failure.code, 'ForgeFailure.code') + } } /** diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 2a11e67ac6..ace12522bb 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -388,7 +388,11 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/restore-failed': Record /** The URL is not a visible binding of the Session that a provider serves, so the panel does not act on it. */ 'forgePanel/not-bound': Record - /** The change request has new commits since the head the user confirmed, so it was not merged. */ + /** + * The change request's head is no longer the commit the request named: the head the user confirmed for a merge, + * the head displayed for complete checks, or the head of the latest status for a diff. A diff read polls the change + * request again at once, so a later status names the current head. + */ 'forgePanel/stale-head': Record /** The code host refused the change or could not be reached; the message gives the host's reason. */ 'forgePanel/action-failed': Record diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index 7ef34076a5..e7305ff6d1 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -261,6 +261,8 @@ describe('expanded ChangeRequestCard', () => { ['an approval with unresolved threads', { reviewDecision: 'approved', unresolvedThreads: 2 }, 'Approved · 2 unresolved', 'success'], ['requested changes with an unresolved thread', { reviewDecision: 'changes-requested', unresolvedThreads: 1 }, 'Changes requested · 1 unresolved', 'error'], + ['more threads than the provider counted', { reviewDecision: 'review-required', unresolvedThreads: 1200, threadsTruncated: true }, + 'Review required · 1,200+ unresolved', null], ] as const)('states the review of %s', (_label, overrides, text, tone) => { const value = rowValue(card(entry(1, snapshot(1, overrides)), { expanded: true }).item, en['change.row.review']) expect(value.textContent).toBe(text) diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index eaa90722ce..1abfc93d1a 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -124,6 +124,7 @@ const REFUSED = { tooLarge: { ok: false, error: new RemoteError('forgePanel/diff-too-large', 'too large', {}) }, filterConfig: { ok: false, error: new RemoteError('forgePanel/filter-config-failed', 'filter configuration unavailable', {}) }, gone: { ok: false, error: new RemoteError('forgePanel/diff-failed', 'gone', {}) }, + staleHead: { ok: false, error: new RemoteError('forgePanel/stale-head', 'the head moved', {}) }, hostRefused: { ok: false, error: new RemoteError('forgePanel/diff-failed', 'diff too large', {}) }, failed: { ok: false, error: new RemoteError('gateway/bad-request', 'failed', {}) }, } satisfies Record> @@ -1094,6 +1095,41 @@ describe('ChangesTab change requests', () => { expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2) }) + it('keeps loading after the head moved past its status and reads again once a later status arrives', async () => { + const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) } }) + await settle() + expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() + expect(m.view.queryByRole('status')).toBeNull() + expect(m.paths()).toEqual([]) + + // A later status with the same head reads again, as when the host's answers disagreed for a moment. + const later = (fetchedAt: number, headSha: string) => { + const polled = entry(7, snapshot(7, { headSha })) + return ready({ changeRequests: [{ ...polled, update: { ...polled.update!, fetchedAt } }] }) + } + m.faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) + act(() => { m.panel.set({ state: later(2, HEAD), disconnected: false }) }) + await settle() + expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2) + expect(m.view.queryByRole('status')).toBeNull() + + act(() => { m.panel.set({ state: later(3, 'b'.repeat(40)), disconnected: false }) }) + await settle() + expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(3) + expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts']) + }) + + it('keeps shown changes while a read waits for a later status, turning the refresh glyph', async () => { + const m = mount({ source }) + await settle() + m.faces.changeRequestDiff.mockResolvedValueOnce(REFUSED.staleHead) + fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) + await settle() + expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts']) + expect(m.view.queryByText(en['diff.error'])).toBeNull() + expect(m.view.getByRole('button', { name: en['diff.refresh'] }).querySelector('[data-turning]')).not.toBeNull() + }) + it.each([ ['unpushed commits it cannot count', null], ['no unpushed commits', 0], diff --git a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts index 55bcc141af..dad26b57b0 100644 --- a/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts +++ b/packages/experimental/client-ui-forge/tests/client-fixtures.client.ts @@ -39,6 +39,7 @@ export function snapshot(number: number, overrides: Partial { expect(opened.provider.diffs).toEqual([7, 7, 7, 7]) }) + it('never labels a diff read after a push with the head of the earlier status', async () => { + const { repo } = await project() + const opened = await open(repo) + const [polledHead, pushedHead] = ['a'.repeat(40), 'b'.repeat(40)] + const patches = new Map([[polledHead, PATCH], [pushedHead, PATCH.replaceAll('src/a.ts', 'src/b.ts')]]) + // The host serves the head of the moment it answers, as GitHub's pull request diff does. + let hostHead = polledHead + const reads: string[] = [] + Object.assign(opened.provider, { + diff: async (_ref: unknown, headSha: string): Promise => { + reads.push(headSha) + return headSha === hostHead ? patches.get(hostHead)! : { code: 'stale', message: `head moved to ${hostHead}` } + }, + }) + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + const follower = reader(opened) + await follower.until(state => polled(state, pullUrl(7))) + hostHead = pushedHead + opened.provider.overrides.set(7, { headSha: pushedHead }) + const fetches = opened.provider.fetches.length + + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)) + .rejects.toMatchObject({ code: 'forgePanel/stale-head', message: `head moved to ${pushedHead}` }) + // The refused read polls again at once, without waiting for the idle interval. + await follower.until(state => state.changeRequests[0]?.snapshot?.headSha === pushedHead) + expect(opened.provider.fetches.length).toBe(fetches + 1) + const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal) + expect([diff.headSha, diff.files.map(file => file.path)]).toEqual([pushedHead, ['src/b.ts']]) + expect(reads).toEqual([polledHead, pushedHead]) + }) + it('reports a diff or file over a size limit as too large', async () => { const { repo } = await project() const opened = await open(repo) diff --git a/packages/experimental/client-ui-forge/tests/harness.ts b/packages/experimental/client-ui-forge/tests/harness.ts index 652de1a153..02f1c8cb79 100644 --- a/packages/experimental/client-ui-forge/tests/harness.ts +++ b/packages/experimental/client-ui-forge/tests/harness.ts @@ -262,6 +262,7 @@ export function snapshot(ref: ChangeRequestRef): ChangeRequestSnapshot { checksRollup: 'success', checksTruncated: false, unresolvedThreads: 0, + threadsTruncated: false, updatedAt: '2026-10-09T00:00:00Z', closedAt: null, } @@ -285,6 +286,8 @@ export class FakeProvider implements ForgeProvider { readonly patches = new Map() /** Change request numbers in the order their diffs were read. */ readonly diffs: number[] = [] + /** Head commits the diff reads named, in the same order. */ + readonly diffHeads: string[] = [] /** File texts or failures by `:`; others return a not-found failure. */ readonly texts = new Map() /** Open change request numbers that a head lookup returns, by head branch. */ @@ -333,8 +336,9 @@ export class FakeProvider implements ForgeProvider { return Promise.resolve(this.actionResult) } - diff(ref: ChangeRequestRef): Promise { + diff(ref: ChangeRequestRef, headSha: string): Promise { this.diffs.push(ref.number) + this.diffHeads.push(headSha) return Promise.resolve(this.patches.get(ref.number) ?? { code: 'not-found', message: `no diff of #${ref.number}` }) } diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index b096b71898..5b14a27a65 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: f2bd06d91b744305 - zh: ad956b539a43b880 + en: 3eece595e10bc32e + zh: fe3c5cf59f9f17d4 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 90f3c10096be642a zh: 4e1b663c52019ac2 @@ -30,8 +30,8 @@ en: 26b946af4b742e17 zh: 00b34f0721ac72f6 /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work: - en: 37308d9458bb9316 - zh: 3d4188f3e94af282 + en: 627b11577406b029 + zh: 6596e545c1c5a6fd /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 2d9e2ce57a..643563baa4 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -34,17 +34,19 @@ Mount the provider after the forge registry and list every GitHub Enterprise hos hosts: [github.com, ghe.example.com] ``` -The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` must be a positive safe integer; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, and `maxOutputBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). +The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` and `maxReviewThreads` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, and `maxReviewThreads` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `git@github.com:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://///pull/` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname `: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none. Polling returns the first 100 head-commit check contexts without following pages. An incomplete preview sets `checksTruncated` and keeps GitHub’s aggregate state; its counts do not describe the full list. `fetchChecks(ref, signal)` reads complete details only for the requested PR, pinning continuation pages to the first response’s rollup. The combined UTF-8 JSON responses must fit `maxOutputBytes`; excess returns `too-large`. Failed or non-advancing pages fail only this detail read and leave polling results intact. Runs with the same application, workflow, event, and check name keep only the newest run id; a queued replacement supersedes an older completed run. Runs without a numeric database id are retained by node id because their relative age is unknown. Commit status contexts keep the newest result per context name. Complete lists derive their indicator from these results; unknown context kinds retain GitHub’s aggregate state. +Every status read counts review threads in pages of up to 100 until it has counted `maxReviewThreads` (default 1,000) of them; each page after the first is one more GraphQL query. A pull request with more threads sets `threadsTruncated`, and its `unresolvedThreads` counts only the threads read. A thread page that fails or does not advance fails that pull request's status read and leaves the other pull requests of the batch intact. + Unfinished check runs and completed runs with stale, missing, or unrecognized conclusions map to `pending`. Other completed checks map to `success`, `failure` (failure, timed out, startup failure, or action required), `cancelled`, `skipped`, or `neutral`. Cancelled checks keep the rollup non-passing. Check runs keep their start and completion times. Commit status contexts map `SUCCESS` to `success`, `FAILURE` and `ERROR` to `failure`, and every other state to `pending`, and carry no times. A GraphQL `NOT_FOUND` error becomes a `not-found` failure. A response without GraphQL data or errors, including an HTTP error JSON body, uses the first stderr diagnostic or the body's message. Authentication diagnostics become `unauthenticated`; oversized check pages become `too-large`; rate limits and other failures become `unavailable`. Head lookups preserve the same diagnostic in their rejection. A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` reads the head commit through GraphQL, runs `gh pr diff --repo // --color never`, and reads the head commit again; it returns the patch only when both reads name the requested commit, and `stale` otherwise. The requested commit must be a full 40- or 64-digit hexadecimal commit. `gh pr diff` takes no commit argument and answers at the head of the moment it runs, so the two reads bracket it. The REST compare endpoint, which names commits explicitly, is not used: compared with the base branch it is empty for a merged pull request, compared with `baseRefOid` it starts from the base commit GitHub recorded at the pull request's last update instead of the current base tip, and it returns diffs over 300 files that the pull request diff refuses. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. @@ -93,9 +95,9 @@ None. Provider output reaches only host-side watchers. - **GitHub CLI on the host** — `gh` must be installed and signed in for each configured host; tokens in environment variables are not forwarded. Hosts missing from `hosts` are never read, including references retained across configuration changes. A status fetch returns `unavailable` for those references; a head lookup rejects before starting `gh`. -- **First 100 review threads** — unresolved threads after the first 100 are not counted. +- **Review thread bound** — a status read counts at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks. - **No fork discovery** — head lookups exclude pull requests whose head is in another repository. -- **Rate limits** — every poll costs one GraphQL query per host, plus one query per additional page of 100 check records, against the signed-in account’s rate limit. +- **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read adds two head reads. All count against the signed-in account’s rate limit. - **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 1ac57ffa7d..404567565d 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -34,17 +34,19 @@ kind: "package-reference" hosts: [github.com, ghe.example.com] ``` -即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs` 与 `maxOutputBytes` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 +即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 与 `maxReviewThreads` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes` 与 `maxReviewThreads` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。 +每次状态读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响。 + 未完成的检查运行(check run),以及结论已过期、缺失或无法识别的已完成运行,均映射为 `pending`。其他已完成的检查映射为 `success`、`failure`(失败、超时、启动失败或需要操作)、`cancelled`、`skipped` 或 `neutral`。已取消的检查使汇总保持未通过状态。检查运行保留其开始与完成时间。提交状态上下文把 `SUCCESS` 映射为 `success`,把 `FAILURE` 与 `ERROR` 映射为 `failure`,其余状态均映射为 `pending`,且不带时间。GraphQL 的 `NOT_FOUND` 错误转为 `not-found` 失败。响应不含 GraphQL data 或 errors 时(包括 HTTP 错误 JSON),使用 stderr 的首条诊断或响应体的 message。认证诊断转为 `unauthenticated`;超出输出大小上限的检查分页转为 `too-large`;限流与其他失败转为 `unavailable`。head 查找在拒绝时保留相同诊断。 pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 先经 GraphQL 读取 head 提交,再运行 `gh pr diff --repo // --color never`,然后再读一次 head 提交;两次读取都是请求的提交时才返回补丁,否则返回 `stale`。请求的提交必须是完整的 40 位或 64 位十六进制提交。`gh pr diff` 不接受提交参数,返回运行那一刻 head 的结果,因此用前后两次读取把它夹住。不使用显式指定提交的 REST compare 接口:与基准分支比较时,已合并的 pull request 得到空结果;与 `baseRefOid` 比较时,起点是 GitHub 在 pull request 最后一次更新时记录的基准提交,而不是当前的基准分支末端;它还会返回 pull request diff 拒绝的超过 300 个文件的 diff。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 @@ -93,9 +95,9 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 - **宿主需要 GitHub CLI**——必须安装 `gh` 并为每个已配置主机登录;环境变量中的令牌不会被转发。不在 `hosts` 中的主机永远不会被读取,包括配置变更后保留的引用。状态读取为这些引用返回 `unavailable`;head 查找会在启动 `gh` 前拒绝。 -- **前 100 个评审讨论**——前 100 个之后的未解决讨论不计入。 +- **评审讨论上限**——每次状态读取每个 pull request 最多统计 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出。 - **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。 -- **速率限制**——每次轮询以已登录账号的速率配额为每个主机消耗一次 GraphQL 查询;检查记录每多一页(100 条),再消耗一次查询。 +- **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取另加两次 head 读取。这些都计入已登录账号的速率配额。 - **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。 diff --git a/packages/experimental/forge-github/src/graphql.ts b/packages/experimental/forge-github/src/graphql.ts index a7d0a8d16b..cea358e1a0 100644 --- a/packages/experimental/forge-github/src/graphql.ts +++ b/packages/experimental/forge-github/src/graphql.ts @@ -19,17 +19,34 @@ const CHECK_FIELDS = `pageInfo { hasNextPage endCursor } ... on StatusContext { context state targetUrl createdAt } }` -const PULL_REQUEST_FIELDS = `number url title state isDraft updatedAt closedAt +/** Most nodes GitHub returns in one connection page. */ +const PAGE_SIZE = 100 + +const THREAD_FIELDS = 'pageInfo { hasNextPage endCursor } nodes { isResolved }' + +/** + * Pull request fields of one snapshot. + * @param threads - review threads the first page holds, at most {@link PAGE_SIZE}. + * @returns the selection of the snapshot fragment. + */ +function pullRequestFields(threads: number): string { + return `id number url title state isDraft updatedAt closedAt author { login } headRefName headRefOid baseRefName additions deletions mergeable mergeStateStatus reviewDecision - reviewThreads(first: 100) { nodes { isResolved } } - commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: 100) { + reviewThreads(first: ${threads}) { ${THREAD_FIELDS} } + commits(last: 1) { nodes { commit { statusCheckRollup { id state contexts(first: ${PAGE_SIZE}) { ${CHECK_FIELDS} } } } } }` +} /** Continue reading the same commit's rollup even if the pull request head moves. */ export const CHECKS_QUERY = `query($id: ID!, $cursor: String!) { - node(id: $id) { ... on StatusCheckRollup { contexts(first: 100, after: $cursor) { ${CHECK_FIELDS} } } } + node(id: $id) { ... on StatusCheckRollup { contexts(first: ${PAGE_SIZE}, after: $cursor) { ${CHECK_FIELDS} } } } +}` + +/** Continue counting a pull request's review threads; variables `id`, `cursor`, and the integer `first`. */ +export const THREADS_QUERY = `query($id: ID!, $cursor: String!, $first: Int!) { + node(id: $id) { ... on PullRequest { reviewThreads(first: $first, after: $cursor) { ${THREAD_FIELDS} } } } }` const REPOSITORY_FIELDS = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod' @@ -42,6 +59,11 @@ export const HEAD_QUERY = `query($owner: String!, $name: String!, $branch: Strin } }` +/** Head commit of one pull request; variables `owner` and `name` are strings, `number` is an integer. */ +export const HEAD_COMMIT_QUERY = `query($owner: String!, $name: String!, $number: Int!) { + repository(owner: $owner, name: $name) { pullRequest(number: $number) { headRefOid } } +}` + const checkRunSchema = z.object({ __typename: z.literal('CheckRun'), id: z.string(), @@ -66,19 +88,40 @@ const statusContextSchema = z.object({ targetUrl: z.string().nullable(), }) -const checkPageSchema = z.object({ - pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), - nodes: z.array(z.unknown()), -}) +const pageInfoSchema = z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }) + +/** Position of a connection page within its connection. */ +type PageInfo = z.infer + +const checkPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.unknown()) }) + +const threadPageSchema = z.object({ pageInfo: pageInfoSchema, nodes: z.array(z.object({ isResolved: z.boolean() })) }) + +/** One validated connection page or a failure that prevents publishing a partial count. */ +export type PageResult = { readonly ok: true; readonly page: T } | { readonly ok: false; readonly failure: ForgeFailure } /** One validated page of check contexts or a failure that prevents publishing a partial count. */ -export type CheckPageResult = { readonly ok: true; readonly page: z.infer } - | { readonly ok: false; readonly failure: ForgeFailure } +export type CheckPageResult = PageResult> + +/** One validated page of review threads or a failure that prevents publishing a partial count. */ +export type ThreadPageResult = PageResult> /** Opaque GitHub node id that pins check pagination to one commit's rollup. */ type RollupId = Branded<'GitHubStatusCheckRollupId'> +/** Opaque GitHub node id of a pull request. */ +type PullRequestId = Branded<'GitHubPullRequestId'> + +/** Continuation reads that complete one snapshot response. */ +export interface SnapshotPages { + /** Read the next page of a pull request's review threads, holding at most `first` threads. */ + readonly threads: (id: PullRequestId, cursor: string, first: number) => Promise + /** Read the next check page of a rollup; omission keeps the first check page with its truncation flag. */ + readonly checks?: (id: RollupId, cursor: string) => Promise +} + const pullRequestSchema = z.object({ + id: z.string().transform(value => value as PullRequestId), url: z.string(), title: z.string(), state: z.enum(['OPEN', 'CLOSED', 'MERGED']), @@ -94,7 +137,7 @@ const pullRequestSchema = z.object({ mergeable: z.string(), mergeStateStatus: z.string(), reviewDecision: z.string().nullable(), - reviewThreads: z.object({ nodes: z.array(z.object({ isResolved: z.boolean() })) }), + reviewThreads: threadPageSchema, commits: z.object({ nodes: z.array(z.object({ commit: z.object({ @@ -143,6 +186,8 @@ const headSchema = z.object({ }), }) +const headCommitSchema = z.object({ data: z.object({ repository: z.object({ pullRequest: z.object({ headRefOid: z.string() }) }) }) }) + type PullRequestNode = z.infer type RepositoryNode = z.infer @@ -169,16 +214,19 @@ export interface SnapshotQuery { readonly document: string /** Change requests keyed by alias path `r.p`. */ readonly targets: ReadonlyMap + /** Most review threads counted per change request. */ + readonly maxReviewThreads: number } /** * Build one query that reads every change request in `refs`, grouping them by * repository. Owners, names, and numbers are validated before they are inlined. * @param refs - change requests on one host. + * @param maxReviewThreads - positive integer bound on the review threads counted per change request. * @returns the document and its alias targets. * @throws when an owner, name, or number cannot be inlined safely. */ -export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery { +export function snapshotQuery(refs: readonly ChangeRequestRef[], maxReviewThreads: number): SnapshotQuery { const repositories = new Map }>() for (const ref of refs) { const { owner, name } = checkedRepository(ref) @@ -201,22 +249,26 @@ export function snapshotQuery(refs: readonly ChangeRequestRef[]): SnapshotQuery const owner = JSON.stringify(repository.owner) fields.push(`r${r}: repository(owner: ${owner}, name: ${JSON.stringify(repository.name)}) { ${REPOSITORY_FIELDS} ${pulls.join(' ')} }`) } - return { document: `query { ${fields.join(' ')} }\nfragment ChangeRequestFields on PullRequest { ${PULL_REQUEST_FIELDS} }`, targets } + const document = `query { ${fields.join(' ')} } +fragment ChangeRequestFields on PullRequest { ${pullRequestFields(Math.min(PAGE_SIZE, maxReviewThreads))} }` + return { document, targets, maxReviewThreads } } /** * Map a snapshot response, including GitHub's partial-error form, into one * result per alias target. Path-scoped errors apply to their repository or * pull request; errors without a path apply to every unresolved target. A - * repository without readable merge settings offers no merge. Polling returns + * repository without readable merge settings offers no merge. Review threads + * are counted across pages up to `query.maxReviewThreads`. Polling returns * the first check page; an explicit detail read can complete its pagination. + * A continuation page that fails or does not advance fails its target. * @param body - parsed JSON printed by `gh api graphql`. * @param query - the query that produced the response. - * @param readChecks - optional detail reader for the same commit; omission returns the first page with its truncation flag. - * @returns a snapshot with its check truncation flag, or a failure, for every target. + * @param pages - continuation reads of review threads and, for a detail read, of checks on the same commit. + * @returns a snapshot with its check and thread truncation flags, or a failure, for every target. */ export async function mapSnapshotResponse( - body: unknown, query: SnapshotQuery, readChecks?: (id: RollupId, cursor: string) => Promise, + body: unknown, query: SnapshotQuery, pages: SnapshotPages, ): Promise> { const results = new Map() const parsed = responseSchema.safeParse(body) @@ -235,23 +287,14 @@ export async function mapSnapshotResponse( const node = pullRequestSchema.safeParse(raw) const settings = repositorySchema.safeParse(parsed.data.data?.[repositoryAlias]) if (node.success) { + const { id, reviewThreads } = node.data const rollup = node.data.commits.nodes[0]?.commit.statusCheckRollup - if (rollup !== undefined && rollup !== null) { - const cursors = new Set() - while (readChecks !== undefined && rollup.contexts.pageInfo.hasNextPage) { - const cursor = rollup.contexts.pageInfo.endCursor - if (cursor === null || cursors.has(cursor)) { - results.set(key, { code: 'unavailable', message: 'GitHub check pagination did not advance' }) - break - } - cursors.add(cursor) - const next = await readChecks(rollup.id, cursor) - if (!next.ok) { results.set(key, next.failure); break } - rollup.contexts.nodes.push(...next.page.nodes) - rollup.contexts.pageInfo = next.page.pageInfo - } - } - if (!results.has(key)) results.set(key, toSnapshot(ref, node.data, settings.success ? settings.data : undefined)) + const { checks } = pages + const failure = await readPages(reviewThreads, query.maxReviewThreads, 'review thread', + async (cursor, first) => await pages.threads(id, cursor, first)) + ?? (rollup === undefined || rollup === null || checks === undefined ? undefined + : await readPages(rollup.contexts, Number.POSITIVE_INFINITY, 'check', async cursor => await checks(rollup.id, cursor))) + results.set(key, failure ?? toSnapshot(ref, node.data, settings.success ? settings.data : undefined)) } else if (error !== undefined) results.set(key, { code: error.type === 'NOT_FOUND' ? 'not-found' : 'unavailable', message: error.message }) else if (raw === null || raw === undefined) results.set(key, { code: 'not-found', message: 'pull request not found' }) else results.set(key, { code: 'unavailable', message: 'unexpected pull request fields' }) @@ -259,21 +302,76 @@ export async function mapSnapshotResponse( return results } +/** + * Append the following pages of a connection until it ends or holds `limit` nodes. + * @param connection - first page, extended in place. + * @param limit - most nodes to hold. + * @param label - what the connection lists, for failure messages. + * @param read - reads the page after `cursor`, holding at most `first` nodes. + * @returns a failure that prevents publishing the partial connection, or undefined once it ended or is full. + */ +async function readPages( + connection: { nodes: T[]; pageInfo: PageInfo }, + limit: number, + label: string, + read: (cursor: string, first: number) => Promise>, +): Promise { + const cursors = new Set() + while (connection.pageInfo.hasNextPage && connection.nodes.length < limit) { + const cursor = connection.pageInfo.endCursor + if (cursor === null || cursors.has(cursor)) return { code: 'unavailable', message: `GitHub ${label} pagination did not advance` } + cursors.add(cursor) + const next = await read(cursor, Math.min(PAGE_SIZE, limit - connection.nodes.length)) + if (!next.ok) return next.failure + connection.nodes.push(...next.page.nodes) + connection.pageInfo = next.page.pageInfo + } + return undefined +} + /** * Validate a continuation response before adding its checks to the snapshot. * @param body - parsed GraphQL response for a rollup node. * @returns the complete page or a failure; partial-error pages are not accepted. */ export function mapCheckPageResponse(body: unknown): CheckPageResult { + return mapPageResponse(body, z.object({ contexts: checkPageSchema }).transform(node => node.contexts), 'check') +} + +/** + * Validate a continuation response of {@link THREADS_QUERY} before counting its review threads. + * @param body - parsed GraphQL response for a pull request node. + * @returns the complete page or a failure; partial-error pages are not accepted. + */ +export function mapThreadPageResponse(body: unknown): ThreadPageResult { + return mapPageResponse(body, z.object({ reviewThreads: threadPageSchema }).transform(node => node.reviewThreads), 'review thread') +} + +/** + * Validate one continuation response of a `node(id:)` query. + * @param body - parsed GraphQL response. + * @param page - schema that maps the node to its connection page. + * @param label - what the connection lists, for failure messages. + * @returns the page, or a failure for an error, a missing node, or unexpected fields. + */ +function mapPageResponse(body: unknown, page: z.ZodType, label: string): PageResult { const parsed = z.object({ - data: z.object({ node: z.object({ contexts: checkPageSchema }).nullable() }).nullable().optional(), + data: z.object({ node: page.nullable() }).nullable().optional(), errors: z.array(z.object({ message: z.string() })).optional(), }).safeParse(body) - if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) { - return { ok: true, page: parsed.data.data.node.contexts } - } + if (parsed.success && !parsed.data.errors?.length && parsed.data.data?.node != null) return { ok: true, page: parsed.data.data.node } return { ok: false, failure: { code: 'unavailable', - message: parsed.success ? parsed.data.errors?.[0]?.message ?? 'GitHub check page is unavailable' : 'unexpected GitHub check page' } } + message: parsed.success ? parsed.data.errors?.[0]?.message ?? `GitHub ${label} page is unavailable` : `unexpected GitHub ${label} page` } } +} + +/** + * Map a head commit read of {@link HEAD_COMMIT_QUERY}. + * @param body - parsed JSON printed by `gh api graphql`. + * @returns the head commit object name, or undefined when the response does not name one. + */ +export function mapHeadCommitResponse(body: unknown): string | undefined { + const parsed = headCommitSchema.safeParse(body) + return parsed.success ? parsed.data.data.repository.pullRequest.headRefOid : undefined } /** @@ -366,6 +464,7 @@ function toSnapshot( checksRollup: summary, checksTruncated: rollup?.contexts.pageInfo.hasNextPage ?? false, unresolvedThreads: node.reviewThreads.nodes.filter(thread => !thread.isResolved).length, + threadsTruncated: node.reviewThreads.pageInfo.hasNextPage, updatedAt: node.updatedAt, closedAt: node.closedAt, } diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index a0bc66126a..c061b57091 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -20,6 +20,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most review threads counted per pull request in one status read; a pull request with more reports a lower bound. */ + maxReviewThreads?: number } export const Config: z = z.object({ @@ -27,6 +29,7 @@ export const Config: z = z.object({ hosts: z.array(z.string()).default(['github.com']), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), + maxReviewThreads: z.number().default(1_000), }) const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i @@ -41,8 +44,8 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } - if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) { - throw new Error('forge-github: maxOutputBytes must be a positive safe integer') + for (const key of ['maxOutputBytes', 'maxReviewThreads'] as const) { + if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } - ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes)) + ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved)) } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index ca56473956..16c93acfbc 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -7,7 +7,11 @@ import type { } from '@deepseek-ai/dsh-experimental-forge' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts' import type { GhOutput, GhRunner } from './gh.ts' -import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery } from './graphql.ts' +import { + CHECKS_QUERY, hasGraphqlFields, HEAD_COMMIT_QUERY, HEAD_QUERY, mapCheckPageResponse, mapHeadCommitResponse, mapHeadResponse, + mapSnapshotResponse, mapThreadPageResponse, snapshotQuery, THREADS_QUERY, +} from './graphql.ts' +import type { SnapshotPages } from './graphql.ts' import { checkedRepository, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' @@ -25,6 +29,14 @@ const TOO_LARGE = /\btoo_large\b/ /** A full SHA-1 or SHA-256 object name. */ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i +/** Bounds on what one read retains or counts. */ +export interface GitHubLimits { + /** Maximum combined JSON bytes retained by an explicit check read. */ + readonly maxOutputBytes: number + /** Most review threads counted per pull request in one status read. */ + readonly maxReviewThreads: number +} + /** Reads GitHub and GitHub Enterprise pull requests through a `gh` runner. */ export class GitHubProvider implements ForgeProvider { readonly forge = 'github' @@ -39,9 +51,9 @@ export class GitHubProvider implements ForgeProvider { /** * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. - * @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read. + * @param limits - bounds on retained check bytes and counted review threads. */ - constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly maxOutputBytes: number) { + constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly limits: GitHubLimits) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) } @@ -93,10 +105,7 @@ export class GitHubProvider implements ForgeProvider { return results.get(changeRequestKey(ref))! } catch (error) { if (signal.aborted) throw signal.reason - if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) { - return { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message } - } - throw error + return processFailure(error) } } @@ -140,12 +149,22 @@ export class GitHubProvider implements ForgeProvider { ], signal) } - /** Read the pull request's diff with `gh pr diff`, which GitHub computes against the merge base. */ - async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise { + /** + * Read the pull request's diff with `gh pr diff`, which GitHub computes + * against the merge base at the head of the moment it answers. The head is + * read before and after the diff; the patch is returned only when both reads + * name `headSha`, and a different head returns `stale` without the patch. + */ + async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const { host, owner, name } = checkedRepository(ref) const failure = this.hostFailure(host) if (failure !== undefined) return failure - return await this.read(['pr', 'diff', String(ref.number), '--repo', `${host}/${owner}/${name}`, '--color', 'never'], signal) + if (!COMMIT.test(headSha)) throw new Error(`forge-github: invalid head commit ${JSON.stringify(headSha)}`) + const before = await this.headMismatch(ref, headSha, signal) + if (before !== undefined) return before + const patch = await this.read(['pr', 'diff', String(ref.number), '--repo', `${host}/${owner}/${name}`, '--color', 'never'], signal) + if (typeof patch !== 'string') return patch + return await this.headMismatch(ref, headSha, signal) ?? patch } /** Read one file at a commit through the contents API in its raw form. */ @@ -178,6 +197,23 @@ export class GitHubProvider implements ForgeProvider { } } + /** + * Read the head commit of a pull request. + * @returns undefined when it is `headSha`, `stale` when it is another commit, or why it could not be read. + */ + private async headMismatch(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const { host, owner, name } = ref.repository + const output = await this.read([ + 'api', 'graphql', '--hostname', host, + '-f', `query=${HEAD_COMMIT_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${ref.number}`, + ], signal) + if (typeof output !== 'string') return output + const head = mapHeadCommitResponse(parseJson(output)) + if (head === undefined) return { code: 'unavailable', message: 'unexpected GitHub response to the head commit read' } + if (head.toLowerCase() === headSha.toLowerCase()) return undefined + return { code: 'stale', message: `the pull request head moved from ${headSha} to ${head}` } + } + /** * Run one reading `gh` command, returning its output. A refusal, a `gh` that * cannot start, output over `maxOutputBytes`, and a run past `timeoutMs` become failures. @@ -232,34 +268,61 @@ export class GitHubProvider implements ForgeProvider { signal: AbortSignal, completeChecks = false, ): Promise> { - const query = snapshotQuery(refs) + const query = snapshotQuery(refs, this.limits.maxReviewThreads) const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal) const body = parseJson(output.stdout) - if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query) + const threads: SnapshotPages['threads'] = async (id, cursor, first) => { + const page = await this.continuation(host, + ['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], signal) + if (!('stdout' in page)) return { ok: false, failure: page } + const value = parseJson(page.stdout) + return hasGraphqlFields(value) ? mapThreadPageResponse(value) : { ok: false, failure: responseFailure(page, value) } + } + if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads }) let bytes = Buffer.byteLength(output.stdout) const tooLarge: ForgeFailure = { code: 'too-large', message: 'GitHub check details exceed the output size limit' } - if (bytes > this.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) - if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, async (id, cursor) => { - signal.throwIfAborted() - let page: GhOutput - try { - page = await this.gh(['api', 'graphql', '--hostname', host, - '-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], signal) - } catch (error) { - if (signal.aborted) throw signal.reason - if (error instanceof GhUnavailableError || error instanceof GhTimeoutError || error instanceof GhOutputLimitError) { - return { ok: false, failure: { code: error instanceof GhOutputLimitError ? 'too-large' : 'unavailable', message: error.message } } - } - throw error - } + if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) + if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => { + const page = await this.continuation(host, ['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], signal) + if (!('stdout' in page)) return { ok: false, failure: page } bytes += Buffer.byteLength(page.stdout) - if (bytes > this.maxOutputBytes) return { ok: false, failure: tooLarge } + if (bytes > this.limits.maxOutputBytes) return { ok: false, failure: tooLarge } const value = parseJson(page.stdout) return hasGraphqlFields(value) ? mapCheckPageResponse(value) : { ok: false, failure: responseFailure(page, value) } - }) + } }) const failure = responseFailure(output, body) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const)) } + + /** + * Run one continuation query of a snapshot read. + * @param host - host the snapshot was read from. + * @param variables - `gh api graphql` field flags, the query first. + * @param signal - cancellation of the snapshot read. + * @returns the output, or the failure of a `gh` that cannot start, times out, or prints over its limit. + * @throws with `signal.reason` when the read is cancelled. + */ + private async continuation(host: string, variables: readonly string[], signal: AbortSignal): Promise { + signal.throwIfAborted() + try { + return await this.gh(['api', 'graphql', '--hostname', host, ...variables], signal) + } catch (error) { + if (signal.aborted) throw signal.reason + return processFailure(error) + } + } +} + +/** + * Report a `gh` invocation that did not run to an exit code. + * @param error - what the runner threw. + * @returns `too-large` for output over its limit, `unavailable` for a `gh` that cannot start or times out. + * @throws `error` when it is any other failure. + */ +function processFailure(error: unknown): ForgeFailure { + if (error instanceof GhOutputLimitError) return { code: 'too-large', message: error.message } + if (error instanceof GhUnavailableError || error instanceof GhTimeoutError) return { code: 'unavailable', message: error.message } + throw error } /** Why `gh` refused: GitHub's message, else its first diagnostic line, with the HTTP status it names. */ diff --git a/packages/experimental/forge-github/tests/fixtures.ts b/packages/experimental/forge-github/tests/fixtures.ts index 5eacc54a6b..66f2f47652 100644 --- a/packages/experimental/forge-github/tests/fixtures.ts +++ b/packages/experimental/forge-github/tests/fixtures.ts @@ -42,6 +42,7 @@ export function repositorySettings(overrides: Record = {}): Rec /** A pull request node with the fields the snapshot query selects. */ export function pullRequestNode(number: number, overrides: Record = {}, contexts: unknown[] = [], rollupState: string | null = 'SUCCESS'): Record { return { + id: `pull-${number}`, number, url: `https://github.com/octo/demo/pull/${number}`, title: `Change ${number}`, @@ -58,7 +59,7 @@ export function pullRequestNode(number: number, overrides: Record ({ isResolved })) } +} diff --git a/packages/experimental/forge-github/tests/graphql.spec.ts b/packages/experimental/forge-github/tests/graphql.spec.ts index 80a96bae20..0181602326 100644 --- a/packages/experimental/forge-github/tests/graphql.spec.ts +++ b/packages/experimental/forge-github/tests/graphql.spec.ts @@ -1,17 +1,25 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestSnapshot } from '@deepseek-ai/dsh-experimental-forge' import { describe, expect, it } from 'vitest' -import { mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery, type CheckPageResult } from '../src/graphql.ts' -import { checkRun, demo, pull, pullRequestNode, repositorySettings, statusContext } from './fixtures.ts' +import { + mapCheckPageResponse, mapHeadCommitResponse, mapHeadResponse, mapSnapshotResponse, mapThreadPageResponse, snapshotQuery, +} from '../src/graphql.ts' +import type { SnapshotPages, ThreadPageResult } from '../src/graphql.ts' +import { checkRun, demo, pull, pullRequestNode, repositorySettings, statusContext, threadPage } from './fixtures.ts' -const noMoreChecks = async (): Promise => { throw new Error('Unexpected check page') } +const MAX_THREADS = 1_000 + +const noMorePages: SnapshotPages = { + threads: async () => { throw new Error('Unexpected review thread page') }, + checks: async () => { throw new Error('Unexpected check page') }, +} const other = { ...demo, name: 'other' } /** Map one pull request node of a repository with `settings`, or without readable merge settings when it is null. */ async function single(node: unknown, settings: Record | null = repositorySettings()): Promise { - const query = snapshotQuery([pull(1)]) - const results = await mapSnapshotResponse({ data: { r0: { ...settings, p0: node } } }, query, noMoreChecks) + const query = snapshotQuery([pull(1)], MAX_THREADS) + const results = await mapSnapshotResponse({ data: { r0: { ...settings, p0: node } } }, query, noMorePages) const result = results.get(changeRequestKey(pull(1))) if (result === undefined || 'code' in result) throw new Error(`expected a snapshot, received ${JSON.stringify(result)}`) return result @@ -20,7 +28,7 @@ async function single(node: unknown, settings: Record | null = describe('snapshot query', () => { it('groups change requests by repository and aliases each one', () => { const upper = { ...demo, owner: 'Octo', name: 'Demo' } - const query = snapshotQuery([pull(1), pull(2, upper), pull(1, upper), pull(7, other)]) + const query = snapshotQuery([pull(1), pull(2, upper), pull(1, upper), pull(7, other)], MAX_THREADS) expect([...query.targets]).toEqual([['r0.p0', pull(1)], ['r0.p1', pull(2, upper)], ['r1.p0', pull(7, other)]]) const settings = 'squashMergeAllowed mergeCommitAllowed rebaseMergeAllowed viewerPermission viewerDefaultMergeMethod' @@ -30,9 +38,9 @@ describe('snapshot query', () => { }) it('refuses owners, names, and numbers that cannot be inlined', () => { - expect(() => snapshotQuery([pull(1, { ...demo, owner: 'oc"to' })])).toThrow('forge-github: invalid repository "oc\\"to/demo"') - expect(() => snapshotQuery([pull(1.5)])).toThrow('forge-github: invalid pull request number 1.5') - expect(() => snapshotQuery([pull(0)])).toThrow('forge-github: invalid pull request number 0') + expect(() => snapshotQuery([pull(1, { ...demo, owner: 'oc"to' })], MAX_THREADS)).toThrow('forge-github: invalid repository "oc\\"to/demo"') + expect(() => snapshotQuery([pull(1.5)], MAX_THREADS)).toThrow('forge-github: invalid pull request number 1.5') + expect(() => snapshotQuery([pull(0)], MAX_THREADS)).toThrow('forge-github: invalid pull request number 0') }) }) @@ -65,6 +73,7 @@ describe('snapshot mapping', () => { checksRollup: 'success', checksTruncated: false, unresolvedThreads: 2, + threadsTruncated: false, updatedAt: '2026-10-09T01:02:03Z', closedAt: null, }) @@ -260,7 +269,7 @@ describe('snapshot mapping', () => { }) it('maps path-scoped and global errors from the partial-error response', async () => { - const query = snapshotQuery([pull(1), pull(2), pull(7, other)]) + const query = snapshotQuery([pull(1), pull(2), pull(7, other)], MAX_THREADS) const body = { data: { r0: { p0: pullRequestNode(1), p1: null }, r1: null }, errors: [ @@ -269,7 +278,7 @@ describe('snapshot mapping', () => { ], } - const results = await mapSnapshotResponse(body, query, noMoreChecks) + const results = await mapSnapshotResponse(body, query, noMorePages) expect(results.get(changeRequestKey(pull(1)))).toMatchObject({ state: 'open' }) expect(results.get(changeRequestKey(pull(2)))).toEqual({ code: 'not-found', message: 'Could not resolve to a PullRequest with the number of 2.' }) @@ -277,8 +286,8 @@ describe('snapshot mapping', () => { }) it('applies an error without a path to every unresolved change request', async () => { - const query = snapshotQuery([pull(1), pull(2)]) - const results = (await mapSnapshotResponse({ data: null, errors: [{ message: 'API rate limit exceeded' }] }, query, noMoreChecks)) + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) + const results = (await mapSnapshotResponse({ data: null, errors: [{ message: 'API rate limit exceeded' }] }, query, noMorePages)) expect([...results.values()]).toEqual([ { code: 'unavailable', message: 'API rate limit exceeded' }, @@ -287,30 +296,93 @@ describe('snapshot mapping', () => { }) it('reports a query validation error whose path names a fragment instead of a response alias', async () => { - const query = snapshotQuery([pull(1)]) + const query = snapshotQuery([pull(1)], MAX_THREADS) const results = await mapSnapshotResponse({ errors: [{ path: ['fragment ChangeRequestFields', 'invalidField'], - message: 'Field invalidField does not exist' }] }, query, noMoreChecks) + message: 'Field invalidField does not exist' }] }, query, noMorePages) expect([...results.values()]).toEqual([{ code: 'unavailable', message: 'Field invalidField does not exist' }]) }) it('reports missing nodes, malformed nodes, and malformed bodies', async () => { - const query = snapshotQuery([pull(1), pull(2)]) + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) - expect([...(await mapSnapshotResponse({ data: { r0: { p0: null, p1: { title: 7 } } } }, query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse({ data: { r0: { p0: null, p1: { title: 7 } } } }, query, noMorePages)).values()]).toEqual([ { code: 'not-found', message: 'pull request not found' }, { code: 'unavailable', message: 'unexpected pull request fields' }, ]) - expect([...(await mapSnapshotResponse({}, query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse({}, query, noMorePages)).values()]).toEqual([ { code: 'unavailable', message: 'unexpected GitHub response' }, { code: 'unavailable', message: 'unexpected GitHub response' }, ]) - expect([...(await mapSnapshotResponse('not json', query, noMoreChecks)).values()]).toEqual([ + expect([...(await mapSnapshotResponse('not json', query, noMorePages)).values()]).toEqual([ { code: 'unavailable', message: 'unexpected GitHub response' }, { code: 'unavailable', message: 'unexpected GitHub response' }, ]) }) }) +describe('review thread counting', () => { + /** Map pull request 1, whose first page holds `first` and whose following pages hold `rest`, counting at most `max` threads. */ + async function counted(max: number, first: readonly boolean[], rest: readonly (readonly boolean[])[]) { + const reads: [string, string, number][] = [] + const threads: SnapshotPages['threads'] = async (id, cursor, size) => { + reads.push([id, cursor, size]) + const index = Number(cursor.slice('page-'.length)) + const resolved = rest[index - 1] + if (resolved === undefined) throw new Error(`Unexpected review thread page ${cursor}`) + const more = index < rest.length || size < resolved.length + return { ok: true, page: threadPage(resolved.slice(0, size), more ? `page-${index + 1}` : null) } + } + const query = snapshotQuery([pull(1)], max) + const node = pullRequestNode(1, { reviewThreads: threadPage(first, rest.length > 0 ? 'page-1' : null) }) + const results = await mapSnapshotResponse({ data: { r0: { ...repositorySettings(), p0: node } } }, query, { threads }) + const result = results.get(changeRequestKey(pull(1))) + return { result, reads, document: query.document } + } + const hundred = (unresolved: number): boolean[] => Array.from({ length: 100 }, (_, index) => index >= unresolved) + + it('counts unresolved threads across every page of a pull request with more than 100 threads', async () => { + const { result, reads } = await counted(MAX_THREADS, hundred(1), [hundred(2), [false, true, false]]) + + expect(result).toMatchObject({ unresolvedThreads: 5, threadsTruncated: false }) + expect(reads).toEqual([['pull-1', 'page-1', 100], ['pull-1', 'page-2', 100]]) + }) + + it.each([ + ['exactly the bound', 203, 5, false, [100, 3]], + ['one thread below the total', 202, 4, true, [100, 2]], + ['a bound inside the second page', 150, 3, true, [50]], + ] as const)('stops counting at %s and marks the count as a lower bound past it', async (_label, max, unresolved, truncated, sizes) => { + const { result, reads } = await counted(max, hundred(1), [hundred(2), [false, true, false]]) + + expect(result).toMatchObject({ unresolvedThreads: unresolved, threadsTruncated: truncated }) + expect(reads.map(([, , size]) => size)).toEqual(sizes) + }) + + it('reads a first page no larger than a bound below 100', async () => { + const { result, reads, document } = await counted(2, [false, false], [[false]]) + + expect(document).toContain('reviewThreads(first: 2)') + expect(result).toMatchObject({ unresolvedThreads: 2, threadsTruncated: true }) + expect(reads).toEqual([]) + expect((await counted(MAX_THREADS, [false], [])).document).toContain('reviewThreads(first: 100)') + }) + + it.each([ + ['a failed page', { ok: false, failure: { code: 'unavailable', message: 'Rate limited' } }, 'Rate limited'], + ['a page that repeats its cursor', { ok: true, page: threadPage([false], 'page-1') }, 'GitHub review thread pagination did not advance'], + ['a page without a cursor', { ok: true, page: { pageInfo: { hasNextPage: true, endCursor: null }, nodes: [] } }, + 'GitHub review thread pagination did not advance'], + ] satisfies [string, ThreadPageResult, string][])('fails the pull request for %s without losing another one', async (_label, page, message) => { + const query = snapshotQuery([pull(1), pull(2)], MAX_THREADS) + const body = { data: { r0: { ...repositorySettings(), p0: pullRequestNode(1, { reviewThreads: threadPage(hundred(0), 'page-1') }), p1: pullRequestNode(2) } } } + + const results = await mapSnapshotResponse(body, query, { threads: async () => page }) + + expect(results.get(changeRequestKey(pull(1)))).toEqual({ code: 'unavailable', message }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + }) +}) + describe('check page mapping', () => { it('validates the next page', () => { const page = { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [statusContext('ci', 'SUCCESS')] } @@ -326,6 +398,29 @@ describe('check page mapping', () => { }) }) +describe('review thread page mapping', () => { + it('validates the next page', () => { + const page = threadPage([true, false], 'next') + expect(mapThreadPageResponse({ data: { node: { reviewThreads: page } } })).toEqual({ ok: true, page }) + }) + + it.each([ + [{ data: { node: null } }, 'GitHub review thread page is unavailable'], + [{ data: { node: { reviewThreads: threadPage([true]) } }, errors: [{ message: 'Rate limited' }] }, 'Rate limited'], + [{ data: { node: { reviewThreads: { nodes: [] } } } }, 'unexpected GitHub review thread page'], + ])('rejects unavailable, partial, or malformed pages', (body, message) => { + expect(mapThreadPageResponse(body)).toEqual({ ok: false, failure: { code: 'unavailable', message } }) + }) +}) + +describe('head commit mapping', () => { + it('returns the head commit, or nothing for a response that names none', () => { + expect(mapHeadCommitResponse({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40) } } } })).toBe('a'.repeat(40)) + expect(mapHeadCommitResponse({ data: { repository: { pullRequest: null } } })).toBeUndefined() + expect(mapHeadCommitResponse('not json')).toBeUndefined() + }) +}) + describe('head branch lookup mapping', () => { const body = (defaultBranch: string | null, nodes: { number: number; isCrossRepository: boolean }[]) => ({ data: { repository: { defaultBranchRef: defaultBranch === null ? null : { name: defaultBranch }, pullRequests: { nodes } } }, diff --git a/packages/experimental/forge-github/tests/plugin.spec.ts b/packages/experimental/forge-github/tests/plugin.spec.ts index a214182694..1385e6094e 100644 --- a/packages/experimental/forge-github/tests/plugin.spec.ts +++ b/packages/experimental/forge-github/tests/plugin.spec.ts @@ -56,6 +56,8 @@ describe('forge-github plugin', () => { [{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'], + [{ maxReviewThreads: 0 }, 'forge-github: maxReviewThreads must be a positive safe integer'], + [{ maxReviewThreads: 2.5 }, 'forge-github: maxReviewThreads must be a positive safe integer'], ])('rejects %j at load', async (config, message) => { const context = await forge() diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index ce513e0ab8..bc48a26b30 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -2,8 +2,10 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import { describe, expect, it } from 'vitest' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from '../src/gh.ts' import type { GhOutput, GhRunner } from '../src/gh.ts' +import { HEAD_COMMIT_QUERY, THREADS_QUERY } from '../src/graphql.ts' import { GitHubProvider } from '../src/provider.ts' -import { checkRun, demo, pull, pullRequestNode } from './fixtures.ts' +import type { GitHubLimits } from '../src/provider.ts' +import { checkRun, demo, pull, pullRequestNode, threadPage } from './fixtures.ts' const enterprise = { forge: 'github', host: 'ghe.corp.example', owner: 'team', name: 'svc' } const signal = new AbortController().signal @@ -23,8 +25,10 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { return { exitCode, stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), stderr } } +const limits: GitHubLimits = { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000 } + function provider(run: GhRunner): GitHubProvider { - return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608) + return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], limits) } describe('GitHub provider addressing', () => { @@ -46,7 +50,7 @@ describe('GitHub provider addressing', () => { it('uses a configured HTTP port for URL mapping and GitHub queries', async () => { const gh = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1) } } })) - const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608) + const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], limits) const repository = subject.repositoryFromRemote('https://ghe.example.com:8443/team/repo.git')! const ref = { repository, number: 1 } expect(subject.changeRequestFromUrl(subject.changeRequestUrl(ref))).toEqual(ref) @@ -69,6 +73,47 @@ describe('GitHub provider fetch', () => { expect(gh.calls).toHaveLength(1) }) + it('counts review threads past the first page while polling, bounded by maxReviewThreads', async () => { + const many = pullRequestNode(1, { reviewThreads: threadPage(Array.from({ length: 100 }, () => true), 'threads-1') }) + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) + ? output({ data: { node: { reviewThreads: threadPage([false, false], 'threads-2') } } }) + : output({ data: { r0: { p0: many, p1: pullRequestNode(2) } } })) + + const results = await new GitHubProvider(gh.run, ['github.com'], { ...limits, maxReviewThreads: 102 }).fetch([pull(1), pull(2)], signal) + + expect(results.get(changeRequestKey(pull(1)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: true }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + expect(gh.calls).toHaveLength(2) + expect(gh.calls[1]).toEqual(['api', 'graphql', '--hostname', 'github.com', + '-f', `query=${THREADS_QUERY}`, '-f', 'id=pull-1', '-f', 'cursor=threads-1', '-F', 'first=2']) + }) + + it.each([ + [new GhTimeoutError('timed out'), 'unavailable'], + [new GhOutputLimitError('too much output'), 'too-large'], + [new GhUnavailableError('gh missing'), 'unavailable'], + ] as const)('fails only the pull request whose review thread page cannot be read', async (error, code) => { + const many = pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) + const gh = fakeGh((args) => { + if (args.includes(`query=${THREADS_QUERY}`)) throw error + return output({ data: { r0: { p0: many, p1: pullRequestNode(2) } } }) + }) + + const results = await provider(gh.run).fetch([pull(1), pull(2)], signal) + + expect(results.get(changeRequestKey(pull(1)))).toEqual({ code, message: error.message }) + expect(results.get(changeRequestKey(pull(2)))).toMatchObject({ title: 'Change 2' }) + }) + + it('reports a review thread page that GitHub refuses', async () => { + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) + ? output({ message: 'API rate limit exceeded' }, 1, 'gh: API rate limit exceeded (HTTP 403)') + : output({ data: { r0: { p0: pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) } } })) + + await expect(provider(gh.run).fetchChecks(pull(1), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'gh: API rate limit exceeded (HTTP 403)' }) + }) + it.each([ [new GhTimeoutError('timed out'), 'unavailable'], [new GhOutputLimitError('too much output'), 'too-large'], @@ -92,7 +137,7 @@ describe('GitHub provider fetch', () => { const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(last.stdout) for (const limit of [total, total - 1, Buffer.byteLength(first.stdout) - 1]) { const gh = fakeGh(args => args.includes('id=fixed-rollup') ? last : first) - const result = await new GitHubProvider(gh.run, ['github.com'], limit).fetchChecks(pull(1), signal) + const result = await new GitHubProvider(gh.run, ['github.com'], { ...limits, maxOutputBytes: limit }).fetchChecks(pull(1), signal) if (limit === total) expect(result).toMatchObject({ checksTruncated: false }) else expect(result).toMatchObject({ code: 'too-large' }) expect(gh.calls).toHaveLength(limit < Buffer.byteLength(first.stdout) ? 1 : 2) @@ -192,7 +237,7 @@ describe('GitHub provider fetch', () => { it('rejects references retained after their host was removed from configuration', async () => { const gh = fakeGh(() => output('')) const retained = provider(gh.run).changeRequestFromUrl('https://ghe.corp.example/team/svc/pull/2')! - const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608) + const replacement = new GitHubProvider(gh.run, ['github.com'], limits) const results = await replacement.fetch([retained], signal) await expect(replacement.findByHead(retained.repository, 'topic', signal)).rejects.toThrow('is not configured') expect(results.get(changeRequestKey(retained))).toMatchObject({ code: 'unavailable' }) @@ -354,12 +399,66 @@ describe('GitHub provider actions', () => { describe('GitHub provider reads', () => { const head = 'c'.repeat(40) + const pushed = 'd'.repeat(40) - it('reads the pull request diff through gh pr diff on its host', async () => { - const gh = fakeGh(() => output('diff --git a/x b/x\n')) + /** Answer head commit reads with `heads` in turn, the last one repeating, and every other command with `other`. */ + function pinned(heads: readonly (string | GhOutput)[], other: (args: readonly string[]) => GhOutput = () => output('diff --git a/x b/x\n')) { + let read = 0 + return fakeGh((args) => { + if (!args.includes(`query=${HEAD_COMMIT_QUERY}`)) return other(args) + const answer = heads[Math.min(read++, heads.length - 1)] + return typeof answer === 'string' ? output({ data: { repository: { pullRequest: { headRefOid: answer } } } }) : answer! + }) + } - await expect(provider(gh.run).diff(pull(7, enterprise), signal)).resolves.toBe('diff --git a/x b/x\n') - expect(gh.calls).toEqual([['pr', 'diff', '7', '--repo', 'ghe.corp.example/team/svc', '--color', 'never']]) + it('reads the pull request diff through gh pr diff on its host between two reads of the requested head', async () => { + const gh = pinned([head]) + + await expect(provider(gh.run).diff(pull(7, enterprise), head, signal)).resolves.toBe('diff --git a/x b/x\n') + const headRead = ['api', 'graphql', '--hostname', 'ghe.corp.example', + '-f', `query=${HEAD_COMMIT_QUERY}`, '-f', 'owner=team', '-f', 'name=svc', '-F', 'number=7'] + expect(gh.calls).toEqual([headRead, ['pr', 'diff', '7', '--repo', 'ghe.corp.example/team/svc', '--color', 'never'], headRead]) + }) + + it('compares the head commit without regard to case', async () => { + await expect(provider(pinned([head]).run).diff(pull(7), head.toUpperCase(), signal)).resolves.toBe('diff --git a/x b/x\n') + }) + + it('reports a head that moved before the read as stale without reading the diff', async () => { + const gh = pinned([pushed]) + + await expect(provider(gh.run).diff(pull(7), head, signal)) + .resolves.toEqual({ code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + expect(gh.calls).toHaveLength(1) + }) + + it('discards a diff read while the head moved', async () => { + const gh = pinned([head, pushed]) + + await expect(provider(gh.run).diff(pull(7), head, signal)) + .resolves.toEqual({ code: 'stale', message: `the pull request head moved from ${head} to ${pushed}` }) + expect(gh.calls.map(call => call[0] === 'pr' ? 'diff' : 'head')).toEqual(['head', 'diff', 'head']) + }) + + it.each([ + ['before the diff', [output({ data: { repository: { pullRequest: null } }, errors: [{ type: 'NOT_FOUND', message: 'Could not resolve' }] }, 1, + 'gh: Could not resolve to a PullRequest with the number of 7.')], 1, + { code: 'not-found', message: 'gh: Could not resolve to a PullRequest with the number of 7.' }], + ['after the diff', [head, output({ message: 'Server Error' }, 1, 'gh: Server Error (HTTP 502)')], 3, { code: 'unavailable', message: 'Server Error' }], + ['without a head commit in the answer', [output({ data: { repository: {} } })], 1, + { code: 'unavailable', message: 'unexpected GitHub response to the head commit read' }], + ] as const)('reports a head read that fails %s', async (_label, heads, calls, failure) => { + const gh = pinned(heads) + + await expect(provider(gh.run).diff(pull(7), head, signal)).resolves.toEqual(failure) + expect(gh.calls).toHaveLength(calls) + }) + + it('refuses a head that is not a full commit object name before starting gh', async () => { + const gh = pinned([head]) + + await expect(provider(gh.run).diff(pull(7), 'HEAD', signal)).rejects.toThrow('forge-github: invalid head commit "HEAD"') + expect(gh.calls).toEqual([]) }) it('reads a file at a commit through the raw contents API, encoding each path segment', async () => { @@ -401,18 +500,18 @@ describe('GitHub provider reads', () => { { code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }], ['no output', '', '', { code: 'unavailable', message: 'gh exited with 1' }], ])('reports a read refused for %s', async (_label, body, stderr, failure) => { - await expect(provider(fakeGh(() => output(body, 1, stderr)).run).diff(pull(7), signal)).resolves.toEqual(failure) + await expect(provider(pinned([head], () => output(body, 1, stderr)).run).diff(pull(7), head, signal)).resolves.toEqual(failure) }) it('reports a read as unavailable when gh cannot start, rethrows other failures, and refuses an invalid commit', async () => { - await expect(provider(() => Promise.reject(new GhUnavailableError('gh could not start: spawn gh ENOENT'))).diff(pull(7), signal)) + await expect(provider(() => Promise.reject(new GhUnavailableError('gh could not start: spawn gh ENOENT'))).diff(pull(7), head, signal)) .resolves.toEqual({ code: 'unavailable', message: 'gh could not start: spawn gh ENOENT' }) await expect(provider(() => Promise.reject(new Error('aborted'))).fileText(pull(7), head, 'a', signal)).rejects.toThrow('aborted') await expect(provider(fakeGh(() => output('')).run).fileText(pull(7), 'main', 'a', signal)).rejects.toThrow('forge-github: invalid commit "main"') }) it('reports output over maxOutputBytes as too large and a run past timeoutMs as unavailable', async () => { - await expect(provider(() => Promise.reject(new GhOutputLimitError('gh pr output exceeds maxOutputBytes'))).diff(pull(7), signal)) + await expect(provider(() => Promise.reject(new GhOutputLimitError('gh pr output exceeds maxOutputBytes'))).diff(pull(7), head, signal)) .resolves.toEqual({ code: 'too-large', message: 'gh pr output exceeds maxOutputBytes' }) await expect(provider(() => Promise.reject(new GhTimeoutError('gh api timed out after 30000ms'))).fileText(pull(7), head, 'a', signal)) .resolves.toEqual({ code: 'unavailable', message: 'gh api timed out after 30000ms' }) @@ -427,7 +526,7 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.readiness(target.repository.host, signal)).resolves.toEqual({ state: 'unavailable', message }) await expect(subject.markReady(target, signal)).resolves.toEqual({ code: 'failed', message }) await expect(subject.merge(target, { method: 'squash', headSha: 'a'.repeat(40) }, signal)).resolves.toEqual({ code: 'failed', message }) - await expect(subject.diff(target, signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.diff(target, 'a'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) expect(gh.calls).toEqual([]) }) diff --git a/packages/experimental/forge-github/tests/review.spec.ts b/packages/experimental/forge-github/tests/review.spec.ts index e128508994..002d018f6a 100644 --- a/packages/experimental/forge-github/tests/review.spec.ts +++ b/packages/experimental/forge-github/tests/review.spec.ts @@ -11,7 +11,7 @@ const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment } const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' } function fixture() { const gh = vi.fn().mockResolvedValueOnce({ exitCode: 0, stdout: JSON.stringify({ head: { sha: head }, state: 'open' }), stderr: '' }).mockResolvedValue(success) - return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608), signal: new AbortController().signal } + return { gh, provider: new GitHubProvider(gh, ['github.com'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000 }), signal: new AbortController().signal } } describe('review submission', () => { @@ -91,7 +91,7 @@ describe('review submission', () => { }) it('rejects a host outside the provider configuration without invoking gh', async () => { const { gh, signal } = fixture() - expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) + expect(await new GitHubProvider(gh, ['enterprise.test'], { maxOutputBytes: 8_388_608, maxReviewThreads: 1_000 }).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) expect(gh).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/forge-session/tests/fixtures.ts b/packages/experimental/forge-session/tests/fixtures.ts index d176c97101..2c857ad28e 100644 --- a/packages/experimental/forge-session/tests/fixtures.ts +++ b/packages/experimental/forge-session/tests/fixtures.ts @@ -46,6 +46,7 @@ export function snapshot(ref: ChangeRequestRef, overrides: Partial ({ + id: 'pull-' + number, number, url: 'https://github.com/octo/demo/pull/' + number, title: 'Change ' + number, @@ -84,7 +85,7 @@ const node = (number) => ({ mergeable: 'MERGEABLE', mergeStateStatus: number === 7 ? 'BLOCKED' : 'CLEAN', reviewDecision: null, - reviewThreads: { nodes: [] }, + reviewThreads: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [] }, commits: { nodes: [{ commit: { statusCheckRollup: { id: 'rollup-' + number, state: number === 7 ? 'PENDING' : 'SUCCESS', contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [{ diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index a51d57819e..a60d0a4d78 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 9ca86ee541048ff2 - zh: 7aef4feb76542dd6 + en: 897de781e679f5f2 + zh: 3d0c589742a4dac0 /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 5d2bb55ec6..e04f46a256 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -36,7 +36,7 @@ Mount the registry with at least one provider package, such as the GitHub provid `markReady(ref, signal)` marks a draft ready for review, and `merge(ref, { method, headSha }, signal)` merges a change request only while its head is still `headSha`. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to undefined once the host accepted the change or to a `ForgeActionFailure`: `unauthenticated`, `stale` when the head moved past `headSha`, or `failed` with the host's reason. After either settles, a watched change request is polled at once. Snapshots carry `mergeReady`, whether the host would merge the change request now for the signed-in user, and `mergeMethods`, the methods the repository accepts with that user's usual one first. -`diff(ref, signal)` reads the change request's unified patch as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. +`diff(ref, headSha, signal)` reads the change request's unified patch at head commit `headSha` as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. A provider returns a patch only when it describes `headSha`; once the head is another commit, `diff` resolves to `stale`, and a watched change request is polled at once so its next status names the current head. Snapshots carry `unresolvedThreads` with `threadsTruncated`, which marks the count as a lower bound when the provider counted only some review threads. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 8961c8d31d..9e61402f5b 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -36,7 +36,7 @@ kind: "package-reference" `markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`,或带主机原因的 `failed`。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 -`diff(ref, signal)` 读取托管平台计算出的变更请求统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 +`diff(ref, headSha, signal)` 读取托管平台计算出的变更请求在 head 提交 `headSha` 处的统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。提供方只在补丁描述 `headSha` 时返回补丁;head 已是其他提交时,`diff` resolve 为 `stale`,被 watch 的变更请求随即重新轮询,使下一次状态给出当前 head。快照携带 `unresolvedThreads` 与 `threadsTruncated`;提供方只统计了部分评审讨论时,后者表示该计数只是下限。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index d5204d988a..df05ef9796 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -236,15 +236,20 @@ export class ForgeService extends Service { } /** - * Read the changes of a change request as its host computes them. + * Read the changes of a change request at one head commit as its host + * computes them. A `stale` failure polls the change request again at once + * when it is watched, so its next status names the current head. * @param ref - change request served by a registered provider. + * @param headSha - head commit the patch must describe, usually the head of the latest status. * @param signal - cancellation of the read. - * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`. * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. */ - async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise { - return await this.invoke(this.registration(ref.repository.forge), signal, - (provider, operation) => provider.diff(ref, operation)) + async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { + const result = await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.diff(ref, headSha, operation)) + if (typeof result !== 'string' && result.code === 'stale') this.refresh(ref) + return result } /** diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 35a977dcfe..7d124dc80f 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -100,8 +100,10 @@ export interface ChangeRequestSnapshot { readonly checksRollup: ChecksRollup /** Whether the host reported more checks than `checks` contains. */ readonly checksTruncated: boolean - /** Number of review threads that are not resolved. */ + /** Number of counted review threads that are not resolved. */ readonly unresolvedThreads: number + /** Whether the change request has more review threads than the provider counted, so `unresolvedThreads` is a lower bound. */ + readonly threadsTruncated: boolean /** ISO 8601 time of the host's last update to the change request. */ readonly updatedAt: string /** ISO 8601 time the change request was merged or closed, or null while it is open. */ @@ -113,9 +115,10 @@ export interface ForgeFailure { /** * `not-found`: the host does not expose it; `unauthenticated`: credentials are missing or rejected; * `too-large`: the host or the provider refuses an answer over its size limit, so reading again fails - * the same way; `unavailable`: any other failure. + * the same way; `stale`: the head is no longer the commit the read named, so reading again at the head of + * a later status can succeed; `unavailable`: any other failure. */ - readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'unavailable' + readonly code: 'not-found' | 'unauthenticated' | 'too-large' | 'stale' | 'unavailable' /** Human-readable cause. */ readonly message: string } @@ -214,8 +217,12 @@ export interface ForgeProvider { markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise /** Merge a change request while its head is still `request.headSha`, resolving to undefined once merged. */ merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise - /** Read the changes of a change request as the host computes them, as one unified patch with `a/` and `b/` path prefixes. */ - diff(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes of a change request at head commit `headSha` as the host computes them, as one unified + * patch with `a/` and `b/` path prefixes. A patch is returned only when it describes `headSha`; once the + * head is another commit, the read resolves to a `stale` failure. + */ + diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise /** Read the text of `path` at `commit` in the change request's repository. */ fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ diff --git a/packages/experimental/forge/tests/fake-provider.ts b/packages/experimental/forge/tests/fake-provider.ts index 6f04abdc00..d82f6e7b65 100644 --- a/packages/experimental/forge/tests/fake-provider.ts +++ b/packages/experimental/forge/tests/fake-provider.ts @@ -39,6 +39,7 @@ export function snapshot(target: ChangeRequestRef, overrides: Partial { - this.actions.push(`diff ${target.number}`) + async diff(target: ChangeRequestRef, headSha: string): Promise { + this.actions.push(`diff ${target.number} ${headSha}`) return this.readResult } diff --git a/packages/experimental/forge/tests/lifecycle.spec.ts b/packages/experimental/forge/tests/lifecycle.spec.ts index 26e779eb87..1021b2fa1f 100644 --- a/packages/experimental/forge/tests/lifecycle.spec.ts +++ b/packages/experimental/forge/tests/lifecycle.spec.ts @@ -137,7 +137,7 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', }) vi.spyOn(provider, 'markReady').mockImplementation(async (_ref, signal) => { await hold(signal); return undefined }) vi.spyOn(provider, 'merge').mockImplementation(async (_ref, _request, signal) => { await hold(signal); return undefined }) - vi.spyOn(provider, 'diff').mockImplementation(async (_ref, signal) => { await hold(signal); return 'diff' }) + vi.spyOn(provider, 'diff').mockImplementation(async (_ref, _headSha, signal) => { await hold(signal); return 'diff' }) vi.spyOn(provider, 'fileText').mockImplementation(async (_ref, _commit, _path, signal) => { await hold(signal); return 'file' }) provider.submitReview = async (_ref, _request, signal) => { await hold(signal); return { ok: true, url: 'https://fake.test/review' } } provider.fetchChecks = async (target, signal) => { await hold(signal); return snapshot(target) } @@ -150,7 +150,7 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', readiness: () => service.readiness(demo, signal), markReady: () => service.markReady(ref(1), signal), merge: () => service.merge(ref(1), { method: 'squash', headSha: 'a'.repeat(40) }, signal), - diff: () => service.diff(ref(1), signal), + diff: () => service.diff(ref(1), 'a'.repeat(40), signal), fileText: () => service.fileText(ref(1), 'a'.repeat(40), 'file.txt', signal), } const rejected = expect(calls[method]()).rejects.toThrow('was unregistered') diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index c70a07057b..30af40c019 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -71,7 +71,7 @@ describe('forge registry', () => { await expect(ctx.forge.markReady(ref(1, elsewhere), signal)).rejects.toThrow('forge: no provider is registered for "missing"') await expect(ctx.forge.merge(ref(1, elsewhere), { method: 'squash', headSha: 'a'.repeat(40) }, signal)) .rejects.toThrow('forge: no provider is registered for "missing"') - await expect(ctx.forge.diff(ref(1, elsewhere), signal)).rejects.toThrow('forge: no provider is registered for "missing"') + await expect(ctx.forge.diff(ref(1, elsewhere), 'a'.repeat(40), signal)).rejects.toThrow('forge: no provider is registered for "missing"') await expect(ctx.forge.fileText(ref(1, elsewhere), 'a'.repeat(40), 'x', signal)).rejects.toThrow('forge: no provider is registered for "missing"') expect(() => ctx!.forge.fileUrl(ref(1, elsewhere), 'a'.repeat(40), 'x')).toThrow('forge: no provider is registered for "missing"') }) @@ -97,11 +97,11 @@ describe('forge registry', () => { await provide(ctx, provider) const signal = new AbortController().signal - await expect(ctx.forge.diff(ref(3), signal)).resolves.toBe('diff --git a/x b/x') + await expect(ctx.forge.diff(ref(3), 'a'.repeat(40), signal)).resolves.toBe('diff --git a/x b/x') provider.readResult = { code: 'not-found', message: 'gone' } await expect(ctx.forge.fileText(ref(3), 'b'.repeat(40), 'src/a.ts', signal)).resolves.toEqual({ code: 'not-found', message: 'gone' }) expect(ctx.forge.fileUrl(ref(3), 'b'.repeat(40), 'src/a.ts')).toBe(`https://fake.test/Octo/Demo/file/${'b'.repeat(40)}/src/a.ts`) - expect(provider.actions).toEqual(['diff 3', `text 3 ${'b'.repeat(40)} src/a.ts`]) + expect(provider.actions).toEqual([`diff 3 ${'a'.repeat(40)}`, `text 3 ${'b'.repeat(40)} src/a.ts`]) }) it('delegates change request actions to the provider of their forge and returns its outcome', async () => { diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 5760417c26..2685e0d904 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -223,6 +223,27 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(3) }) + it('polls a watched change request at once after a diff read finds a newer head, and only then', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + + provider.readResult = 'diff --git a/x b/x' + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + provider.readResult = { code: 'not-found', message: 'gone' } + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(1) + + provider.readResult = { code: 'stale', message: 'the head moved' } + await expect(context.forge.diff(ref(1), 'a'.repeat(40), signal)).resolves.toEqual({ code: 'stale', message: 'the head moved' }) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..9e5da268f3 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1246,10 +1246,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ throws: ['on cancellation, provider disposal, or expiry of this read\'s own `fetchTimeoutMs` deadline.'], }, { - signature: 'async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise', - description: 'Read the changes of a change request as its host computes them.', - parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'signal', description: 'cancellation of the read.' }], - returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it.', + signature: 'async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise', + description: 'Read the changes of a change request at one head commit as its host computes them. A `stale` failure polls the change request again at once when it is watched, so its next status names the current head.', + parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'headSha', description: 'head commit the patch must describe, usually the head of the latest status.' }, { name: 'signal', description: 'cancellation of the read.' }], + returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], }, { @@ -1372,7 +1372,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read the changes of a change request of a Session as its code host computes them, at the head commit of its latest status. A patch already read at the same head commit and base branch is reused from memory, for any Session, until `maxCachedDiffBytes` evicts it.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'signal', description: 'request cancellation.' }], returns: 'the files, the head commit, each file\'s web page, and the commits the checkout has beyond the head.', - throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise.'], + throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/stale-head` when the head moved past the latest status, which is then polled again; `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise.'], }, { signature: '@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise', @@ -5956,7 +5956,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ChangeRequestSnapshot', - declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly unresolvedThreads: number;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', + declaration: 'export interface ChangeRequestSnapshot {\n readonly ref: ChangeRequestRef;\n readonly url: string;\n readonly title: string;\n readonly state: ChangeRequestState;\n readonly draft: boolean;\n readonly author: string | null;\n readonly headBranch: string;\n readonly headSha: string;\n readonly baseBranch: string;\n readonly additions: number;\n readonly deletions: number;\n readonly mergeability: Mergeability;\n readonly mergeReady: boolean;\n readonly mergeMethods: readonly MergeMethod[];\n readonly reviewDecision: ReviewDecision;\n readonly checks: readonly ChangeRequestCheck[];\n readonly checksRollup: ChecksRollup;\n readonly checksTruncated: boolean;\n readonly unresolvedThreads: number;\n readonly threadsTruncated: boolean;\n readonly updatedAt: string;\n readonly closedAt: string | null;\n}', }, { name: 'ChangeRequestState', @@ -6604,7 +6604,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeFailure', - declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'unavailable\';\n readonly message: string;\n}', + declaration: 'export interface ForgeFailure {\n readonly code: \'not-found\' | \'unauthenticated\' | \'too-large\' | \'stale\' | \'unavailable\';\n readonly message: string;\n}', }, { name: 'ForgeLineComment', @@ -6640,7 +6640,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeProvider', - declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n}', + declaration: 'export interface ForgeProvider {\n readonly forge: string;\n submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise;\n repositoryFromRemote(url: string): ForgeRepository | undefined;\n changeRequestFromUrl(url: string): ChangeRequestRef | undefined;\n changeRequestUrl(ref: ChangeRequestRef): string;\n fetch(refs: readonly ChangeRequestRef[], signal: AbortSignal): Promise>;\n fetchChecks?(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n findByHead(repository: ForgeRepository, branch: string, signal: AbortSignal): Promise;\n readiness(host: string, signal: AbortSignal): Promise;\n markReady(ref: ChangeRequestRef, signal: AbortSignal): Promise;\n merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): Promise;\n diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise;\n fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise;\n fileUrl(ref: ChangeRequestRef, commit: string, path: string): string;\n}', }, { name: 'ForgeReadiness', From 3430de353188d0f27554cd75f424cc94b5fc313c Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 16:16:47 +0800 Subject: [PATCH 039/103] Keep platform-specific CUA instructions and hover policy in the macOS provider --- packages/experimental/cua-macos/README.md | 28 +++++++++---------- packages/experimental/cua-macos/README.zh.md | 28 +++++++++---------- .../cua-macos/native/README.i18n.yaml | 4 +-- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 8 ++++-- .../CuaNative/RequestCoordinator.swift | 3 +- .../native/Sources/CuaNative/Runtime.swift | 7 ++++- .../tests/swift/SharedHelperTests.swift | 10 ++++++- .../experimental/cua-macos/src/guidance.ts | 18 ++++++++++-- packages/experimental/cua-macos/src/index.ts | 5 ++-- .../cua-macos/src/shared-native.ts | 11 +++++--- .../cua-macos/tests/guidance.spec.ts | 13 ++++++--- .../tests/provider-lifecycle.spec.ts | 25 ++--------------- .../cua-macos/tests/shared-native.spec.ts | 14 ++++++---- packages/experimental/cua/README.i18n.yaml | 4 +-- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 27 +++++++++--------- packages/experimental/cua/src/index.ts | 3 -- .../experimental/cua/src/native-schema.ts | 4 +-- packages/experimental/cua/src/types.ts | 22 ++++++--------- .../cua-native/system-prompt.expected.md | 28 +++++++++---------- .../cua-native/workspace/native-helper.mjs | 8 ++++-- .../session/cua-ptc/system-prompt.expected.md | 28 +++++++++---------- .../system-prompt.expected.md | 28 +++++++++---------- 26 files changed, 177 insertions(+), 157 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 742e218285..6abe3c08de 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -176,7 +176,7 @@ The plugin contributes one `cua` operation tool with method-specific parameters. ##### Operation guidance (verbatim) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -187,20 +187,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. Searches /Applications, /System/Applications, and ~/Applications. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. Unhides the app and restores its focused, main, or sole window without activating it. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. Unhides the app and restores this window without activating it. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -210,17 +210,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. Line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 276baf2131..13f4fa1d06 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -176,7 +176,7 @@ AppKit 的 sheet 可以出现在文档窗口的树里,并有独立的窗口 ID ##### 操作指导文本(原文) ```markdown -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -187,20 +187,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. Searches /Applications, /System/Applications, and ~/Applications. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. Unhides the app and restores its focused, main, or sole window without activating it. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. Unhides the app and restores this window without activating it. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -210,17 +210,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. Line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 25d5fb8952..8d43fbd6b8 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 88a59904ca4ebedc zh: 14f2b666d7382145 /dsh-cua-native-helper/observation-and-input: - en: da6a1c45fd166818 - zh: 7f378d5409a6085d + en: 2d380e942a4057e4 + zh: fe7c9339ec63a6e5 /dsh-cua-native-helper/verification: en: 49f4cce2a4cc3114 zh: e9d65c92ef35fe24 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index bdb844e806..bc80110951 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -121,7 +121,7 @@ Tree observation and action discovery treat a generic AX failure reading one ele `paste` publishes one plain-text or HTML clipboard format, dispatches the application's enabled standard Paste menu command, and waits for a clipboard data request. It then restores the preserved formats only while its ownership marker and change count still match. The Host serializes its pastes across helpers with a file lock. maxClipboardBytes bounds both input and preserved contents; unsupported menus and oversized data fail before dispatch. A later copy is preserved. Cancellation restores owned clipboard data when possible; forced termination cannot guarantee restoration, and a data request does not prove the target completed editing. After dispatch, `pasteReadTimeoutMs` bounds waiting for clipboard consumption. Expiry returns `PASTE_NOT_CONSUMED`, closes the promised data provider, and restores the original clipboard only while still owned. The failure does not prove the app will never process its queued Paste command; inspect the target before deciding whether to retry. -`mouseMove` reveals or restores alternate UI through an enabled element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Without an AX route it returns `HOVER_UNAVAILABLE` before sending input. The Host supplies the native boolean `allowSystemPointer` from its `systemPointerHover` setting. Omission means false. Only true permits posting a system pointer move after checking the foreground process and window hit. +`mouseMove` reveals or restores alternate UI through an enabled element or ancestor advertising both `AXShowAlternateUI` and `AXShowDefaultUI`. Without an AX route it returns `HOVER_UNAVAILABLE` before sending input. The macOS provider sets `systemPointerHover` in the connection handshake. Diagnostic clients that omit this setting may opt in per request with `allowSystemPointer: true`. The default is false. Only true permits posting a system pointer move after checking the foreground process and window hit. The opt-in system pointer route returns `FOREGROUND_REQUIRED` if the target is obscured or belongs to a background app. The result reports the route and whether the visible cursor moved in `hoverRoute` and `systemPointerMoved`. It never presses a button or restores the cursor after a read. Later input may interrupt the hover. Clicks send their button events at the target without an off-window priming click. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 51d6c13c29..0927a82bce 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -121,7 +121,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `paste` 提供一种纯文本或 HTML 剪贴板格式,调用应用已启用的标准 Paste 菜单命令,并等待剪贴板数据请求。随后仅在所有权标记和修改计数仍匹配时恢复原有格式。Host 通过文件锁串行化不同 helper 的粘贴。maxClipboardBytes 同时限制输入和保留内容,不支持的菜单和过大的数据在分派前失败。后续复制会被保留。取消会尽可能恢复仍持有的剪贴板数据,强制结束不保证恢复,数据请求也不证明目标已完成编辑。 分派完成后,`pasteReadTimeoutMs` 限制等待剪贴板读取的时间。到期返回 `PASTE_NOT_CONSUMED`,关闭延迟数据提供方,并仅在仍持有剪贴板时恢复原内容。该失败不能证明应用以后不会处理已排队的 Paste 命令;决定是否重试前先检查目标内容。 -默认情况下,`mouseMove` 通过同一窗口内启用的控件或祖先声明的 `AXShowAlternateUI` 和 `AXShowDefaultUI` 展开或恢复界面。缺少这条路径时返回 `HOVER_UNAVAILABLE`,不发送输入。Host 根据部署配置 `systemPointerHover` 传入原生布尔参数 `allowSystemPointer`,省略时为 false。只有值为 true 才允许移动全局光标,且须检查前台进程和鼠标命中的窗口。 +默认情况下,`mouseMove` 通过同一窗口内启用的控件或祖先声明的 `AXShowAlternateUI` 和 `AXShowDefaultUI` 展开或恢复界面。缺少这条路径时返回 `HOVER_UNAVAILABLE`,不发送输入。macOS 提供方在连接握手中设置 `systemPointerHover`。未在握手中指定该配置的诊断客户端,可以在单次请求中传入 `allowSystemPointer: true`。默认值为 false。只有值为 true 才允许移动全局光标,且须检查前台进程和鼠标命中的窗口。 开启后,系统指针路线会检查前台应用和坐标命中的窗口,不满足条件时返回 `FOREGROUND_REQUIRED`。返回值 `hoverRoute` 和 `systemPointerMoved` 说明走了哪条路线以及是否移动了可见光标。悬停不会按下鼠标,也不会在读取后还原光标。后续输入可能中断悬停。点击只在目标点发送按键事件,不先在窗口外点击。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 73e8e78fd9..96a6054525 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -78,6 +78,7 @@ actor AXWorker { private let axTimeout: Float private let textEventInterval: Double private let maxClickHoldMs: Int + private let systemPointerHover: Bool? private let sessionState: @Sendable () -> Bool? private var access: AXAccess? private var keyboard: KeyboardInput? @@ -85,12 +86,13 @@ actor AXWorker { private var hovers: [String: AXHover] = [:] private var closed = false - init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, + init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, systemPointerHover: Bool? = nil, sessionState: @escaping @Sendable () -> Bool? = NativePlatform.sessionLocked) { self.cancellation = cancellation self.axTimeout = axTimeout self.textEventInterval = textEventInterval self.maxClickHoldMs = maxClickHoldMs + self.systemPointerHover = systemPointerHover self.sessionState = sessionState } private func identifier(_ kind: String) throws -> String { @@ -105,7 +107,9 @@ actor AXWorker { return created } private func moveUsingAX(_ element: AXUIElement?, windowID: UInt32, handle: String, params: RequestParameters) throws -> Bool { - let allowSystemPointer = try params.optionalBoolean("allowSystemPointer") ?? false + let requestSetting = try params.optionalBoolean("allowSystemPointer") + // Diagnostic JSONL clients without a deployment setting may opt in per request. + let allowSystemPointer = systemPointerHover ?? requestSetting ?? false let hover = hovers[handle] ?? AXHover() hovers[handle] = hover if try hover.move(to: element, in: windowID, access: ax()) { return true } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 3a778cb8ae..000a69e848 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -42,7 +42,8 @@ import Darwin self.onClose = onClose self.onFatal = onFatal worker = AXWorker(cancellation: cancellation, axTimeout: configuration.axTimeoutSeconds, - textEventInterval: configuration.textEventIntervalSeconds, maxClickHoldMs: configuration.maxClickHoldMs) + textEventInterval: configuration.textEventIntervalSeconds, maxClickHoldMs: configuration.maxClickHoldMs, + systemPointerHover: configuration.systemPointerHover) input = JSONLInput(limit: configuration.maxRequestBytes, cancellation: cancellation, channel: channel) self.writer = writer } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift index d61f0803ab..c31a07ebef 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/Runtime.swift @@ -21,6 +21,7 @@ struct HelperConfiguration: Sendable { var shutdownGraceSeconds: Double = 3 var textEventIntervalSeconds: Double = 0.00025 var maxClickHoldMs = 5000 + var systemPointerHover: Bool? var timeoutSeconds: Double = 30 var screenshotTimeoutSeconds: Double = 5 init(arguments: [String]) throws { @@ -64,7 +65,7 @@ struct HelperConfiguration: Sendable { guard let fields = decoded.object, Set(fields.keys) == ["type", "protocol", "runtimeKey", "config"], fields["type"] == .string("hello"), fields["protocol"] == .number(1), fields["runtimeKey"] == .string(runtimeKey), let config = fields["config"]?.object, - Set(config.keys) == ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "maxClickHoldMs", "screenshotTimeoutMs", "timeoutMs", "graceMs"] else { + Set(config.keys).subtracting(["systemPointerHover"]) == ["maxRequestBytes", "maxResponseBytes", "axTimeoutMs", "textEventIntervalMs", "maxClickHoldMs", "screenshotTimeoutMs", "timeoutMs", "graceMs"] else { throw NativeFailure(code: "NATIVE_PROTOCOL", message: "Expected shared helper protocol 1 hello for this runtime") } func number(_ name: String) throws -> String { @@ -82,6 +83,10 @@ struct HelperConfiguration: Sendable { "--screenshot-timeout-ms", number("screenshotTimeoutMs"), "--timeout-ms", number("timeoutMs"), "--shutdown-grace-ms", number("graceMs"), ]) + if let setting = config["systemPointerHover"] { + guard case .bool(let allowed) = setting else { throw RequestParameters.invalid("systemPointerHover must be a boolean") } + systemPointerHover = allowed + } } } diff --git a/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift b/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift index 9b43bc330e..52f7f0f224 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SharedHelperTests.swift @@ -33,6 +33,14 @@ private func hello(overrides: [String: JSONValue] = [:]) throws -> Data { } } +@Test func readsSystemPointerHoverFromEachConnection() throws { + #expect(try HelperConfiguration(hello: hello(), runtimeKey: runtimeKey).systemPointerHover == nil) + for allowed in [true, false] { + let configuration = try HelperConfiguration(hello: hello(overrides: ["systemPointerHover": .bool(allowed)]), runtimeKey: runtimeKey) + #expect(configuration.systemPointerHover == allowed) + } +} + @Test func resolvesClickHoldLimitFromHelperArguments() throws { #expect(try HelperConfiguration(arguments: []).maxClickHoldMs == 5000) for limit in [0, 7000] { @@ -48,7 +56,7 @@ private func hello(overrides: [String: JSONValue] = [:]) throws -> Data { ("axTimeoutMs", .number(0)), ("textEventIntervalMs", .number(-1)), ("screenshotTimeoutMs", .number(0)), ("timeoutMs", .string("8000")), ("graceMs", .number(-1)), ("maxClickHoldMs", .number(-1)), ("maxClickHoldMs", .number(0.5)), - ("maxClickHoldMs", .number(2147483648)), ("unexpected", .bool(true)), + ("maxClickHoldMs", .number(2147483648)), ("unexpected", .bool(true)), ("systemPointerHover", .string("true")), ]) func refusesInvalidSharedConfiguration(_ name: String, _ value: JSONValue) throws { #expect(throws: NativeFailure.self) { try HelperConfiguration(hello: hello(overrides: [name: value]), runtimeKey: runtimeKey) } diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 9da4e5f85a..0379d91120 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -2,9 +2,23 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' /** macOS operation levels, permissions, selectors, and native measurement units. */ -export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' +export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' + +const methodDetails = new Map([ + ['cua.getApp', 'Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background.'], + ['cua.findApps', 'Searches /Applications, /System/Applications, and ~/Applications.'], + ['app.show', 'Unhides the app and restores its focused, main, or sole window without activating it.'], + ['window.show', 'Unhides the app and restores this window without activating it.'], + ['mouseMove', 'Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured.'], + ['click', 'Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click.'], + ['typeText', 'Line endings send Return and tabs send Tab.'], + ['paste', 'Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying.'], +]) /** Complete model instructions for this provider. */ export const GUIDANCE = `${PLATFORM_GUIDANCE} -${COMMON_GUIDANCE}` +${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { + const detail = methodDetails.get(method) + return detail ? `${entry} ${detail}` : entry +})}` diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 52788c0752..4b07e9c8b7 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url' import type { Context } from '@deepseek-ai/cordis' import Schema from '@deepseek-ai/schemastery' import { installCua, type CuaConfig, type CuaStartupCapabilities } from '@deepseek-ai/dsh-cua' +import type { NativeChannelFactory } from '@deepseek-ai/dsh-cua/native-client' import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { createPermissionParameters } from './permission-guide.ts' import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } from './native-build.ts' @@ -63,8 +64,8 @@ export const Config = Schema.object({ * @returns Completion after native preparation and tool registration. */ export async function apply(ctx: Context, config: Config): Promise { - const backend = { createChannel: createSharedNativeChannel, guidance: GUIDANCE, capabilities: CAPABILITIES, - systemPointerHover: config.systemPointerHover, + const createChannel: NativeChannelFactory = (owner, native) => createSharedNativeChannel(owner, native, config.systemPointerHover) + const backend = { createChannel, guidance: GUIDANCE, capabilities: CAPABILITIES, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { if (!isAbsolute(config.helperPath)) throw new Error('dsh-cua helperPath must be absolute') diff --git a/packages/experimental/cua-macos/src/shared-native.ts b/packages/experimental/cua-macos/src/shared-native.ts index 0fe2cf6436..7be638a96b 100644 --- a/packages/experimental/cua-macos/src/shared-native.ts +++ b/packages/experimental/cua-macos/src/shared-native.ts @@ -56,7 +56,8 @@ class SharedNativeChannel implements NativeChannel { private cleanupTimer: ReturnType | undefined private cleanupFailure: Error | undefined - constructor(private readonly owner: { subprocess: Pick }, private readonly config: NativeClientConfig) { + constructor(private readonly owner: { subprocess: Pick }, private readonly config: NativeClientConfig, + private readonly systemPointerHover: boolean) { this.stdin = new Writable({ write: (chunk: Buffer, encoding, callback) => { void this.ready.promise.then((socket) => { @@ -214,7 +215,8 @@ class SharedNativeChannel implements NativeChannel { const { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, maxClickHoldMs, screenshotTimeoutMs, timeoutMs, graceMs } = this.config socket.write(JSON.stringify({ type: 'hello', protocol: 1, runtimeKey, - config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, maxClickHoldMs, screenshotTimeoutMs, timeoutMs, graceMs } }) + '\n') + config: { maxRequestBytes, maxResponseBytes, axTimeoutMs, textEventIntervalMs, maxClickHoldMs, + screenshotTimeoutMs, timeoutMs, graceMs, systemPointerHover: this.systemPointerHover } }) + '\n') }) const receive = (chunk: Buffer): void => { const newline = chunk.indexOf(10) @@ -286,8 +288,9 @@ class SharedNativeChannel implements NativeChannel { * Prepare or join the native process; writes wait for identity-checked readiness. * @param owner - Provider owning the short-lived native startup command. * @param config - Native runtime identity, operation limits and connection deadlines. + * @param systemPointerHover - Whether this connection may move the visible pointer when AX hover is unavailable. * @returns One independently disposable Agent connection, without operation replay. */ -export function createSharedNativeChannel(owner: { subprocess: Pick }, config: NativeClientConfig): NativeChannel { - return new SharedNativeChannel(owner, config) +export function createSharedNativeChannel(owner: { subprocess: Pick }, config: NativeClientConfig, systemPointerHover: boolean): NativeChannel { + return new SharedNativeChannel(owner, config, systemPointerHover) } diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 7afb53b84c..c00f600a79 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -19,7 +19,7 @@ it('keeps exactly three ordered operation headings', () => { }) it('prefixes concise platform guidance before the shared catalog', () => { - expect(GUIDANCE).toBe(`${PLATFORM_GUIDANCE}\n\n${COMMON_GUIDANCE}`) + expect(GUIDANCE.startsWith(`${PLATFORM_GUIDANCE}\n\nUse cua`)).toBe(true) expect(PLATFORM_GUIDANCE).not.toContain('##') }) @@ -27,9 +27,12 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('accessibility tree operations are available at app or window level') expect(PLATFORM_GUIDANCE).toContain('Simulated keyboard input is available at app level') expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') - const hover = COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) + const hover = GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE', 'systemPointerHover']) expect(hover).toContain(term) - expect(COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- click('))).toContain('call app.activate() first') + expect(GUIDANCE.split('\n').find(line => line.startsWith('- click('))).toContain('call app.activate() first') + for (const platformDetail of ['macOS', 'AXShowAlternateUI', 'AXRaise', 'HOVER_UNAVAILABLE', 'systemPointerHover', 'mouse-down', 'bundle ID', 'Paste command']) { + expect(COMMON_GUIDANCE).not.toContain(platformDetail) + } }) it('enumerates every available method once in its catalog entry', () => { @@ -41,7 +44,9 @@ it('enumerates every available method once in its catalog entry', () => { ...windowNames.filter(name => name !== 'windowId').map(name => `${name}(`), ...['typeText', 'paste', 'pressKey'].map(name => `${name}(`), ] - for (const signature of signatures) expect(COMMON_GUIDANCE.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) + for (const catalog of [COMMON_GUIDANCE, GUIDANCE]) { + for (const signature of signatures) expect(catalog.split('\n').filter(line => line.startsWith(`- ${signature}`))).toHaveLength(1) + } expect(signatures).toHaveLength(24) expect(new Set(signatures.map(signature => signature.slice(signature.indexOf('.') + 1, -1))).size).toBe(23) expect(COMMON_GUIDANCE).toContain('app.appHandle') diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 38e632e6ae..017a605ce1 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -71,6 +71,7 @@ const { helperPath: _helperPath, ...automaticConfig } = config it('defaults to ad-hoc signing and requires a keychain path for certificate signing', () => { expect(NativeProvider.Config({}).sourceSigning).toBe('ad-hoc') + expect(NativeProvider.Config({}).systemPointerHover).toBe(false) expect(NativeProvider.Config({ sourceSigning: 'ad-hoc' }).sourceSigning).toBe('ad-hoc') for (const sourceSigning of [{ identity: 'Apple Development: Example', keychain: '/keychains/custom.keychain-db' }, { identity: 'ABC123', keychain: '/keychains/custom.keychain-db' }]) { expect(NativeProvider.Config({ sourceSigning }).sourceSigning).toEqual(sourceSigning) @@ -109,7 +110,7 @@ class ImageAdapter extends LlmAdapter { const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } -async function setup(model?: { provider: string; model: string }, systemPointerHover = false) { +async function setup(model?: { provider: string; model: string }) { native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() native.instances.length = 0 @@ -119,7 +120,7 @@ async function setup(model?: { provider: string; model: string }, systemPointerH await mountAgentLoopTestDependencies(ctx) await ctx.plugin(ComputerUseRegistry) await ctx.plugin(Subprocess, []) - const provider = await ctx.plugin(NativeProvider, { ...config, systemPointerHover }) + const provider = await ctx.plugin(NativeProvider, config) await mountAgentLoopTestHarness(ctx) const handle = await ctx.agents.create({ sessionId: SessionId('native-lifecycle'), ...model ? { agentOptions: model } : {} }) let index = 0 @@ -386,26 +387,6 @@ it('rejects malformed and unowned operations before acquiring a helper', async ( expect(native.request).not.toHaveBeenCalled() }) -it.each([false, true])('rejects an ended Agent with prior helper acquisition %s', async (acquired) => { - const f = await setup() - if (acquired) await f.execute() - await f.handle.dispose() - const requests = native.request.mock.calls.length - const result = await f.execute() - expect(result.isError).toBe(true) - expect(JSON.stringify(result.content)).toContain('agent has been disposed') - expect(native.instances).toHaveLength(acquired ? 1 : 0) - expect(native.request).toHaveBeenCalledTimes(requests) -}) - -it.each([false, true])('passes the deployment hover policy (%s) to native input', async (allowed) => { - const f = await setup(undefined, allowed) - await selectApplication(f) - const params = { appHandle: 'app-one', windowId: 7, snapshotId: 's', elementId: '0' } - await f.execute('mouseMove', params) - expect(native.request).toHaveBeenLastCalledWith('mouseMove', { ...params, allowSystemPointer: allowed }, expect.any(AbortSignal), expect.any(String)) -}) - it('supplies configured resource bounds and clears registrations on unload', async () => { const f = await setup() await selectApplication(f) diff --git a/packages/experimental/cua-macos/tests/shared-native.spec.ts b/packages/experimental/cua-macos/tests/shared-native.spec.ts index cef346ab9b..871475fb53 100644 --- a/packages/experimental/cua-macos/tests/shared-native.spec.ts +++ b/packages/experimental/cua-macos/tests/shared-native.spec.ts @@ -133,8 +133,8 @@ async function fixture(options: { timeoutMs: 30_000, graceMs: options.graceMs ?? 1000, axTimeoutMs: 3000, maxRequestBytes: 65536, maxResponseBytes: 1048576, textEventIntervalMs: 0.5, maxClickHoldMs: 7000, } - function open(): NativeChannel { - const channel = createSharedNativeChannel({ subprocess: { spawn } }, config) + function open(systemPointerHover = false): NativeChannel { + const channel = createSharedNativeChannel({ subprocess: { spawn } }, config, systemPointerHover) channels.push(channel) return channel } @@ -172,7 +172,7 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', ( it('keeps concurrent Agent scopes independent and leaves other sockets alive when one closes', async () => { const f = await fixture() const first = f.open() - const second = f.open() + const second = f.open(true) const firstReply = nextBytes(first) const secondReply = nextBytes(second) await Promise.all([write(first, 'one\n'), write(second, 'two\n')]) @@ -186,10 +186,14 @@ describe.skipIf(process.platform === 'win32')('shared native Unix connection', ( expect(f.spawn).toHaveBeenCalledTimes(2) // oxlint-disable-next-line typescript/unbound-method -- Fixture termination methods are spies inspected without invocation. for (const handle of f.handles) expect(handle.terminate).not.toHaveBeenCalled() - expect(f.hellos).toEqual([expect.objectContaining({ type: 'hello', protocol: 1, config: { + const limits = { axTimeoutMs: 3000, timeoutMs: 30000, screenshotTimeoutMs: 5000, graceMs: 1000, maxRequestBytes: 65536, maxResponseBytes: 1048576, textEventIntervalMs: 0.5, maxClickHoldMs: 7000, - } }), expect.anything()]) + } + expect(f.hellos).toHaveLength(2) + for (const systemPointerHover of [true, false]) { + expect(f.hellos).toContainEqual(expect.objectContaining({ type: 'hello', protocol: 1, config: { ...limits, systemPointerHover } })) + } }) it('waits for both launcher outcome and managed range release before sending any bytes', async () => { diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index dd3c6d217a..f4abb13c43 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,8 +15,8 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: d0088d2ec1ab8cf2 - zh: d927289a63d7a564 + en: ba1f8e6ae51f69d7 + zh: 8f4fde9857bae319 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: d92d5948a7941e8d zh: d43491ae6521b87e diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 365c549650..c95e4ae8ec 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -43,7 +43,7 @@ Application consent precedes launch, observation, capture, and input. Session ac Actions return a `dispatched` boolean; `mouseMove` also reports `hoverRoute` and `systemPointerMoved`, and `show()` adds `windowId` and `foregroundChanged`. Read fresh state to verify the result. Screenshots and pointer actions are available only on explicit window objects. Coordinate actions default to pixels in the latest returned screenshot; `relative: true` accepts integers from 0 to 999 after a successful window observation. Values are divided by 1000 and scaled to the window dimensions, then clamped inside the window. The Host resolves attachment normalization and the selected model route’s image projection before returning the screenshot, then converts input to the provider’s native window coordinates. Resizing invalidates the screenshot mapping; `SCREENSHOT_REQUIRED` requires a new screenshot for absolute coordinates. Resizing rejects old coordinates with `WINDOW_CHANGED`; movement alone preserves window-local coordinates. -`click(target, { holdMs: 800 })` holds the mouse button for 800 milliseconds before release. `holdMs` applies only to `click`; it accepts nonnegative integers and applies to each press of a double-click; zero releases without an additional hold. The provider config `maxClickHoldMs` limits explicit holds and defaults to 5000 ms. On macOS, both ordinary and held clicks send mouse events at the element center or the supplied point. Use `invoke(id)` for the default accessibility action. The operation deadline includes the hold, and cancellation or timeout releases the button. Received input cannot be undone; forced helper termination cannot guarantee release. +`click(target, { holdMs: 800 })` holds the mouse button for 800 milliseconds before release. `holdMs` applies only to `click`; it accepts nonnegative integers and applies to each press of a double-click; zero releases without an additional hold. The provider config `maxClickHoldMs` limits explicit holds and defaults to 5000 ms. Explicit holds use pointer input; omission preserves ordinary click behavior. The operation deadline includes the hold, and cancellation or timeout releases the button. Received input cannot be undone; forced helper termination cannot guarantee release. ### Permission controls diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index b64c445c44..c1c5ed863c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -43,7 +43,7 @@ kind: "package-reference" 动作返回 `dispatched` 布尔值;`mouseMove` 还会返回 `hoverRoute` 和 `systemPointerMoved`,`show()` 还会返回 `windowId` 和 `foregroundChanged`。请读取新状态以验证结果。截图和指针操作只能通过显式窗口对象使用。坐标操作默认使用最近返回截图中的像素;成功观察窗口后,传入 `relative: true` 可使用 0~999 的整数坐标。数值除以 1000 后按窗口尺寸缩放,并限制在窗口内。Host 在返回截图前解析附件归一化和当前模型的图片缩放规则,再将输入换算为提供方的原生窗口坐标。窗口尺寸变化会使截图映射失效,绝对坐标遇到 `SCREENSHOT_REQUIRED` 时需要重新截图。窗口缩放后以 `WINDOW_CHANGED` 拒绝旧坐标;单纯移动窗口不改变窗口内坐标。 -`click(target, { holdMs: 800 })` 按住鼠标按钮 800 毫秒后松开。`holdMs` 仅适用于 `click`;它接受非负整数,双击时应用于每次按下;0 表示按下后立即松开,不额外等待。提供方配置 `maxClickHoldMs` 限制显式按住时长,默认 5000 毫秒。在 macOS 上,无论是否指定按住时长,点击都会向元素中心或给定坐标发送鼠标事件。要执行控件的默认辅助功能动作,请用 `invoke(id)`。按住时间计入操作超时,取消或超时会松开按钮。已接收的输入无法撤销;辅助进程被强制终止时无法保证松开。 +`click(target, { holdMs: 800 })` 按住鼠标按钮 800 毫秒后松开。`holdMs` 仅适用于 `click`;它接受非负整数,双击时应用于每次按下;0 表示按下后立即松开,不额外等待。提供方配置 `maxClickHoldMs` 限制显式按住时长,默认 5000 毫秒。指定时长后使用鼠标事件;省略时保留普通点击行为。按住时间计入操作超时,取消或超时会松开按钮。已接收的输入无法撤销;辅助进程被强制终止时无法保证松开。 ### 权限控件 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 1d6d0266d1..27be40b4c7 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -1,5 +1,4 @@ /** Shared model instructions for native application and window operations. */ -/** Async method catalog with consent and observation rules, grouped by observation, mouse, and keyboard. */ export const COMMON_GUIDANCE = `Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. In persistent PTC, use the host-provided bridge initialization once and retain the returned objects; cua comes from that bridge and is not a preinstalled global. Use void await for observations that emit, and never stringify screenshot image bytes. @@ -9,20 +8,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -32,17 +31,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 7cb5177f71..d6c75f46bc 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -126,8 +126,6 @@ export interface CuaBackend { createChannel: NativeChannelFactory guidance: string capabilities: CuaStartupCapabilities - /** macOS deployment policy sent only to the native mouseMove operation. */ - systemPointerHover?: boolean /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -213,7 +211,6 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient - if (method === 'mouseMove' && backend.systemPointerHover !== undefined) params.allowSystemPointer = backend.systemPointerHover const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' diff --git a/packages/experimental/cua/src/native-schema.ts b/packages/experimental/cua/src/native-schema.ts index bbd52e2591..a6122ed71e 100644 --- a/packages/experimental/cua/src/native-schema.ts +++ b/packages/experimental/cua/src/native-schema.ts @@ -13,10 +13,10 @@ function variants(schema: Schema): Schema[] { return schema.anyOf ?? schema.oneO /** * Derive native request schemas and admission fields from the shared operation definitions. - * @param platformFields Platform-specific parameters added by the Host before native dispatch. + * @param platformFields Additional native protocol fields accepted by the provider. * @returns Native field and enum tables and the complete wire schema. */ -export function nativeProtocol(platformFields: Partial> = {}): { +export function nativeProtocol(platformFields: Partial['method'] | 'requestPermission' | 'openPermissionSettings', z.ZodObject>> = {}): { fields: Map> enums: Map>> json: string diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 4e5f1ef0d9..4c6b27b78e 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -79,6 +79,7 @@ export type CuaMouseButton = NonNullable['mouseButton']> /** * Left clicks support one or two presses; right and middle clicks support one. * holdMs is a nonnegative integer in milliseconds, limited by maxClickHoldMs; zero releases immediately. + * Explicit holds use pointer input; omission preserves ordinary clicks. */ export type CuaClickOptions = Pick, 'mouseButton' | 'clickCount' | 'modifiers' | 'holdMs'> & CuaCoordinateOptions /** One same-window drag; omitted button is left and omitted modifiers are empty. */ @@ -95,7 +96,7 @@ export type CuaScrollOptions = Pick, 'x' | 'y' | 'deltaL */ export interface CuaSurface { /** - * Unhide the app and restore a minimized selected, focused, main or sole window without requesting activation. + * Request that the provider show the selected application or window. * @returns Dispatch evidence, the selected window when available, and sampled foreground change; read fresh state before input. */ show(): Promise @@ -190,22 +191,17 @@ export interface CuaWindow extends CuaSurface { */ getScreenshot(options?: CuaObservationOptions): Promise /** - * On macOS, prefer an available control's click or advertised accessibility action over hover. - * By default, mouseMove reveals or restores alternate UI on an enabled target or ancestor that advertises - * both AXShowAlternateUI and AXShowDefaultUI. Without an AX route it throws HOVER_UNAVAILABLE before sending input. - * Only the macOS provider's systemPointerHover setting permits moving the visible cursor as a fallback. - * That route requires a foreground app and an unobscured target and leaves the cursor at the destination. + * Request hover at an element or a point in this window. The provider reports the route used and whether + * the visible system pointer moved. Observe the resulting UI after its hover delay. * @param target - current element id or screenshot-local [x,y]. * @param options - coordinate mode; applies only to [x,y]. * @returns dispatch evidence and the selected route; observe the resulting UI after its hover delay. */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions): Promise /** - * Click an element or a point in this window. On macOS both forms send mouse-down and mouse-up events. - * For a background control, prefer {@link CuaSurface.invoke} for its default action. When a mouse click is needed, - * call app.activate() first and observe the target again. Background apps can ignore dispatched mouse events. + * Click a current element id or screenshot-local point. * Cancellation or timeout releases the held button; received input cannot be undone. The operation deadline includes holdMs. - * @param target - On macOS, an id from the latest tree targets the element center. A coordinate pair targets the given point. + * @param target - element id or [x,y]. * @param options - button, click count, modifiers, optional hold duration and coordinate mode. * @returns dispatch evidence. */ @@ -274,9 +270,9 @@ export interface CuaApi { */ getState(options?: CuaObservationOptions): Promise<{ apps: CuaAppInfo[]; browsers: [] }> /** - * Select an app, obtain consent, launch it in the background if necessary, and silently retain initial AX state. - * @param selector - Exact name, bundle ID, absolute application path or running PID string; ambiguous names reject. - * @returns An application handle tied to this process lifetime; its initial tree read becomes the current snapshot. + * Select an app and obtain consent. Providers with app-level accessibility silently read the initial tree. + * @param selector - A selector accepted by the provider; ambiguous matches reject. + * @returns An application handle tied to this process lifetime. */ getApp(selector: string): Promise } diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 1738793701..5a793421cf 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -33,7 +33,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -44,20 +44,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. Searches /Applications, /System/Applications, and ~/Applications. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. Unhides the app and restores its focused, main, or sole window without activating it. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. Unhides the app and restores this window without activating it. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -67,17 +67,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. Line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-native/workspace/native-helper.mjs b/snapshots/session/cua-native/workspace/native-helper.mjs index 0786eeefe6..1e148d7ab5 100755 --- a/snapshots/session/cua-native/workspace/native-helper.mjs +++ b/snapshots/session/cua-native/workspace/native-helper.mjs @@ -47,6 +47,7 @@ function serve() { const server = createServer({ allowHalfOpen: true }, socket => { sockets.add(socket) let connected = false + let systemPointerHover const connectionId = ++connection const input = createInterface({ input: socket }) const scopedRecord = (event, data = {}) => record(event, { connection: connectionId, ...data }) @@ -58,6 +59,7 @@ function serve() { socket.destroy() return } + systemPointerHover = request.config.systemPointerHover connected = true hadClient = true clearTimeout(startupDeadline) @@ -71,7 +73,7 @@ function serve() { } let response try { - const result = call(request.id, request.method, request.params) + const result = call(request.id, request.method, request.params, systemPointerHover) if (result === undefined) return response = { id: request.id, result } } catch (error) { @@ -122,7 +124,7 @@ function createApplicationState(socket, record, application, captureBroker, conn let observationChanged = false let malformedScreenshot = false function refuse(code, message) { throw Object.assign(new Error(message), { code }) } - function call(requestId, method, params) { + function call(requestId, method, params, systemPointerHover) { record('call', { requestId, method, params }) if (method === 'applicationIcons') return Object.fromEntries(params.paths.map(path => [path, `data:image/png;base64,${png}`])) if (method === 'openPermissionSettings') return { opened: true } @@ -203,7 +205,7 @@ function createApplicationState(socket, record, application, captureBroker, conn if (method === 'mouseMove') { const alternate = params.elementId === '0' || (params.x >= 20 && params.x <= 40) if (!alternate && !application.hovering) { - if (!params.allowSystemPointer) refuse('HOVER_UNAVAILABLE', 'No AX alternate UI at this target. No input was sent and the pointer did not move.') + if (!(systemPointerHover ?? params.allowSystemPointer)) refuse('HOVER_UNAVAILABLE', 'No AX alternate UI at this target. No input was sent and the pointer did not move.') systemPointerMoved = true } application.hovering = alternate diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ff29eddb7f..8e3daa7253 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -46,20 +46,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. Searches /Applications, /System/Applications, and ~/Applications. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. Unhides the app and restores its focused, main, or sole window without activating it. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. Unhides the app and restores this window without activating it. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -69,17 +69,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. Line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 434e92e3f7..fcd315e68c 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -35,7 +35,7 @@ Start independent delegations with `subagent` or `subagent_fork` together in one Bash, formatters, code generators, and scripts can overwrite concurrent edits without conflict detection; coordinate their changes explicitly. The agent integrating the work must review the final diff and run relevant tests. -macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. Default hover uses AX alternate UI and keeps the system cursor in place. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). getApp also accepts bundle IDs and .app paths, and findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. +macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action. Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. @@ -46,20 +46,20 @@ Signatures show resolved return values after await. ActionResult = { dispatched: Setup and discovery: - cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. -- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search for applications that match the query. Searches /Applications, /System/Applications, and ~/Applications. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. -- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- cua.getApp(selector: string) -> App — select an application using a provider-supported selector and obtain consent. When app-level accessibility is available, selection reads the initial tree silently. Accepts a name, bundle ID, .app path, or running PID string. A stopped app launches in the background. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds. A null onCurrentSpace means desktop membership is unknown. +- app.getWindow(windowId: number) -> Window — select one window and silently read its initial accessibility tree. Select a window before screenshots or pointer input. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. -- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. -- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the application be shown. Unhides the app and restores its focused, main, or sole window without activating it. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — request that the selected window be shown. Unhides the app and restores this window without activating it. ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so use IDs from the most recent observation. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text. includeMenus requests menu contents and details requests additional element information. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -69,17 +69,17 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — on macOS, prefer acting on an available control. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on the element or an enabled ancestor. Without an AX route it returns HOVER_UNAVAILABLE and sends no input. For browser content without those actions, use browser tools. Use click for a visible target or performAction for an advertised AXShowAlternateUI, AXShowMenu or AXPress. Only systemPointerHover: true permits moving the visible cursor; this requires a foreground, unobscured target. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — on macOS, send mouse-down and mouse-up events at the center of an element in this window (id) or at the given point ([x, y]). Prefer invoke(id) for a background control’s default action. When a mouse click is needed, call app.activate() first and observe the target again: a background app can ignore a dispatched click. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request hover at an observed element or window point. Inspect hoverRoute and systemPointerMoved to see how the provider dispatched it. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an observed element or a window point. Set clickCount to 2 to perform a left-button double-click. holdMs controls each press duration. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. -A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. For hover-only content, prefer an available click or advertised accessibility action. With system-pointer hover enabled, FOREGROUND_REQUIRED means activate the app explicitly and check that the point is unobscured. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current window observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. ## Simulated keyboard Available at app or window level depending on the platform. -- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. -- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- typeText(text: string) -> ActionResult — type text at the current input focus. Line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — paste text or HTML at the current input focus. Uses the app’s Paste command and restores the clipboard unless another writer changes it. For PASTE_NOT_CONSUMED, inspect the target before retrying. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From 0f15e8766abf883ba0566d876782aeb55b1885be Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 16:19:01 +0800 Subject: [PATCH 040/103] Refresh the configuration catalog and retain Agent disposal coverage --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- .../cua-macos/tests/provider-lifecycle.spec.ts | 12 ++++++++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index e6fafb2ae4..230dcfd070 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1112,7 +1112,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 7aa0c7245c..663c726c2a 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1114,7 +1114,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:32`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 017a605ce1..48b9eb99e3 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -387,6 +387,18 @@ it('rejects malformed and unowned operations before acquiring a helper', async ( expect(native.request).not.toHaveBeenCalled() }) +it.each([false, true])('rejects an ended Agent with prior helper acquisition %s', async (acquired) => { + const f = await setup() + if (acquired) await f.execute() + await f.handle.dispose() + const requests = native.request.mock.calls.length + const result = await f.execute() + expect(result.isError).toBe(true) + expect(JSON.stringify(result.content)).toContain('agent has been disposed') + expect(native.instances).toHaveLength(acquired ? 1 : 0) + expect(native.request).toHaveBeenCalledTimes(requests) +}) + it('supplies configured resource bounds and clears registrations on unload', async () => { const f = await setup() await selectApplication(f) From 5e7532f8fafe6b6685b04babf2d6ad85d9a449b1 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 16:21:51 +0800 Subject: [PATCH 041/103] Verify macOS hover permission stays with its connection --- .../cua-hover-ax-only/guide.i18n.yaml | 4 ++-- .../v0.2.2-rc.1/cua-hover-ax-only/guide.md | 2 +- .../v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md | 2 +- .../native/Sources/CuaNative/AXHover.swift | 5 +++-- .../native/Sources/CuaNative/AXWorker.swift | 4 +--- .../native/tests/swift/SystemHoverTests.swift | 19 +++++++++++-------- 6 files changed, 19 insertions(+), 17 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml index 69471af235..9a48f7428c 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.i18n.yaml @@ -12,5 +12,5 @@ en: 55c3070b24b4ad39 zh: 2555d127b0f4e4a0 /macos-hover-keeps-the-system-pointer-in-place-by-default/migration: - en: bfa15519fd2afb89 - zh: b350e3a7aa2aaa7a + en: 1f0ab7e8741e821f + zh: f59adc3a23ebcb43 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md index fdd3d811eb..f7191cc254 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.md @@ -14,5 +14,5 @@ On macOS, `win.mouseMove(target)` uses an enabled element or ancestor that adver ## Migration 1. For an available control, use its advertised action or click it directly. Use browser tools for web content that requires page hover. -2. To restore visible pointer movement, set `systemPointerHover: true` in the `config` of the macOS provider entry (`id: cua`) in your profile's `cordis.patch.yml`. Preserve the entry's other settings. Restart the profile. +2. To restore visible pointer movement, set `systemPointerHover: true` in the `config` of the macOS provider entry (`id: cua`) in your profile's `cordis.patch.yml`. Preserve the entry's other settings. If you set `helperPath`, rebuild the custom helper so it accepts `systemPointerHover` in the connection handshake. Restart the profile. 3. Call `win.mouseMove` on a foreground, unobscured control without AX alternate UI. The opt-in result reports `hoverRoute: "system-pointer"` and `systemPointerMoved: true`. Keep the default to avoid disturbing the user's cursor. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md index 7202988db2..713ae43fb3 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-hover-ax-only/guide.zh.md @@ -14,5 +14,5 @@ description: "macOS 的 mouseMove 默认要求控件支持 AX 备用界面,否 ## 迁移 1. 对已经可用的控件,可执行它声明的动作或直接点击。需要网页悬停时可用浏览器工具。 -2. 要恢复可见光标移动,在 profile 的 `cordis.patch.yml` 中,给 macOS 提供方条目(`id: cua`)的 `config` 添加 `systemPointerHover: true`。保留该条目的其他设置,重启 profile。 +2. 要恢复可见光标移动,在 profile 的 `cordis.patch.yml` 中,给 macOS 提供方条目(`id: cua`)的 `config` 添加 `systemPointerHover: true`。保留该条目的其他设置。如果指定了 `helperPath`,先重新构建自定义 helper,使其在建立连接时能读取 `systemPointerHover`,然后重启 profile。 3. 对前台未受遮挡且不提供 AX 备用界面的控件调用 `win.mouseMove`。启用配置时,结果为 `hoverRoute: "system-pointer"` 和 `systemPointerMoved: true`。要保留用户的光标位置,使用默认配置。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift index ecab67f6d7..17b142d113 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXHover.swift @@ -2,8 +2,9 @@ import ApplicationServices final class AXHover { - static func requireSystemPointer(allowed: Bool) throws { - guard allowed else { + /// Only diagnostic clients without a connection policy may opt in per request. + static func requireSystemPointer(connectionSetting: Bool?, requestSetting: Bool?) throws { + guard connectionSetting ?? requestSetting ?? false else { throw NativeFailure(code: "HOVER_UNAVAILABLE", message: "No enabled element at this target or in its ancestors offers both AXShowAlternateUI and AXShowDefaultUI. System-pointer hover is disabled; this provider has no other pointer-free hover route. No input was sent and the pointer did not move. Use click on an available control or performAction with an action from listActions.") } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 96a6054525..c4cc6066c8 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -108,12 +108,10 @@ actor AXWorker { } private func moveUsingAX(_ element: AXUIElement?, windowID: UInt32, handle: String, params: RequestParameters) throws -> Bool { let requestSetting = try params.optionalBoolean("allowSystemPointer") - // Diagnostic JSONL clients without a deployment setting may opt in per request. - let allowSystemPointer = systemPointerHover ?? requestSetting ?? false let hover = hovers[handle] ?? AXHover() hovers[handle] = hover if try hover.move(to: element, in: windowID, access: ax()) { return true } - try AXHover.requireSystemPointer(allowed: allowSystemPointer) + try AXHover.requireSystemPointer(connectionSetting: systemPointerHover, requestSetting: requestSetting) return false } private func inputs() -> (KeyboardInput, WindowPointerInput) { diff --git a/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift b/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift index 8bb26dfdb9..df48871c4c 100644 --- a/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/SystemHoverTests.swift @@ -3,15 +3,18 @@ import Testing import CoreGraphics @testable import CuaNative -@Test func unavailableAXHoverRequiresExplicitSystemPointerPermission() throws { - do { - try AXHover.requireSystemPointer(allowed: false) - Issue.record("A default hover without an AX route was allowed to move the pointer") - } catch let failure as NativeFailure { - #expect(failure.code == "HOVER_UNAVAILABLE") - #expect(failure.message.contains("No input was sent")) +@Test func unavailableAXHoverHonorsConnectionPolicyBeforeRequestFlags() throws { + for (connection, request): (Bool?, Bool?) in [(nil, nil), (nil, false), (false, nil), (false, true)] { + do { + try AXHover.requireSystemPointer(connectionSetting: connection, requestSetting: request) + Issue.record("An unapproved request was allowed to move the pointer") + } catch let failure as NativeFailure { + #expect(failure.code == "HOVER_UNAVAILABLE") + #expect(failure.message.contains("No input was sent")) + } } - try AXHover.requireSystemPointer(allowed: true) + try AXHover.requireSystemPointer(connectionSetting: true, requestSetting: nil) + try AXHover.requireSystemPointer(connectionSetting: nil, requestSetting: true) } @Test func systemHoverRequiresTheForegroundUnobscuredTarget() throws { From 4736af3b0066b0f1eb9cc2cdba994d84d34b3a56 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 16:22:06 +0800 Subject: [PATCH 042/103] test(ui-goal): drop unnecessary button cast Co-authored-by: Yifffan <133629972+Yifffan@users.noreply.github.com> --- packages/client/ui-goal/tests/goalbar.client.spec.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/ui-goal/tests/goalbar.client.spec.tsx b/packages/client/ui-goal/tests/goalbar.client.spec.tsx index 0016781fbb..aa86379524 100644 --- a/packages/client/ui-goal/tests/goalbar.client.spec.tsx +++ b/packages/client/ui-goal/tests/goalbar.client.spec.tsx @@ -158,7 +158,7 @@ describe('GoalBar', () => { const actions = makeActions() render() expect(screen.getAllByRole('button').map(b => b.getAttribute('aria-label'))).toEqual(['编辑目标', '清除目标', '暂停目标']) - expect((screen.getByRole('button', { name: '暂停目标' }) as HTMLButtonElement).disabled).toBe(true) + expect(screen.getByRole('button', { name: '暂停目标' }).hasAttribute('disabled')).toBe(true) }) it('active disarmed goal: "待继续的目标" with a resume action instead of pause', () => { From 334a76ef8845b737bd3f79fee30d64b364f06b23 Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 14:46:37 +0800 Subject: [PATCH 043/103] fix(settings): show masked saved keys and restore environment auth --- .../tests/deepseek-messages-settings.e2e.ts | 125 ++++++++++++++++- .../cards.expected.md | 4 +- .../clear-key.expected.md | 26 ++++ .../default-models.expected.md | 4 +- .../models.expected.md | 4 +- apps/web/tests/models-settings.e2e.ts | 2 +- .../tests/onboarding-deepseek-config.e2e.ts | 7 +- docs/event-producer-consumer.md | 4 +- docs/event-producer-consumer.zh.md | 4 +- docs/subsystems/credentials.i18n.yaml | 4 +- docs/subsystems/credentials.md | 8 +- docs/subsystems/credentials.zh.md | 8 +- docs/user/guide/providers.i18n.yaml | 4 +- docs/user/guide/providers.md | 4 +- docs/user/guide/providers.zh.md | 4 +- .../settings-controller/src/credentials.ts | 1 + .../tests/credentials-controller.host.spec.ts | 19 +++ .../ui-settings-models/README.i18n.yaml | 8 +- packages/client/ui-settings-models/README.md | 6 +- .../client/ui-settings-models/README.zh.md | 6 +- .../src/client/ProviderEditor.tsx | 67 ++++++--- .../ui-settings-models/src/client/locales.ts | 56 ++++++-- .../tests/components.client.spec.tsx | 131 +++++++++++++++++- .../credentials-local/README.i18n.yaml | 4 +- .../credentials/credentials-local/README.md | 4 +- .../credentials-local/README.zh.md | 4 +- .../credentials-local/src/index.ts | 5 +- .../credentials-local/tests/local.spec.ts | 29 +++- .../credentials/credentials/README.i18n.yaml | 4 +- packages/credentials/credentials/README.md | 4 +- packages/credentials/credentials/README.zh.md | 4 +- packages/credentials/credentials/src/types.ts | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- 33 files changed, 484 insertions(+), 88 deletions(-) create mode 100644 apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 6033c8f06f..95aaf1df40 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -1,9 +1,14 @@ -/** Web DeepSeek configuration, credential reuse, and saved model selection. */ +/** Web provider credentials, environment fallback, and DeepSeek model selection. */ import { readFile } from 'node:fs/promises' +import { once } from 'node:events' +import { createServer } from 'node:http' import { join } from 'node:path' import { fileURLToPath } from 'node:url' import { chromium, webkit, type Browser, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { BlockAssembler, createUserMessage, type StreamChunk } from '@deepseek-ai/dsh-llm' +import { credentialRef } from '@deepseek-ai/dsh-credentials' +import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold, @@ -12,6 +17,109 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url)) +it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'clear-fixture'])( + 'clears the saved %s key and sends the next request with environment authentication', async (provider) => { + const messages = provider === 'deepseek-official' + const google = provider === 'google' + const ref = credentialRef(messages ? 'DEEPSEEK_API_KEY' : `${provider.toUpperCase().replaceAll('-', '_')}_API_KEY`) + const envRef = google ? 'GEMINI_API_KEY' : ref + const calls: { path: string; key: string | undefined }[] = [] + const server = createServer((request, response) => { + request.on('end', () => { + const key = request.headers[messages ? 'x-api-key' : google ? 'x-goog-api-key' : 'authorization'] + calls.push({ path: request.url ?? '', key: typeof key === 'string' ? key : undefined }) + const events = messages ? [ + { type: 'message_start', message: { id: 'clear', type: 'message', role: 'assistant', model: 'clear-model', content: [], usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, + { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'connection-ok' } }, + { type: 'content_block_stop', index: 0 }, + { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 1 } }, + { type: 'message_stop' }, + ] : google ? [{ candidates: [{ content: { role: 'model', parts: [{ text: 'connection-ok' }] }, finishReason: 'STOP' }] }] + : [{ id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: { content: 'connection-ok' }, finish_reason: null }] }, + { id: 'clear', object: 'chat.completion.chunk', choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] }] + response.writeHead(200, { 'content-type': 'text/event-stream' }) + response.end(events.map(event => `data: ${JSON.stringify(event)}\n\n`).join('')) + }) + request.resume() + }) + server.listen(0, '127.0.0.1') + await once(server, 'listening') + let scaffold: WebScaffold | undefined + let browser: Browser | undefined + try { + const address = server.address() + if (address === null || typeof address === 'string') throw new Error('Missing credential test listener') + const baseURL = `http://127.0.0.1:${String(address.port)}/configured` + scaffold = await launchWebScaffold({ + deepSeekMissingCredential: true, + openInAppEnvironment: createLaunchEnvironmentSnapshot([{ source: 'process', values: { [envRef]: 'fixture-environment-key' } }]), + }) + const profile = { apiKeyEnv: ref, baseURL, models: [{ id: 'clear-model' }], + ...messages || google ? {} : { api: 'openai-completions' } } + await scaffold.ctx.settings.mutate(messages ? 'llm-deepseek' : 'llm-pi-ai', [{ + op: 'set', path: messages ? [] : ['providers', provider], value: profile, + }]) + await scaffold.ctx.credentials.set(ref, 'fixture-saved-key') + const runtime = scaffold.ctx + const generate = async (): Promise => { + const assembler = new BlockAssembler() + const chunks: StreamChunk[] = [] + for await (const chunk of runtime.llm.stream({ provider, model: 'clear-model', + messages: [createUserMessage({ content: [{ type: 'text', text: 'Reply connection-ok' }], source: { kind: 'user' } })] })) { + chunks.push(chunk) + assembler.push(chunk) + } + expect(assembler.message({ provider, model: 'clear-model' }).content, JSON.stringify(chunks)) + .toContainEqual({ type: 'text', text: 'connection-ok' }) + } + await generate() + browser = await chromium.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click() + expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) + await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'), + await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) + await dialog.getByRole('button', { name: '取消', exact: true }).click() + expect((await runtime.credentials.resolve(ref))?.source).toBe('file') + await edit.click() + await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click() + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await generate() + expect(calls).toHaveLength(2) + expect(calls[0]?.key).toBe(messages || google ? 'fixture-saved-key' : 'Bearer fixture-saved-key') + expect(calls[1]).toEqual({ path: calls[0]?.path, + key: messages || google ? 'fixture-environment-key' : 'Bearer fixture-environment-key' }) + expect(calls[1]?.path).toContain('/configured/') + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).not.toContain('fixture-saved-key') + await edit.click() + await dialog.getByText(`已检测到环境变量(${envRef})`, { exact: true }).waitFor() + await dialog.getByText('自定义设置', { exact: true }).click() + expect(await dialog.getByLabel('API 地址', { exact: true }).inputValue()).toBe(baseURL) + expect(await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).count()).toBe(0) + } finally { + try { await browser?.close() } finally { + try { await scaffold?.close() } finally { + await new Promise((resolve, reject) => server.close((error) => { + if (error === undefined) resolve() + else reject(error) + })) + } + } + } + }, +) + it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( 'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => { const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) @@ -90,6 +198,10 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(await dialog.getByText('DeepSeek', { exact: true }).count()).toBe(1) await dialog.getByText('DeepSeek', { exact: true }).locator('xpath=ancestor::li').getByRole('button', { name: '编辑' }).click() const messages = dialog + const key = messages.getByLabel('API 密钥', { exact: true }) + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('placeholder')).toBe('留空保留现有认证(已保存 API key)') + await messages.getByText('已保存 API key:sk-m…ding', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') @@ -114,6 +226,17 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(credentials).toContain('DEEPSEEK_API_KEY: sk-e2e-messages') expect(credentials).not.toContain('DEEPSEEK_MESSAGES_API_KEY') expect(await page.locator('body').innerText()).not.toContain('sk-e2e-') + await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click() + expect(await key.inputValue()).toBe('') + await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor() + expect(await key.getAttribute('type')).toBe('password') + await key.fill('sk-cancelled-replacement') + expect(await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).count()).toBe(0) + await key.fill('') + await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor() + await messages.getByRole('button', { name: '保存', exact: true }).click() + await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor() + expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) await page.keyboard.press('Escape') await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e') await page.getByRole('button', { name: /^选择模型/ }).click() diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 93993bbe04..b069459b00 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -16,8 +16,10 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" + - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: 留空保留现有认证(已保存 API key) + - paragraph: 已保存 API key:sk-m…ding - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md new file mode 100644 index 0000000000..2882ca8a34 --- /dev/null +++ b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md @@ -0,0 +1,26 @@ +- dialog "设置": + - text: 设置 + - navigation: + - button "通用设置" + - button "模型" + - button "内置插件" + - button "Agent 预设" + - button "打开配置文件" + - button "关闭" + - heading "模型" [level=2] + - paragraph: 填入各提供商的 API 密钥即可使用其模型。 + - list: + - listitem: + - text: DeepSeek + - img "API 密钥已配置" + - button "编辑 DeepSeek (deepseek-official)": 编辑 + - text: DeepSeek deepseek-official API 密钥 + - button "认证说明": "?" + - button "撤销清除" + - textbox "API 密钥": + - /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY) + - paragraph: 保存后清除已保存密钥,并使用环境认证 + - group: 自定义设置 + - button "取消" + - button "保存" + - button "添加模型提供商" diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index a7be30e8c3..3831507855 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -16,8 +16,10 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" + - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: 留空保留现有认证(已保存 API key) + - paragraph: 已保存 API key:dsh_…test - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index b369a619b4..3b99eb9c63 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -16,8 +16,10 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" + - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空使用已保存凭据 + - /placeholder: 留空保留现有认证(已保存 API key) + - paragraph: 已保存 API key:dsh_…test - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 950076a427..60b82d06cb 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() - await dialog.getByPlaceholder('留空使用已保存凭据', { exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByPlaceholder('留空保留现有认证(已保存 API key)', { exact: true }).waitFor({ timeout: 10_000 }) expect(await dialog.textContent()).not.toContain('API 密钥来源:') expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index 8706a7a4de..cb8d12bf9b 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -86,7 +86,8 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE) - const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}` + // Keep the displayed prefix and suffix stable while the credential remains unique. + const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test` await keyInput.fill(secret) await credentialStep.getByRole('button', { name: '保存并继续' }).click() await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) @@ -115,7 +116,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe('留空保留现有认证(已保存 API key)') const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -257,7 +258,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空使用已保存凭据') + ).toBe('留空保留现有认证(已保存 API key)') const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..f309851827 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -40,8 +40,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..2924a21051 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -42,8 +42,8 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index bad9827407..551fc5c9bf 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -12,8 +12,8 @@ en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: f7b09588c0f34952 - zh: 1b93d673c5bf6a80 + en: 5150dd250ea3a4b2 + zh: 944d0fffca37dec5 /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..47143f32da 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -32,19 +32,21 @@ interface ResolvedCredential { ## Description -`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. +`describe(ref)` reports whether a reference resolves, its source, writability, and an optional masked preview of a managed credential. It never returns the full value or an ambient credential preview. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * never the full value. Providers may include a masked preview of a managed + * credential; ambient credentials do not expose a preview. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string + /** Masked managed value for display only; short values must be fully masked. */ + preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..727d2a09c2 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -32,19 +32,21 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 +`describe(ref)` 报告引用是否可解析、来源、可写性,以及可选的托管凭据脱敏摘要。它不返回完整值,也不提供环境凭据摘要。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * never the full value. Providers may include a masked preview of a managed + * credential; ambient credentials do not expose a preview. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string + /** Masked managed value for display only; short values must be fully masked. */ + preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 899572eab5..2ee34aa5c0 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: f6fb44a85dc5e4dd - zh: 2b86ea4492c32ed7 + en: 2bfca1d989fce463 + zh: f86948426dad32b0 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 90b70e0696..7e08db5dbc 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,9 +20,9 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential uses the placeholder **Leave blank to use saved credentials**, with no status text below the input. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential uses the placeholder **Leave blank to keep current authentication (API key saved)** and a green masked-key preview below the empty input. Select **Clear saved key**, then **Save**, to remove the stored override and use environment authentication. **Undo clear** or **Cancel** preserves the key. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. -A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Stored credentials remain write-only. +A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. ## Add a custom model API diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index c580fd2ab0..7b93565776 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,9 +20,9 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据使用**留空使用已保存凭据**占位文字,输入框下方不显示状态文字。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据使用**留空保留现有认证(已保存 API key)**占位文字,在空输入框下方显示绿色的密钥脱敏摘要。选择**清除已保存密钥**,再点**保存**,即可移除存储覆盖并使用环境认证。**撤销清除**或**取消**会保留密钥。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 -密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。已保存凭据仍保持只写。 +密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 ## 添加自定义模型 API diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 3889669048..225dbcd6d0 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -46,6 +46,7 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo { return { configured: info.configured, ...info.source === undefined ? {} : { source: info.source }, + ...info.preview === undefined ? {} : { preview: info.preview }, writable: info.writable, } } diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 5eeb190385..d1019cab01 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -14,6 +14,16 @@ class LeakyCredentials extends MemoryCredentials { } } +/** A managed provider returning a display preview alongside an undeclared secret. */ +class PreviewCredentials extends MemoryCredentials { + override describe(): Promise { + return Promise.resolve({ + configured: true, source: 'file', writable: true, + preview: 'sk-m…abcd', value: 'sk-managed-secret-abcd', + } as CredentialInfo) + } +} + /** A store whose write rejects with a bare string, the way some client libraries do. */ class LiteralRejectingCredentials extends MemoryCredentials { override async set(): Promise { @@ -105,6 +115,15 @@ describe('the credentials Remote namespace a configuration surface calls', () => expect(JSON.stringify(described)).not.toContain('sk-leaked') }) + it('returns the masked preview without the original stored credential', async () => { + const controller = await boot({}, PreviewCredentials) + const described = await controller.describe(['DEEPSEEK_API_KEY']) + expect(described.DEEPSEEK_API_KEY).toEqual({ + configured: true, source: 'file', writable: true, preview: 'sk-m…abcd', + }) + expect(JSON.stringify(described)).not.toContain('sk-managed-secret-abcd') + }) + it('stores and removes through the same references the batch describes', async () => { const controller = await boot() await controller.set('DEEPSEEK_API_KEY', 'sk-live') diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 74ecbbb6d5..d8277713b1 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: f4817eb2e3537ed9 - zh: e589c193fa85473f + en: c4865eabb48e3839 + zh: 66f5c6698845112f /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: a0501172f15c3286 - zh: 6dfa112f215b2d3d + en: 19fbfafb53ea1593 + zh: 880f6703111383fd /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 5039f7988d..89bbf726d4 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,15 +41,15 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. +API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. -The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint never receives a credential value or changes field writability. +The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint receives only a Host-masked preview of a saved key and never changes field writability. ### Editing a provider -A blank key field offers a saved credential when one is detected, with no status text below the input; otherwise it offers environment authentication. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +A blank key field preserves existing authentication. A saved credential shows a green notice with its masked preview below the input; providers without a preview show only that a key is saved. Otherwise the field offers environment authentication. **Clear saved key** stages removal until Save; Undo or Cancel preserves the key. Entering a new key replaces the removal draft. A catalog route drops its user-layer derived reference to restore native authentication; explicit aliases, inherited references, and custom routes retain their reference for environment fallback. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index a6a1595bda..4d2527b402 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,15 +41,15 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。 +API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 -编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示从不接收凭据值,也不改变字段的可写性。 +编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示只接收 Host 生成的已保存密钥脱敏摘要,不改变字段的可写性。 ### 编辑提供商 -密钥字段留空时,已检测到已保存凭据则提示使用该凭据,输入框下方不显示状态文字;否则提示使用环境认证。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +密钥字段留空时保留现有认证。已保存凭据在输入框下方显示绿色提示及脱敏摘要;提供方未提供摘要时,只提示已保存密钥。否则提示使用环境认证。**清除已保存密钥**将删除操作暂存到「保存」时执行;撤销或取消会保留密钥。输入新密钥会替换待删除草稿。目录路由会移除用户层中的派生引用以恢复原生认证;显式别名、继承引用和自定义路由保留原引用以使用环境后备。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index d5e7e528df..d7ee7baf99 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -199,7 +199,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const { mode } = retryPolicyDefaults(schema, node, schema.getPath(namespace.base, path)) return { ...loaded, retryPolicy: { ...policy, mode } } }) - const [keyDraft, setKeyDraft] = useState('') + // An empty string preserves authentication; a reference stages its removal. + const [keyDraft, setKeyDraft] = useState('') + const keyText = typeof keyDraft === 'string' ? keyDraft : '' + const keyRemoval = typeof keyDraft === 'string' ? undefined : keyDraft const [busy, setBusy] = useState(false) const [listBusy, setListBusy] = useState(false) const { onBusyChange } = props @@ -242,6 +245,8 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { ? schema.deletePath(current, [key]) : schema.setPath(current, [key], value)) } + const clearsDerivedRef = keyRemoval !== undefined && layout === 'pi-ai' + && props.nativeAuth !== undefined && stringAt(draft, 'apiKeyEnv') === deriveKeyRef(props.provider) // The model list is validated by the same per-row checker for both families, // so a bad row is named by its position rather than by a blanket message. @@ -274,18 +279,18 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const retryFailure = retryNode === undefined || retryDefaults === undefined || props.credentialOnly === true ? undefined : retryPolicyFailure(schema, retryNode, schema.getPath(draft, ['retryPolicy']), retryDefaults, t) - const keyFailure = apiKeyFailure(keyDraft) + const keyFailure = apiKeyFailure(keyText) // What a probe or a write must carry: the typed key with paste whitespace // removed. A blank field yields an empty string, which both call sites read // as "no key supplied" rather than as a key — that is how a card whose // provider already has a stored key is edited without re-entering it. - const keyValue = keyDraft.trim() + const keyValue = keyText.trim() // A route whose protocol cannot authenticate without a key needs a key reference or a typed key. const protocolNeedsKeyHere = layout === 'pi-ai' && protocolNeedsKey(probeApi) && stringAt(draft, 'apiKeyEnv') === undefined && stringAt(fallback, 'apiKeyEnv') === undefined const protocolKeyMissing = protocolNeedsKeyHere && keyValue.length === 0 const credentialRequiredFailure = (props.credentialRequired === true - && keyDraft.length > 0 && keyValue.length === 0) || protocolKeyMissing + && keyText.length > 0 && keyValue.length === 0) || protocolKeyMissing ? 'keyRequired' as const : undefined const shownKeyFailure = credentialRequiredFailure ?? keyFailure @@ -308,12 +313,16 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { */ const applyOnce = async (): Promise => { const ns = namespace.ns + // A catalog provider returns to native authentication when this page's + // derived reference is removed. Explicit aliases and custom routes keep + // their reference so its environment fallback remains addressable. + const profileDraft = clearsDerivedRef ? schema.deletePath(draft, ['apiKeyEnv']) : draft // A pi-ai profile names the conventional reference only when this page is // about to store a key. Otherwise the provider keeps its native auth path. - const next = layout === 'pi-ai' && stringAt(draft, 'apiKeyEnv') === undefined - && stringAt(fallback, 'apiKeyEnv') === undefined && keyValue.length > 0 - ? schema.setPath(draft, ['apiKeyEnv'], keyRef) - : draft + const next = layout === 'pi-ai' && stringAt(profileDraft, 'apiKeyEnv') === undefined + && stringAt(schema.getPath(namespace.base, settingsPath), 'apiKeyEnv') === undefined && keyValue.length > 0 + ? schema.setPath(profileDraft, ['apiKeyEnv'], keyRef) + : profileDraft if (props.credentialOnly !== true) { // The same checker gates the submit button, so a card cannot reach this // with a bad row; it stays because the schema check below would refuse @@ -346,7 +355,10 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { setExpectedRevision(written.view.revision) setDraft(next) } - if (keyValue.length > 0) { + if (keyRemoval !== undefined) { + const removed = await operations.removeCredential(keyRemoval.ref) + if (removed !== undefined) return removed + } else if (keyValue.length > 0) { const stored = await operations.storeCredential(keyRef, keyValue) if (stored !== undefined) return stored } @@ -410,7 +422,9 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { // A named reference is the only credential the adapter reads for this // route. Without one, a catalog route authenticates the way the directory // reports, and a declared route sends no key at all. - const namedRef = stringAt(fallback, 'apiKeyEnv') + const namedRef = clearsDerivedRef + ? stringAt(schema.getPath(namespace.base, settingsPath), 'apiKeyEnv') + : stringAt(fallback, 'apiKeyEnv') const nativeAuth = namedRef === undefined ? props.nativeAuth : undefined // Display method-neutral references without changing the adapter's lookup. const authRefs = namedRef === undefined @@ -424,12 +438,18 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const detectedRef = detected?.[0] const detectedVisibleRef = detectedRef === undefined || !visibleRefs.includes(detectedRef) ? undefined : detectedRef const missingRefs = checkedRefs.length > 0 && checkedRefs.every(([, info]) => info?.configured === false) - const savedCredential = detected?.[1]?.source === 'file' - const credentialHint = keyDraft.length > 0 || savedCredential || keyHint === undefined || props.credentialRequired === true + const savedPreview = detected?.[1]?.preview + const savedCredential = detected?.[1]?.source === 'file' || savedPreview !== undefined + const removalRef = keyRemoval?.ref ?? detectedRef + const credentialHint = keyText.length > 0 || props.credentialRequired === true ? undefined - : t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked' - : detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected') - .replace('{hint}', () => detectedVisibleRef ?? keyHint) + : keyRemoval !== undefined ? t('keyRemovePending') + : keyHint === undefined ? undefined + : savedCredential + ? savedPreview === undefined ? t('keySaved') : t('keySavedPreview').replace('{preview}', () => savedPreview) + : t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked' + : detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected') + .replace('{hint}', () => detectedVisibleRef ?? keyHint) const keyHelp = visibleRefs.length === 0 ? undefined : t('keyHelp').replace('{env}', () => visibleRefs.join(' / ')) @@ -442,7 +462,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const keylessNativeAuth = nativeAuth?.env.length === 0 && nativeAuth.oauth const keyPlaceholder = keyHint === undefined || props.credentialRequired === true ? t('keyPlaceholder') - : t(savedCredential ? 'keyPlaceholderSaved' : 'keyPlaceholderFallback').replace('{hint}', () => keyHint) + : t(keyRemoval === undefined && savedCredential ? 'keyPlaceholderSaved' : 'keyPlaceholderFallback').replace('{hint}', () => keyHint) /** What both family editors take: the rows, whose layer owns them, and the two writes. */ const catalogProps = { models, @@ -462,10 +482,19 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { {t('keyInput')} {authHelp} + {keyText.length === 0 && props.credentialRequired !== true && removalRef !== undefined + && (keyRemoval !== undefined || (savedCredential && detected?.[1]?.writable === true)) + ? + : null} { setKeyDraft(event.target.value) }} /> - {credentialHint === undefined ? null :

{credentialHint}

} + {credentialHint === undefined ? null :

{credentialHint}

} {/* A key the protocol requires is a requirement still to meet, not a fault. */} {shownKeyFailure === undefined ? null @@ -597,7 +626,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { reasoningLevelsOnly={reasoning.levelsOnly} defaultInput={Array.isArray(defaultInput) ? defaultInput : undefined} probe={probe} - probeBlocked={shownKeyFailure} + probeBlocked={keyRemoval !== undefined ? 'keyRemovePending' : shownKeyFailure} operations={operations} onBusyChange={setListBusy} /> diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index ae9d4f71a4..0a359c223c 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -41,7 +41,12 @@ export const en = { keyHide: 'Hide secret', keyPlaceholder: 'Enter your API key', keyPlaceholderFallback: 'Leave blank to use env as auth ({hint})', - keyPlaceholderSaved: 'Leave blank to use saved credentials', + keyPlaceholderSaved: 'Leave blank to keep current authentication (API key saved)', + keySaved: 'API key saved', + keySavedPreview: 'API key saved: {preview}', + keyRemove: 'Clear saved key', + keyRemoveUndo: 'Undo clear', + keyRemovePending: 'Save to clear the saved key and use environment authentication.', keyFallbackMissing: 'Env var not detected. Enter an API key, or configure {hint} in your env.', keyFallbackDetected: 'Env var detected. ({hint})', keyFallbackDetectedHidden: 'Env var detected.', @@ -217,7 +222,12 @@ export const zh: { [Key in keyof typeof en]: string } = { keyHide: '隐藏密钥', keyPlaceholder: '输入 API 密钥', keyPlaceholderFallback: '留空使用环境认证({hint})', - keyPlaceholderSaved: '留空使用已保存凭据', + keyPlaceholderSaved: '留空保留现有认证(已保存 API key)', + keySaved: '已保存 API key', + keySavedPreview: '已保存 API key:{preview}', + keyRemove: '清除已保存密钥', + keyRemoveUndo: '撤销清除', + keyRemovePending: '保存后清除已保存密钥,并使用环境认证', keyFallbackMissing: '未检测到环境变量。请填写 API 密钥,或设置环境变量 {hint}。', keyFallbackDetected: '已检测到环境变量({hint})', keyFallbackDetectedHidden: '已检测到环境变量', @@ -390,7 +400,12 @@ export const ja = { 'keyHide': 'シークレットを非表示', 'keyPlaceholder': 'APIキーを入力', 'keyPlaceholderFallback': '空欄のままにすると環境変数を認証に使用します ({hint})', - 'keyPlaceholderSaved': '空欄のままにすると保存済みの認証情報を使用します', + 'keyPlaceholderSaved': '空欄のままにすると現在の認証を保持します(APIキー保存済み)', + keySaved: 'APIキー保存済み', + keySavedPreview: 'APIキー保存済み: {preview}', + keyRemove: '保存済みキーを削除', + keyRemoveUndo: '削除を取り消す', + keyRemovePending: '保存すると保存済みキーを削除し、環境変数の認証を使用します。', 'keyFallbackMissing': '環境変数が検出されません。APIキーを入力するか、環境変数に{hint}を設定してください。', 'keyFallbackDetected': '環境変数を検出しました。({hint})', 'keyFallbackDetectedHidden': '環境変数を検出しました。', @@ -563,7 +578,12 @@ export const es = { keyHide: 'Ocultar secreto', keyPlaceholder: 'Ingrese su clave API', keyPlaceholderFallback: 'Déjelo en blanco para usar env como autenticación ({hint})', - keyPlaceholderSaved: 'Déjelo en blanco para usar las credenciales guardadas', + keyPlaceholderSaved: 'Déjelo en blanco para conservar la autenticación actual (clave API guardada)', + keySaved: 'Clave API guardada', + keySavedPreview: 'Clave API guardada: {preview}', + keyRemove: 'Borrar clave guardada', + keyRemoveUndo: 'Deshacer borrado', + keyRemovePending: 'Guarde para borrar la clave guardada y usar la autenticación del entorno.', keyFallbackMissing: 'No se detectó la variable de entorno. Ingrese una clave API o configure {hint} en su entorno.', keyFallbackDetected: 'Se detectó var env. ({hint})', keyFallbackDetectedHidden: 'Se detectó var env.', @@ -736,7 +756,12 @@ export const fr = { keyHide: 'Cacher le secret', keyPlaceholder: 'Entrez votre clé API', keyPlaceholderFallback: 'Laissez vide pour utiliser env comme authentification ({hint})', - keyPlaceholderSaved: "Laissez vide pour utiliser les informations d'identification enregistrées", + keyPlaceholderSaved: 'Laissez vide pour conserver l’authentification actuelle (clé API enregistrée)', + keySaved: 'Clé API enregistrée', + keySavedPreview: 'Clé API enregistrée : {preview}', + keyRemove: 'Effacer la clé enregistrée', + keyRemoveUndo: 'Annuler l’effacement', + keyRemovePending: 'Enregistrez pour effacer la clé enregistrée et utiliser l’authentification de l’environnement.', keyFallbackMissing: "Var d'environnement non détectée. Entrez une clé API ou configurez {hint} dans votre environnement.", keyFallbackDetected: "Var d'environnement détectée. ({hint})", keyFallbackDetectedHidden: "Var d'environnement détectée.", @@ -909,7 +934,12 @@ export const de = { keyHide: 'Geheimnis verbergen', keyPlaceholder: 'Geben Sie Ihren API-Schlüssel ein', keyPlaceholderFallback: 'Lassen Sie das Feld leer, um env als Authentifizierung zu verwenden ({hint})', - keyPlaceholderSaved: 'Lassen Sie das Feld leer, um gespeicherte Anmeldeinformationen zu verwenden', + keyPlaceholderSaved: 'Leer lassen, um die aktuelle Authentifizierung beizubehalten (API-Schlüssel gespeichert)', + keySaved: 'API-Schlüssel gespeichert', + keySavedPreview: 'API-Schlüssel gespeichert: {preview}', + keyRemove: 'Gespeicherten Schlüssel löschen', + keyRemoveUndo: 'Löschen rückgängig machen', + keyRemovePending: 'Speichern, um den gespeicherten Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.', keyFallbackMissing: 'Umgebungsvariable nicht erkannt. Geben Sie einen API-Schlüssel ein oder konfigurieren Sie {hint} in Ihrer Umgebung.', keyFallbackDetected: 'Umgebungsvariable erkannt. ({hint})', keyFallbackDetectedHidden: 'Umgebungsvariable erkannt.', @@ -1082,7 +1112,12 @@ export const ru = { keyHide: 'Скрыть секрет', keyPlaceholder: 'Введите свой ключ API', keyPlaceholderFallback: 'Оставьте пустым, чтобы использовать env в качестве аутентификации ({hint})', - keyPlaceholderSaved: 'Оставьте поле пустым, чтобы использовать сохраненные учетные данные.', + keyPlaceholderSaved: 'Оставьте поле пустым, чтобы сохранить текущую аутентификацию (API-ключ сохранён)', + keySaved: 'API-ключ сохранён', + keySavedPreview: 'API-ключ сохранён: {preview}', + keyRemove: 'Удалить сохранённый ключ', + keyRemoveUndo: 'Отменить удаление', + keyRemovePending: 'Сохраните, чтобы удалить сохранённый ключ и использовать аутентификацию из окружения.', keyFallbackMissing: 'Переменная Env не обнаружена. Введите ключ API или настройте {hint} в своей среде.', keyFallbackDetected: 'Обнаружена переменная Env. ({hint})', keyFallbackDetectedHidden: 'Обнаружена переменная Env.', @@ -1255,7 +1290,12 @@ export const pt = { keyHide: 'Ocultar segredo', keyPlaceholder: 'Insira sua chave API', keyPlaceholderFallback: 'Deixe em branco para usar env como autenticação ({hint})', - keyPlaceholderSaved: 'Deixe em branco para usar credenciais salvas', + keyPlaceholderSaved: 'Deixe em branco para manter a autenticação atual (chave API salva)', + keySaved: 'Chave API salva', + keySavedPreview: 'Chave API salva: {preview}', + keyRemove: 'Limpar chave salva', + keyRemoveUndo: 'Desfazer limpeza', + keyRemovePending: 'Salve para limpar a chave salva e usar a autenticação do ambiente.', keyFallbackMissing: 'Env var não detectado. Insira uma chave API ou configure {hint} em seu ambiente.', keyFallbackDetected: 'Variável de ambiente detectada. ({hint})', keyFallbackDetectedHidden: 'Variável de ambiente detectada.', diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index c23e423256..28cc89d192 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -2204,14 +2204,14 @@ describe('apiKeyFailure', () => { }) }) -it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows only the blank-input environment detection for source %s', (source) => { +it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing authentication with a blank input for source %s', (source) => { renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { credential: { configured: true, source, writable: true }, }) const hint = en.keyFallbackDetected.replace('{hint}', 'OPENAI_API_KEY') const input = screen.getByLabelText(en.keyInput) expect(screen.queryByText(/^API key source:/)).toBeNull() - if (source === 'file') expect(screen.queryByText(hint)).toBeNull() + if (source === 'file') expect(screen.getByText(en.keySaved)).toBeTruthy() else expect(screen.getAllByText(hint)).toHaveLength(1) expect(input.value).toBe('') expect(input.placeholder) @@ -2221,10 +2221,135 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows only the bla expect(screen.queryByText(/^API key source:/)).toBeNull() expect(input.getAttribute('aria-describedby')).toBeNull() fireEvent.change(input, { target: { value: '' } }) - if (source === 'file') expect(screen.queryByText(hint)).toBeNull() + if (source === 'file') expect(screen.getByText(en.keySaved)).toBeTruthy() else expect(screen.getAllByText(hint)).toHaveLength(1) }) +it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('shows only a saved-key preview for %s and preserves it when the draft is cleared', (provider) => { + const preview = 'sk-m…abcd' + const hint = en.keySavedPreview.replace('{preview}', preview) + renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: 'TEAM_API_KEY' }), { + credential: { configured: true, source: 'file', writable: true, preview }, + }) + const input = screen.getByLabelText(en.keyInput) + expect(input.value).toBe('') + expect(input.type).toBe('password') + expect(input.placeholder).toBe(en.keyPlaceholderSaved) + const notice = screen.getByText(hint) + expect(input.getAttribute('aria-describedby')).toBe(notice.id) + expect(screen.queryByLabelText(en.keyReveal)).toBeNull() + fireEvent.change(input, { target: { value: 'replacement-key' } }) + expect(screen.queryByText(hint)).toBeNull() + fireEvent.change(input, { target: { value: '' } }) + expect(screen.getByText(hint)).toBeTruthy() + expect(input.value).toBe('') +}) + +it('uses a managed preview from a credential provider with its own source label', () => { + renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { + credential: { configured: true, source: 'keychain', writable: true, preview: 'sk-m…abcd' }, + }) + expect(screen.getByText(en.keySavedPreview.replace('{preview}', 'sk-m…abcd'))).toBeTruthy() + expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved) + expect(screen.queryByText(/Env var detected/)).toBeNull() +}) + +it('stages key removal and lets Undo or Cancel retain the saved credential', async () => { + const { unset, set } = await mountSection() + fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(screen.getByLabelText(en.keyInput).placeholder) + .toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) + expect(screen.queryByText(en.keySaved)).toBeNull() + expect(unset).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) + expect(screen.getByText(en.keySaved)).toBeTruthy() + expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved) + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.click(screen.getByRole('button', { name: en.cancel })) + expect(unset).not.toHaveBeenCalled() + expect(set).not.toHaveBeenCalled() +}) + +it.each([ + ['google', 'GOOGLE_API_KEY', { env: ['GEMINI_API_KEY'], oauth: false }, true], + ['openai', 'TEAM_API_KEY', { env: ['OPENAI_API_KEY'], oauth: false }, false], + ['acme', 'ACME_API_KEY', undefined, false], +] as const)('clears %s through its saved reference and preserves the endpoint', async (provider, ref, nativeAuth, removesReference) => { + const { face, unset, set, mutate } = scriptedFace() + const namespace = piAiNamespaceWith(provider, { apiKeyEnv: ref, baseURL: 'https://gateway.example/v1' }) + const closed = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + expect(screen.getByLabelText(en.keyInput).placeholder) + .toBe(en.keyPlaceholderFallback.replace('{hint}', removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref)) + fireEvent.click(screen.getByText(en.customized)) + expect(screen.getByRole('button', { name: en.fetchModels }).disabled).toBe(true) + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(closed).toHaveBeenCalledWith(true) }) + expect(unset).toHaveBeenCalledExactlyOnceWith(ref) + expect(set).not.toHaveBeenCalled() + if (removesReference) expect(mutate.mock.calls[0]?.[1]) + .toEqual([{ op: 'unset', path: ['providers', provider, 'apiKeyEnv'] }]) + else expect(mutate).not.toHaveBeenCalled() +}) + +it('can replace a key after its removal was refused, without losing its derived reference', async () => { + const namespace = piAiNamespaceWith('google', { apiKeyEnv: 'GOOGLE_API_KEY' }) + const written = { ...namespace, revision: namespace.revision + 1, + user: { providers: { google: {} } }, value: { providers: { google: {} } } } + const mutate: ReturnType = vi.fn(() => Promise.resolve(remoteOk(written))) + const { face, unset, set } = scriptedFace({ + mutate, unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))), + }) + render() + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await screen.findByText('credential store locked') + expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } }) + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') }) + expect(unset).toHaveBeenCalledTimes(1) + expect(mutate.mock.calls[1]?.[1]).toEqual([ + { op: 'set', path: ['providers', 'google', 'apiKeyEnv'], value: 'GOOGLE_API_KEY' }, + ]) +}) + +it('clears the selected reference when refreshed metadata names a different credential', async () => { + const { face, unset, mutate } = scriptedFace() + const props: ProviderEditorProps = { + provider: 'openai', displayName: 'OpenAI', namespace: piAiNamespaceWith('openai', { apiKeyEnv: 'OLD_KEY' }), + settingsPath: ['providers', 'openai'], schema: settingsSchema, operations: operationsWith(face), + t, readOnly: false, onClose: vi.fn(), credential: { configured: true, source: 'file', writable: true }, + } + const view = render() + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + view.rerender() + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('OLD_KEY') }) + expect(mutate).not.toHaveBeenCalled() +}) + +it('clears the detected native key instead of an unused derived reference', async () => { + const { face, unset, mutate } = scriptedFace() + render() + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('GEMINI_API_KEY') }) + expect(mutate).not.toHaveBeenCalled() +}) + it.each([ ['unconfigured', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: false, source: 'env', writable: true }], ['unknown source', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: true, source: 'oauth', writable: true }], diff --git a/packages/credentials/credentials-local/README.i18n.yaml b/packages/credentials/credentials-local/README.i18n.yaml index b4401964e7..57be8084b5 100644 --- a/packages/credentials/credentials-local/README.i18n.yaml +++ b/packages/credentials/credentials-local/README.i18n.yaml @@ -24,8 +24,8 @@ en: fccad7d354c2af71 zh: 5b95b5890e21f80f /deepseek-ai-dsh-credentials-local/use-this-package/storing-and-removing-keys: - en: 5e3d45470142b9dd - zh: 1f8358f987769d3a + en: 892c025758def492 + zh: 2b04ea8dabee95aa /deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from: en: a55fac148b62e007 zh: fdb3d19ccae676ee diff --git a/packages/credentials/credentials-local/README.md b/packages/credentials/credentials-local/README.md index c3d15999be..54fed52119 100644 --- a/packages/credentials/credentials-local/README.md +++ b/packages/credentials/credentials-local/README.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value await ctx.credentials.unset(ref) // remove ``` -A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). +A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the full value. Stored keys longer than 12 characters expose only their first and last four characters in `preview`; shorter keys are fully masked. Environment credentials have no preview. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). ### Where keys come from diff --git a/packages/credentials/credentials-local/README.zh.md b/packages/credentials/credentials-local/README.zh.md index 5249827cde..47e31a979c 100644 --- a/packages/credentials/credentials-local/README.zh.md +++ b/packages/credentials/credentials-local/README.zh.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value await ctx.credentials.unset(ref) // remove ``` -你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 +你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回完整值。超过 12 个字符的已保存密钥只在 `preview` 中显示首尾各四个字符;较短密钥全部遮住。环境凭据不提供摘要。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 ### 密钥从哪里来 diff --git a/packages/credentials/credentials-local/src/index.ts b/packages/credentials/credentials-local/src/index.ts index 48ae487c6d..c8d52a317c 100644 --- a/packages/credentials/credentials-local/src/index.ts +++ b/packages/credentials/credentials-local/src/index.ts @@ -633,7 +633,10 @@ export class LocalCredentialProvider extends CredentialProvider { override describe(ref: CredentialRef): Promise { const stored = this.values.get(ref) - if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true }) + if (stored !== undefined) return Promise.resolve({ + configured: true, source: 'file', writable: true, + preview: stored.length > 12 ? `${stored.slice(0, 4)}…${stored.slice(-4)}` : '••••••••', + }) // Every reference is writable: a set writes the managed file, which // outranks every fallback, and an unset exposes the fallback again. if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true }) diff --git a/packages/credentials/credentials-local/tests/local.spec.ts b/packages/credentials/credentials-local/tests/local.spec.ts index d1436e0731..40e320f828 100644 --- a/packages/credentials/credentials-local/tests/local.spec.ts +++ b/packages/credentials/credentials-local/tests/local.spec.ts @@ -59,6 +59,23 @@ describe('resolveSpec', () => { }) describe('layering and reads', () => { + it.each([ + ['a', '••••••••'], + ['123456789012', '••••••••'], + ['1234567890123', '1234…0123'], + ['sk-managed-secret-abcd', 'sk-m…abcd'], + ])('describes a stored credential with a masked preview (%s)', async (value, preview) => { + const dir = await tempDir() + const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) + await ctx.credentials.set(KEY, value) + const info = await ctx.credentials.describe(KEY) + expect(info).toEqual({ configured: true, source: 'file', writable: true, preview }) + expect(info.preview).not.toBe(value) + expect(await ctx.credentials.resolve(KEY)).toEqual({ value, source: 'file' }) + await ctx.credentials.unset(KEY) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: false, writable: true }) + }) + it('treats an absent file as an empty writable store', async () => { const dir = await tempDir() const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) @@ -73,7 +90,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' }) expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) }) it('lets the managed file win over a non-empty process environment', async () => { @@ -83,7 +100,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', 'from-env') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) }) it('treats an empty environment value as absent, falling through to the file', async () => { @@ -93,7 +110,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', '') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) }) it('fails boot loud when the document exists but cannot be read', async () => { @@ -131,7 +148,7 @@ describe('layer ladder', () => { expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) // A key sitting in the user's .env does not make the stored one // unwritable. - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) await expect(ctx.credentials.set(KEY, 'rotated')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' }) }) @@ -230,7 +247,7 @@ describe('layer ladder', () => { { source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } }, ]) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' }) }) @@ -382,7 +399,7 @@ describe('document writes', () => { const reread = await boot({ path, watch: false }) expect(await reread.credentials.resolve(KEY)).toEqual({ value: multiLine, source: 'file' }) expect(await reread.credentials.resolve(OTHER)).toEqual({ value: mixedQuotes, source: 'file' }) - expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: 'line… two' }) }) it('unsets only the owning entry, with its own annotation, and keeps an absent unset silent', async () => { diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 3f2265caf7..3d4ea94773 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: fa334e2d4438e0b6 - zh: 009b9252ed046886 + en: d354985614dafc0d + zh: 3ff9fdd480521283 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 85ed5a68b0..95ccc9ed8e 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. +Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the full value. A provider may supply a masked `preview` for a managed key; ambient credentials have no preview. ### Storing, updating, and removing records diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index c73f0c68bf..8388b99c61 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。 +用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回完整值。提供方可为托管密钥提供脱敏的 `preview`;环境凭据不提供摘要。 ### 存储、更新与移除记录 diff --git a/packages/credentials/credentials/src/types.ts b/packages/credentials/credentials/src/types.ts index 5c9ae99350..b0e2d88cb4 100644 --- a/packages/credentials/credentials/src/types.ts +++ b/packages/credentials/credentials/src/types.ts @@ -61,14 +61,16 @@ export type CredentialRecord = ApiKeyRecord | GrantRecord /** * Source and writability facts for one reference, safe for configuration UIs — - * never the value. The view has no slot a value could ride in, which is what - * lets the whole read half cross the Remote wire. + * never the full value. Providers may include a masked preview of a managed + * credential; ambient credentials do not expose a preview. */ export interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string + /** Masked managed value for display only; short values must be fully masked. */ + preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..242f81f8eb 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -6280,7 +6280,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CredentialInfo', - declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}', + declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n preview?: string;\n writable: boolean;\n}', }, { name: 'CredentialKey', From 8b50763c0d1579bc1afa3bae74950de0325b2e63 Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 15:16:16 +0800 Subject: [PATCH 044/103] test(credentials): expect masked metadata after provider restart --- packages/llm/llm-deepseek/tests/loader-composition.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts index 183c590e2b..b90c1a8d2b 100644 --- a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts +++ b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts @@ -323,7 +323,7 @@ describe('llm-deepseek real dynamic composition', () => { const home = root! await boot.ctx.get('credentials')!.set(KEY_REF, 'stored-by-ui') expect(await boot.ctx.get('credentials')!.describe(KEY_REF)) - .toEqual({ configured: true, source: 'file', writable: true }) + .toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) await assemble(boot.ctx, { model: 'deepseek-v4-flash', messages: [] }) expect(first.headers[0]?.['x-api-key']).toBe('stored-by-ui') await boot.ctx.fiber.dispose() @@ -335,7 +335,7 @@ describe('llm-deepseek real dynamic composition', () => { // The stored key is still the provider's own file entry — not a // launch-environment value, which is what hoisting it would have made it. expect(await credentials.resolve(KEY_REF)).toEqual({ value: 'stored-by-ui', source: 'file' }) - expect(await credentials.describe(KEY_REF)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await credentials.describe(KEY_REF)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) // Rotation still works after the restart, and the next request uses it. await credentials.set(KEY_REF, 'rotated-after-restart') await assemble(restarted.ctx, { model: 'deepseek-v4-flash', messages: [] }) From 86247d664b131635059cdcac31c533eceb74c2ff Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 17:28:13 +0800 Subject: [PATCH 045/103] fix(settings): protect saved keys and preserve clear failure state --- .../tests/deepseek-messages-settings.e2e.ts | 58 ++++++- .../cards.expected.md | 4 +- .../default-models.expected.md | 4 +- .../models.expected.md | 4 +- apps/web/tests/models-settings.e2e.ts | 2 +- .../tests/onboarding-deepseek-config.e2e.ts | 4 +- docs/event-producer-consumer.md | 4 +- docs/event-producer-consumer.zh.md | 4 +- docs/subsystems/credentials.i18n.yaml | 4 +- docs/subsystems/credentials.md | 8 +- docs/subsystems/credentials.zh.md | 8 +- docs/user/guide/providers.i18n.yaml | 4 +- docs/user/guide/providers.md | 2 +- docs/user/guide/providers.zh.md | 2 +- .../settings-controller/src/credentials.ts | 1 - .../tests/credentials-controller.host.spec.ts | 19 --- .../ui-settings-models/README.i18n.yaml | 8 +- packages/client/ui-settings-models/README.md | 6 +- .../client/ui-settings-models/README.zh.md | 6 +- .../src/client/ApiKeyInput.tsx | 25 ++- .../src/client/ModelsSection.module.css | 5 + .../src/client/ProviderEditor.tsx | 48 +++--- .../ui-settings-models/src/client/locales.ts | 26 ++-- .../tests/components.client.spec.tsx | 145 +++++++++++++----- .../credentials-local/README.i18n.yaml | 4 +- .../credentials/credentials-local/README.md | 4 +- .../credentials-local/README.zh.md | 4 +- .../credentials-local/src/index.ts | 5 +- .../credentials-local/tests/local.spec.ts | 29 +--- .../credentials/credentials/README.i18n.yaml | 4 +- packages/credentials/credentials/README.md | 4 +- packages/credentials/credentials/README.zh.md | 4 +- packages/credentials/credentials/src/types.ts | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tests/loader-composition.spec.ts | 4 +- 35 files changed, 287 insertions(+), 184 deletions(-) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 95aaf1df40..232257bab3 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -17,7 +17,7 @@ import { openSettings, connectFreshWorkspaceZh, saveFailureShot, ZH_BROWSER_LOCA const EXPECTED = fileURLToPath(new URL('./expected/deepseek-messages-settings/', import.meta.url)) -it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'clear-fixture'])( +it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', 'openai', 'acme-gateway'])( 'clears the saved %s key and sends the next request with environment authentication', async (provider) => { const messages = provider === 'deepseek-official' const google = provider === 'google' @@ -120,6 +120,52 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' }, ) +it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( + 'protects saved keys and reveals only unsaved replacements in $name', async ({ engine }) => { + const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) + let browser: Browser | undefined + try { + await scaffold.ctx.credentials.set(credentialRef('DEEPSEEK_API_KEY'), 'fixture-protected-old-key') + browser = await engine.launch() + const page = await browser.newPage({ locale: ZH_BROWSER_LOCALE }) + await page.goto(scaffold.authenticatedUrl) + await openSettings(page, 'zh') + const dialog = page.getByRole('dialog', { name: '设置' }) + await dialog.getByRole('button', { name: '模型', exact: true }).click() + const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }) + await edit.click() + const key = dialog.getByLabel('API 密钥', { exact: true }) + expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.inputValue()).toBe('') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') + await key.press('Backspace') + await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') + await dialog.getByRole('button', { name: '撤销清除', exact: true }).click() + expect(await key.getAttribute('placeholder')).toBe('••••••••') + await key.fill('fixture-new-key') + await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() + expect(await key.getAttribute('type')).toBe('text') + expect(await key.inputValue()).toBe('fixture-new-key') + await key.press('ControlOrMeta+A') + await key.press('ControlOrMeta+X') + await expect.poll(() => key.inputValue()).toBe('') + await key.fill('fixture-new-key') + await dialog.getByRole('button', { name: '保存', exact: true }).click() + await expect.poll(() => key.count()).toBe(0) + await edit.click() + expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.inputValue()).toBe('') + expect(await key.getAttribute('type')).toBe('password') + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key') + } finally { + try { await browser?.close() } finally { await scaffold.close() } + } + }, +) + it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( 'keeps a foreign model drag from editing another provider input in $name', async ({ engine }) => { const scaffold = await launchWebScaffold({ deepSeekMissingCredential: true }) @@ -200,8 +246,8 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const messages = dialog const key = messages.getByLabel('API 密钥', { exact: true }) expect(await key.inputValue()).toBe('') - expect(await key.getAttribute('placeholder')).toBe('留空保留现有认证(已保存 API key)') - await messages.getByText('已保存 API key:sk-m…ding', { exact: true }).waitFor() + expect(await key.getAttribute('placeholder')).toBe('••••••••') + await messages.getByText('已保存 API key', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') @@ -228,12 +274,12 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(await page.locator('body').innerText()).not.toContain('sk-e2e-') await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click() expect(await key.inputValue()).toBe('') - await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor() + await messages.getByText('已保存 API key', { exact: true }).waitFor() expect(await key.getAttribute('type')).toBe('password') await key.fill('sk-cancelled-replacement') - expect(await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).count()).toBe(0) + expect(await messages.getByText('已保存 API key', { exact: true }).count()).toBe(0) await key.fill('') - await messages.getByText('已保存 API key:sk-e…ages', { exact: true }).waitFor() + await messages.getByText('已保存 API key', { exact: true }).waitFor() await messages.getByRole('button', { name: '保存', exact: true }).click() await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor() expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index b069459b00..16292f4f76 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -18,8 +18,8 @@ - button "认证说明": "?" - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空保留现有认证(已保存 API key) - - paragraph: 已保存 API key:sk-m…ding + - /placeholder: •••••••• + - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 3831507855..36c34db458 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -18,8 +18,8 @@ - button "认证说明": "?" - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空保留现有认证(已保存 API key) - - paragraph: 已保存 API key:dsh_…test + - /placeholder: •••••••• + - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 3b99eb9c63..2bd3311246 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -18,8 +18,8 @@ - button "认证说明": "?" - button "清除已保存密钥" - textbox "API 密钥": - - /placeholder: 留空保留现有认证(已保存 API key) - - paragraph: 已保存 API key:dsh_…test + - /placeholder: •••••••• + - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 60b82d06cb..8ab5654d88 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() - await dialog.getByPlaceholder('留空保留现有认证(已保存 API key)', { exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByPlaceholder('••••••••', { exact: true }).waitFor({ timeout: 10_000 }) expect(await dialog.textContent()).not.toContain('API 密钥来源:') expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index cb8d12bf9b..b8a66b6600 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -116,7 +116,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空保留现有认证(已保存 API key)') + ).toBe('••••••••') const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -258,7 +258,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('留空保留现有认证(已保存 API key)') + ).toBe('••••••••') const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index f309851827..7e1a837be5 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -40,8 +40,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 2924a21051..85f0623eaf 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -42,8 +42,8 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index 551fc5c9bf..bad9827407 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -12,8 +12,8 @@ en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: 5150dd250ea3a4b2 - zh: 944d0fffca37dec5 + en: f7b09588c0f34952 + zh: 1b93d673c5bf6a80 /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 47143f32da..2a084fb29f 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -32,21 +32,19 @@ interface ResolvedCredential { ## Description -`describe(ref)` reports whether a reference resolves, its source, writability, and an optional masked preview of a managed credential. It never returns the full value or an ambient credential preview. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. +`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** * Source and writability facts for one reference, safe for configuration UIs — - * never the full value. Providers may include a masked preview of a managed - * credential; ambient credentials do not expose a preview. + * never the value. The view has no slot a value could ride in, which is what + * lets the whole read half cross the Remote wire. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string - /** Masked managed value for display only; short values must be fully masked. */ - preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 727d2a09c2..1e9221699a 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -32,21 +32,19 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 报告引用是否可解析、来源、可写性,以及可选的托管凭据脱敏摘要。它不返回完整值,也不提供环境凭据摘要。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 +`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** * Source and writability facts for one reference, safe for configuration UIs — - * never the full value. Providers may include a masked preview of a managed - * credential; ambient credentials do not expose a preview. + * never the value. The view has no slot a value could ride in, which is what + * lets the whole read half cross the Remote wire. */ interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string - /** Masked managed value for display only; short values must be fully masked. */ - preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 2ee34aa5c0..becdd6b82f 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: 2bfca1d989fce463 - zh: f86948426dad32b0 + en: c0993fb8f0131a5e + zh: 8932850d36a0f3d7 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 7e08db5dbc..12250389ea 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,7 +20,7 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential uses the placeholder **Leave blank to keep current authentication (API key saved)** and a green masked-key preview below the empty input. Select **Clear saved key**, then **Save**, to remove the stored override and use environment authentication. **Undo clear** or **Cancel** preserves the key. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays a fixed mask in the input and a green saved-key hint. The mask does not expose the key or its length. Saved keys cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Select **Clear saved key**, then **Save**, to remove the stored override and use environment authentication. **Keep saved key** or **Cancel** preserves the key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 7b93565776..a50dd918b6 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,7 +20,7 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据使用**留空保留现有认证(已保存 API key)**占位文字,在空输入框下方显示绿色的密钥脱敏摘要。选择**清除已保存密钥**,再点**保存**,即可移除存储覆盖并使用环境认证。**撤销清除**或**取消**会保留密钥。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中显示固定掩码,下方显示绿色的已保存密钥提示。掩码不暴露密钥或长度。已保存密钥不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。选择**清除已保存密钥**,再点**保存**,即可移除存储覆盖并使用环境认证。保存前,**撤销清除**或**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 225dbcd6d0..3889669048 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -46,7 +46,6 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo { return { configured: info.configured, ...info.source === undefined ? {} : { source: info.source }, - ...info.preview === undefined ? {} : { preview: info.preview }, writable: info.writable, } } diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index d1019cab01..5eeb190385 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -14,16 +14,6 @@ class LeakyCredentials extends MemoryCredentials { } } -/** A managed provider returning a display preview alongside an undeclared secret. */ -class PreviewCredentials extends MemoryCredentials { - override describe(): Promise { - return Promise.resolve({ - configured: true, source: 'file', writable: true, - preview: 'sk-m…abcd', value: 'sk-managed-secret-abcd', - } as CredentialInfo) - } -} - /** A store whose write rejects with a bare string, the way some client libraries do. */ class LiteralRejectingCredentials extends MemoryCredentials { override async set(): Promise { @@ -115,15 +105,6 @@ describe('the credentials Remote namespace a configuration surface calls', () => expect(JSON.stringify(described)).not.toContain('sk-leaked') }) - it('returns the masked preview without the original stored credential', async () => { - const controller = await boot({}, PreviewCredentials) - const described = await controller.describe(['DEEPSEEK_API_KEY']) - expect(described.DEEPSEEK_API_KEY).toEqual({ - configured: true, source: 'file', writable: true, preview: 'sk-m…abcd', - }) - expect(JSON.stringify(described)).not.toContain('sk-managed-secret-abcd') - }) - it('stores and removes through the same references the batch describes', async () => { const controller = await boot() await controller.set('DEEPSEEK_API_KEY', 'sk-live') diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index d8277713b1..d63c348a8b 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: c4865eabb48e3839 - zh: 66f5c6698845112f + en: 980f4a0dcc47c6e0 + zh: 603ea270e1b6f79d /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 19fbfafb53ea1593 - zh: 880f6703111383fd + en: b4f40dfd8857e64e + zh: 21486ade0dc4c259 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 89bbf726d4..09f8c21558 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,15 +41,15 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs start empty and use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. +API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display a fixed mask as a placeholder, never a credential value or its length. They have no reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. -The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint receives only a Host-masked preview of a saved key and never changes field writability. +The editor uses redacted `CredentialInfo` to choose the saved-credential placeholder or environment detection, without displaying a credential-source label. Refreshing the snapshot updates an open editor without a separate probe. The hint receives no credential value and never changes field writability. ### Editing a provider -A blank key field preserves existing authentication. A saved credential shows a green notice with its masked preview below the input; providers without a preview show only that a key is saved. Otherwise the field offers environment authentication. **Clear saved key** stages removal until Save; Undo or Cancel preserves the key. Entering a new key replaces the removal draft. A catalog route drops its user-layer derived reference to restore native authentication; explicit aliases, inherited references, and custom routes retain their reference for environment fallback. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +A blank key field preserves existing authentication. A saved credential shows a fixed input mask and a green saved-key notice. Otherwise the field offers environment authentication. **Clear saved key** stages removal until Save; Undo or Cancel preserves the key. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, without Undo; Close leaves that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 4d2527b402..20aa8a3604 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,15 +41,15 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框初始为空,并通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 +API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥以固定掩码占位显示,不表示凭据值或长度;不提供显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 -编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示只接收 Host 生成的已保存密钥脱敏摘要,不改变字段的可写性。 +编辑器使用脱敏 `CredentialInfo` 选择已保存凭据的占位文字或环境检测,不显示凭据来源标签。快照刷新会更新打开的编辑器,无需单独探测。提示从不接收凭据值,也不改变字段的可写性。 ### 编辑提供商 -密钥字段留空时保留现有认证。已保存凭据在输入框下方显示绿色提示及脱敏摘要;提供方未提供摘要时,只提示已保存密钥。否则提示使用环境认证。**清除已保存密钥**将删除操作暂存到「保存」时执行;撤销或取消会保留密钥。输入新密钥会替换待删除草稿。目录路由会移除用户层中的派生引用以恢复原生认证;显式别名、继承引用和自定义路由保留原引用以使用环境后备。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +密钥字段留空时保留现有认证。已保存凭据显示固定的输入掩码和绿色的已保存密钥提示。否则提示使用环境认证。**清除已保存密钥**将删除操作暂存到「保存」时执行;撤销或取消会保留密钥。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;不再提供撤销,「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index e983a40303..2a157caaa1 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -1,4 +1,4 @@ -/** Write-only credential input with the same reveal behavior as masked conversation text. */ +/** Credential drafts can be revealed; saved keys are represented by a protected mask. */ import { useState } from 'react' import type { InputHTMLAttributes, ReactNode } from 'react' import type { en } from './locales.ts' @@ -12,26 +12,39 @@ const EYE_OFF_PATH = `${EYE_CONTOUR}M2.5 2.5L13.5 13.5` interface ApiKeyInputProps extends Omit, 'value' | 'type' | 'className' | 'autoComplete'> { /** Unsaved input; stored credentials are never read into this field. */ readonly value: string + /** Saved-key actions; the mask never contains the stored credential. */ + readonly saved?: { + readonly clear?: () => void + } /** Section copy, including the same reveal labels as SecretText. */ readonly t: (key: keyof typeof en) => string } /** - * Reveal only a nonempty draft; a different value starts masked, as in SecretText. + * Reveal only a nonempty draft. Saved keys allow whole replacement or deletion. * @param props - current draft, input attributes, and translated control labels. * @returns a password input with an optional reveal button. */ -export function ApiKeyInput({ value, t, ...props }: ApiKeyInputProps): ReactNode { +export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): ReactNode { const [revealedValue, setRevealedValue] = useState() - const revealed = value.length > 0 && revealedValue === value + const revealed = saved === undefined && value.length > 0 && revealedValue === value return ( -
+
0 ? styles['keyInputFilled'] : ''}`} + className={`${styles['input']} ${saved === undefined && value.length > 0 ? styles['keyInputFilled'] : ''}`} type={revealed ? 'text' : 'password'} autoComplete="new-password" value={value} + placeholder={saved === undefined ? props.placeholder : '••••••••'} + onCopy={(event) => { if (saved !== undefined) event.preventDefault() }} + onCut={(event) => { if (saved !== undefined) event.preventDefault() }} + onKeyDown={(event) => { + if (saved !== undefined && (event.key === 'Backspace' || event.key === 'Delete')) { + event.preventDefault() + saved.clear?.() + } + }} onChange={(event) => { setRevealedValue(undefined) props.onChange?.(event) diff --git a/packages/client/ui-settings-models/src/client/ModelsSection.module.css b/packages/client/ui-settings-models/src/client/ModelsSection.module.css index eb25fd570c..a232a69045 100644 --- a/packages/client/ui-settings-models/src/client/ModelsSection.module.css +++ b/packages/client/ui-settings-models/src/client/ModelsSection.module.css @@ -844,6 +844,11 @@ select.input { position: relative; } +.savedKeyInput .input::placeholder { + color: var(--dsw-alias-label-primary); + opacity: 1; +} + .keyInputFilled { padding-right: 40px; } diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index d7ee7baf99..7b337a2be1 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -200,9 +200,9 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { return { ...loaded, retryPolicy: { ...policy, mode } } }) // An empty string preserves authentication; a reference stages its removal. - const [keyDraft, setKeyDraft] = useState('') + const [keyDraft, setKeyDraft] = useState() const keyText = typeof keyDraft === 'string' ? keyDraft : '' - const keyRemoval = typeof keyDraft === 'string' ? undefined : keyDraft + const keyRemoval = typeof keyDraft === 'object' ? keyDraft : undefined const [busy, setBusy] = useState(false) const [listBusy, setListBusy] = useState(false) const { onBusyChange } = props @@ -313,9 +313,8 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { */ const applyOnce = async (): Promise => { const ns = namespace.ns - // A catalog provider returns to native authentication when this page's - // derived reference is removed. Explicit aliases and custom routes keep - // their reference so its environment fallback remains addressable. + // Removing a catalog route's conventional reference restores native auth. + // Other aliases and custom routes keep their named environment fallback. const profileDraft = clearsDerivedRef ? schema.deletePath(draft, ['apiKeyEnv']) : draft // A pi-ai profile names the conventional reference only when this page is // about to store a key. Otherwise the provider keeps its native auth path. @@ -348,6 +347,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { : materializesNativeProfile ? [{ op: 'set', path: [...settingsPath], value: {} }] : pathOps(settingsPath, committedOriginal, next) + if (keyRemoval !== undefined && keyRemoval.removed !== true) { + const removed = await operations.removeCredential(keyRemoval.ref) + if (removed !== undefined) return removed + // A later settings failure cannot restore a secret that was deleted. + setKeyDraft({ ...keyRemoval, removed: true }) + } if (ops.length > 0) { const written = await operations.writeSettings(ns, ops, expectedRevision) if (written.kind !== 'written') return written.kind === 'conflict' ? t('conflict') : written.message @@ -355,10 +360,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { setExpectedRevision(written.view.revision) setDraft(next) } - if (keyRemoval !== undefined) { - const removed = await operations.removeCredential(keyRemoval.ref) - if (removed !== undefined) return removed - } else if (keyValue.length > 0) { + if (keyValue.length > 0) { const stored = await operations.storeCredential(keyRef, keyValue) if (stored !== undefined) return stored } @@ -438,15 +440,14 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const detectedRef = detected?.[0] const detectedVisibleRef = detectedRef === undefined || !visibleRefs.includes(detectedRef) ? undefined : detectedRef const missingRefs = checkedRefs.length > 0 && checkedRefs.every(([, info]) => info?.configured === false) - const savedPreview = detected?.[1]?.preview - const savedCredential = detected?.[1]?.source === 'file' || savedPreview !== undefined + const savedCredential = detected?.[1]?.source === 'file' && detectedVisibleRef !== undefined const removalRef = keyRemoval?.ref ?? detectedRef const credentialHint = keyText.length > 0 || props.credentialRequired === true ? undefined - : keyRemoval !== undefined ? t('keyRemovePending') + : keyRemoval !== undefined ? t(keyRemoval.removed === true ? 'keyRemoveApplied' : 'keyRemovePending') : keyHint === undefined ? undefined : savedCredential - ? savedPreview === undefined ? t('keySaved') : t('keySavedPreview').replace('{preview}', () => savedPreview) + ? t('keySaved') : t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked' : detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected') .replace('{hint}', () => detectedVisibleRef ?? keyHint) @@ -482,27 +483,36 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { {t('keyInput')} {authHelp} - {keyText.length === 0 && props.credentialRequired !== true && removalRef !== undefined - && (keyRemoval !== undefined || (savedCredential && detected?.[1]?.writable === true)) + {keyRemoval?.removed !== true && keyText.length === 0 && props.credentialRequired !== true && removalRef !== undefined + && (keyRemoval !== undefined || (savedCredential && detected[1].writable)) ? : null} { setKeyDraft({ ref: removalRef }); setFailure(undefined) } } : {}, + }, + } : {}} placeholder={keyPlaceholder} aria-label={t('keyInput')} aria-invalid={shownKeyFailure !== undefined && !protocolKeyMissing} aria-describedby={credentialHint === undefined ? undefined : `${props.provider}-credential-hint`} required={props.credentialRequired === true || protocolNeedsKeyHere} autoFocus={props.autoFocusCredential === true} - disabled={disabled} - onChange={(event) => { setKeyDraft(event.target.value) }} + disabled={disabled || keyRemoval?.removed === true} + onChange={(event) => { setKeyDraft(event.target.value); setFailure(undefined) }} /> {credentialHint === undefined ? null :

{credentialHint}

} {/* A key the protocol requires is a requirement still to meet, not a fault. */} @@ -674,7 +684,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { || (props.credentialRequired === true && keyValue.length === 0)} submitLabelKey={props.submitLabelKey ?? 'apply'} submitBusyLabelKey={props.submitBusyLabelKey ?? 'applying'} - {...props.cancelLabelKey === undefined ? {} : { cancelLabelKey: props.cancelLabelKey }} + cancelLabelKey={keyRemoval?.removed === true ? 'close' : props.cancelLabelKey ?? 'cancel'} onCancel={() => { props.onClose(false) }} onSubmit={() => { props.onSubmitCredential?.(); void apply() }} /> diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index 0a359c223c..5b7861878a 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -43,10 +43,10 @@ export const en = { keyPlaceholderFallback: 'Leave blank to use env as auth ({hint})', keyPlaceholderSaved: 'Leave blank to keep current authentication (API key saved)', keySaved: 'API key saved', - keySavedPreview: 'API key saved: {preview}', keyRemove: 'Clear saved key', - keyRemoveUndo: 'Undo clear', + keyRemoveUndo: 'Keep saved key', keyRemovePending: 'Save to clear the saved key and use environment authentication.', + keyRemoveApplied: 'Key cleared. Retry Save to finish settings; this deletion cannot be undone.', keyFallbackMissing: 'Env var not detected. Enter an API key, or configure {hint} in your env.', keyFallbackDetected: 'Env var detected. ({hint})', keyFallbackDetectedHidden: 'Env var detected.', @@ -224,10 +224,10 @@ export const zh: { [Key in keyof typeof en]: string } = { keyPlaceholderFallback: '留空使用环境认证({hint})', keyPlaceholderSaved: '留空保留现有认证(已保存 API key)', keySaved: '已保存 API key', - keySavedPreview: '已保存 API key:{preview}', keyRemove: '清除已保存密钥', keyRemoveUndo: '撤销清除', keyRemovePending: '保存后清除已保存密钥,并使用环境认证', + keyRemoveApplied: '密钥已清除,请重试保存以完成配置更新;此删除无法撤销', keyFallbackMissing: '未检测到环境变量。请填写 API 密钥,或设置环境变量 {hint}。', keyFallbackDetected: '已检测到环境变量({hint})', keyFallbackDetectedHidden: '已检测到环境变量', @@ -401,11 +401,11 @@ export const ja = { 'keyPlaceholder': 'APIキーを入力', 'keyPlaceholderFallback': '空欄のままにすると環境変数を認証に使用します ({hint})', 'keyPlaceholderSaved': '空欄のままにすると現在の認証を保持します(APIキー保存済み)', - keySaved: 'APIキー保存済み', - keySavedPreview: 'APIキー保存済み: {preview}', - keyRemove: '保存済みキーを削除', - keyRemoveUndo: '削除を取り消す', - keyRemovePending: '保存すると保存済みキーを削除し、環境変数の認証を使用します。', + 'keySaved': 'APIキー保存済み', + 'keyRemove': '保存済みキーを削除', + 'keyRemoveUndo': '削除を取り消す', + 'keyRemovePending': '保存すると保存済みキーを削除し、環境変数の認証を使用します。', + 'keyRemoveApplied': 'キーは削除済みです。保存を再試行して設定を更新してください。削除は取り消せません。', 'keyFallbackMissing': '環境変数が検出されません。APIキーを入力するか、環境変数に{hint}を設定してください。', 'keyFallbackDetected': '環境変数を検出しました。({hint})', 'keyFallbackDetectedHidden': '環境変数を検出しました。', @@ -580,10 +580,10 @@ export const es = { keyPlaceholderFallback: 'Déjelo en blanco para usar env como autenticación ({hint})', keyPlaceholderSaved: 'Déjelo en blanco para conservar la autenticación actual (clave API guardada)', keySaved: 'Clave API guardada', - keySavedPreview: 'Clave API guardada: {preview}', keyRemove: 'Borrar clave guardada', keyRemoveUndo: 'Deshacer borrado', keyRemovePending: 'Guarde para borrar la clave guardada y usar la autenticación del entorno.', + keyRemoveApplied: 'Clave borrada. Reintente guardar para completar la configuración; no se puede deshacer.', keyFallbackMissing: 'No se detectó la variable de entorno. Ingrese una clave API o configure {hint} en su entorno.', keyFallbackDetected: 'Se detectó var env. ({hint})', keyFallbackDetectedHidden: 'Se detectó var env.', @@ -758,10 +758,10 @@ export const fr = { keyPlaceholderFallback: 'Laissez vide pour utiliser env comme authentification ({hint})', keyPlaceholderSaved: 'Laissez vide pour conserver l’authentification actuelle (clé API enregistrée)', keySaved: 'Clé API enregistrée', - keySavedPreview: 'Clé API enregistrée : {preview}', keyRemove: 'Effacer la clé enregistrée', keyRemoveUndo: 'Annuler l’effacement', keyRemovePending: 'Enregistrez pour effacer la clé enregistrée et utiliser l’authentification de l’environnement.', + keyRemoveApplied: 'Clé supprimée. Réessayez d’enregistrer pour terminer les paramètres ; la suppression est irréversible.', keyFallbackMissing: "Var d'environnement non détectée. Entrez une clé API ou configurez {hint} dans votre environnement.", keyFallbackDetected: "Var d'environnement détectée. ({hint})", keyFallbackDetectedHidden: "Var d'environnement détectée.", @@ -936,10 +936,10 @@ export const de = { keyPlaceholderFallback: 'Lassen Sie das Feld leer, um env als Authentifizierung zu verwenden ({hint})', keyPlaceholderSaved: 'Leer lassen, um die aktuelle Authentifizierung beizubehalten (API-Schlüssel gespeichert)', keySaved: 'API-Schlüssel gespeichert', - keySavedPreview: 'API-Schlüssel gespeichert: {preview}', keyRemove: 'Gespeicherten Schlüssel löschen', keyRemoveUndo: 'Löschen rückgängig machen', keyRemovePending: 'Speichern, um den gespeicherten Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.', + keyRemoveApplied: 'Schlüssel gelöscht. Speichern erneut versuchen, um die Einstellungen abzuschließen; das Löschen ist unwiderruflich.', keyFallbackMissing: 'Umgebungsvariable nicht erkannt. Geben Sie einen API-Schlüssel ein oder konfigurieren Sie {hint} in Ihrer Umgebung.', keyFallbackDetected: 'Umgebungsvariable erkannt. ({hint})', keyFallbackDetectedHidden: 'Umgebungsvariable erkannt.', @@ -1114,10 +1114,10 @@ export const ru = { keyPlaceholderFallback: 'Оставьте пустым, чтобы использовать env в качестве аутентификации ({hint})', keyPlaceholderSaved: 'Оставьте поле пустым, чтобы сохранить текущую аутентификацию (API-ключ сохранён)', keySaved: 'API-ключ сохранён', - keySavedPreview: 'API-ключ сохранён: {preview}', keyRemove: 'Удалить сохранённый ключ', keyRemoveUndo: 'Отменить удаление', keyRemovePending: 'Сохраните, чтобы удалить сохранённый ключ и использовать аутентификацию из окружения.', + keyRemoveApplied: 'Ключ удалён. Повторите сохранение настроек; удаление нельзя отменить.', keyFallbackMissing: 'Переменная Env не обнаружена. Введите ключ API или настройте {hint} в своей среде.', keyFallbackDetected: 'Обнаружена переменная Env. ({hint})', keyFallbackDetectedHidden: 'Обнаружена переменная Env.', @@ -1292,10 +1292,10 @@ export const pt = { keyPlaceholderFallback: 'Deixe em branco para usar env como autenticação ({hint})', keyPlaceholderSaved: 'Deixe em branco para manter a autenticação atual (chave API salva)', keySaved: 'Chave API salva', - keySavedPreview: 'Chave API salva: {preview}', keyRemove: 'Limpar chave salva', keyRemoveUndo: 'Desfazer limpeza', keyRemovePending: 'Salve para limpar a chave salva e usar a autenticação do ambiente.', + keyRemoveApplied: 'Chave apagada. Tente salvar novamente para concluir as configurações; a exclusão não pode ser desfeita.', keyFallbackMissing: 'Env var não detectado. Insira uma chave API ou configure {hint} em seu ambiente.', keyFallbackDetected: 'Variável de ambiente detectada. ({hint})', keyFallbackDetectedHidden: 'Variável de ambiente detectada.', diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index 28cc89d192..076b625075 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -1455,7 +1455,7 @@ describe('ModelsSection', () => { fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) // The field names the profile's reference; a stored value stays hidden. const editorKey = await screen.findByLabelText(en.keyInput) - expect(editorKey.placeholder).toBe(en.keyPlaceholderSaved) + expect(editorKey.placeholder).toBe('••••••••') // pi-ai carries Base URL too: the stored override shows as the value and // the effective profile endpoint, ahead of the catalog's, as its placeholder. fireEvent.click(screen.getByText(en.customized)) @@ -1641,7 +1641,7 @@ describe('ModelsSection', () => { face.credentials.describe.mockImplementation(() => Promise.resolve(remoteFail('down', 'gateway/internal'))) fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) const editorKey = await screen.findByLabelText(en.keyInput) - expect(editorKey.placeholder).toBe(en.keyPlaceholderSaved) + expect(editorKey.placeholder).toBe('••••••••') fireEvent.change(editorKey, { target: { value: 'sk-live' } }) fireEvent.click(screen.getByText(en.apply)) await waitFor(() => { expect(set).toHaveBeenCalledTimes(1) }) @@ -2215,7 +2215,7 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing else expect(screen.getAllByText(hint)).toHaveLength(1) expect(input.value).toBe('') expect(input.placeholder) - .toBe(source === 'file' ? en.keyPlaceholderSaved : en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) + .toBe(source === 'file' ? '••••••••' : en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) fireEvent.change(input, { target: { value: 'new-key' } }) expect(screen.queryByText(hint)).toBeNull() expect(screen.queryByText(/^API key source:/)).toBeNull() @@ -2225,33 +2225,69 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing else expect(screen.getAllByText(hint)).toHaveLength(1) }) -it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('shows only a saved-key preview for %s and preserves it when the draft is cleared', (provider) => { - const preview = 'sk-m…abcd' - const hint = en.keySavedPreview.replace('{preview}', preview) +it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects the saved %s key and reveals only its replacement', (provider) => { renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: 'TEAM_API_KEY' }), { - credential: { configured: true, source: 'file', writable: true, preview }, + credential: { configured: true, source: 'file', writable: true }, }) const input = screen.getByLabelText(en.keyInput) expect(input.value).toBe('') expect(input.type).toBe('password') - expect(input.placeholder).toBe(en.keyPlaceholderSaved) - const notice = screen.getByText(hint) - expect(input.getAttribute('aria-describedby')).toBe(notice.id) + expect(input.placeholder).toBe('••••••••') expect(screen.queryByLabelText(en.keyReveal)).toBeNull() + expect(fireEvent.copy(input)).toBe(false) + expect(fireEvent.cut(input)).toBe(false) fireEvent.change(input, { target: { value: 'replacement-key' } }) - expect(screen.queryByText(hint)).toBeNull() + expect(screen.queryByText(en.keySaved)).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.keyReveal })) + expect(input.type).toBe('text') + expect(input.value).toBe('replacement-key') + expect(fireEvent.copy(input)).toBe(true) + expect(fireEvent.cut(input)).toBe(true) fireEvent.change(input, { target: { value: '' } }) - expect(screen.getByText(hint)).toBeTruthy() - expect(input.value).toBe('') + expect(screen.getByText(en.keySaved)).toBeTruthy() + expect(input.placeholder).toBe(en.keyPlaceholderSaved) + expect(screen.queryByLabelText(en.keyReveal)).toBeNull() }) -it('uses a managed preview from a credential provider with its own source label', () => { +it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and can undo it', async (key) => { + const { unset } = await mountSection() + fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) + const input = screen.getByLabelText(en.keyInput) + expect(input.placeholder).toBe('••••••••') + fireEvent.keyDown(input, { key: 'ArrowLeft' }) + expect(input.placeholder).toBe('••••••••') + fireEvent.keyDown(input, { key }) + expect(input.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) + expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(unset).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) + expect(input.placeholder).toBe('••••••••') + fireEvent.keyDown(input, { key }) + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('OPENAI_API_KEY') }) +}) + +it('keeps a saved read-only credential masked when deletion is unavailable', () => { renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { - credential: { configured: true, source: 'keychain', writable: true, preview: 'sk-m…abcd' }, + credential: { configured: true, source: 'file', writable: false }, }) - expect(screen.getByText(en.keySavedPreview.replace('{preview}', 'sk-m…abcd'))).toBeTruthy() - expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved) - expect(screen.queryByText(/Env var detected/)).toBeNull() + const input = screen.getByLabelText(en.keyInput) + fireEvent.keyDown(input, { key: 'Delete' }) + expect(input.placeholder).toBe('••••••••') + expect(screen.queryByText(en.keyRemovePending)).toBeNull() + expect(screen.queryByRole('button', { name: en.keyRemove })).toBeNull() +}) + +it('keeps a hidden OAuth reference out of the saved API-key controls', () => { + renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', { apiKeyEnv: 'ANTHROPIC_OAUTH_TOKEN' }), { + credential: { configured: true, source: 'file', writable: true }, + }) + const input = screen.getByLabelText(en.keyInput) + expect(input.value).toBe('') + expect(input.placeholder).toBe(en.keyPlaceholder) + expect(screen.queryByRole('button', { name: en.keyRemove })).toBeNull() + fireEvent.keyDown(input, { key: 'Delete' }) + expect(screen.queryByText(en.keyRemovePending)).toBeNull() }) it('stages key removal and lets Undo or Cancel retain the saved credential', async () => { @@ -2265,7 +2301,7 @@ it('stages key removal and lets Undo or Cancel retain the saved credential', asy expect(unset).not.toHaveBeenCalled() fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) expect(screen.getByText(en.keySaved)).toBeTruthy() - expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved) + expect(screen.getByLabelText(en.keyInput).placeholder).toBe('••••••••') fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) fireEvent.click(screen.getByRole('button', { name: en.cancel })) expect(unset).not.toHaveBeenCalled() @@ -2298,29 +2334,68 @@ it.each([ else expect(mutate).not.toHaveBeenCalled() }) -it('can replace a key after its removal was refused, without losing its derived reference', async () => { - const namespace = piAiNamespaceWith('google', { apiKeyEnv: 'GOOGLE_API_KEY' }) - const written = { ...namespace, revision: namespace.revision + 1, - user: { providers: { google: {} } }, value: { providers: { google: {} } } } - const mutate: ReturnType = vi.fn(() => Promise.resolve(remoteOk(written))) - const { face, unset, set } = scriptedFace({ - mutate, unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))), +it.each(['undo', 'cancel', 'replace'])('keeps authentication unchanged after refused deletion, then %s', async (action) => { + const { face, unset, set, mutate } = scriptedFace({ + unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))), }) - render() fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('credential store locked') + expect(mutate).not.toHaveBeenCalled() expect(screen.getByText(en.keyRemovePending)).toBeTruthy() - fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } }) + if (action === 'cancel') { + fireEvent.click(screen.getByRole('button', { name: en.cancel })) + expect(closed).toHaveBeenCalledWith(false) + } else { + if (action === 'undo') { + fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) + expect(screen.getByLabelText(en.keyInput).placeholder).toBe('••••••••') + } else { + fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } }) + } + expect(screen.queryByText('credential store locked')).toBeNull() + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(closed).toHaveBeenCalledWith(true) }) + if (action === 'replace') expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') + else expect(set).not.toHaveBeenCalled() + } + expect(unset).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY') + expect(mutate).not.toHaveBeenCalled() +}) + +it.each(['retry', 'close'])('reports a completed deletion when settings fail, then %s', async (action) => { + const namespace = piAiNamespaceWith('google', { apiKeyEnv: 'GOOGLE_API_KEY' }) + const written = { ...namespace, revision: namespace.revision + 1, + user: { providers: { google: {} } }, value: { providers: { google: {} } } } + const mutate = vi.fn().mockResolvedValueOnce(remoteFail('settings locked')).mockResolvedValueOnce(remoteOk(written)) + const { face, unset } = scriptedFace({ mutate }) + const closed = vi.fn() + render() + fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) fireEvent.click(screen.getByRole('button', { name: en.apply })) - await waitFor(() => { expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') }) - expect(unset).toHaveBeenCalledTimes(1) - expect(mutate.mock.calls[1]?.[1]).toEqual([ - { op: 'set', path: ['providers', 'google', 'apiKeyEnv'], value: 'GOOGLE_API_KEY' }, - ]) + await screen.findByText('settings locked') + expect(screen.getByText(en.keyRemoveApplied)).toBeTruthy() + expect(screen.queryByRole('button', { name: en.keyRemoveUndo })).toBeNull() + expect(screen.getByLabelText(en.keyInput).disabled).toBe(true) + if (action === 'retry') { + fireEvent.click(screen.getByRole('button', { name: en.apply })) + await waitFor(() => { expect(closed).toHaveBeenCalledWith(true) }) + expect(mutate).toHaveBeenCalledTimes(2) + } else { + fireEvent.click(screen.getByRole('button', { name: en.close })) + expect(closed).toHaveBeenCalledWith(false) + expect(mutate).toHaveBeenCalledOnce() + } + expect(unset).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY') }) it('clears the selected reference when refreshed metadata names a different credential', async () => { @@ -2364,7 +2439,7 @@ it('refreshes a blank editor from saved credentials to environment detection wit const { face, controller } = await mountSection() const reads = face.credentials.describe.mock.calls.length fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) - expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholderSaved) + expect(screen.getByLabelText(en.keyInput).placeholder).toBe('••••••••') expect(screen.queryByText(/^API key source:/)).toBeNull() expect(screen.queryByText(/Env var detected/)).toBeNull() expect(face.credentials.describe).toHaveBeenCalledTimes(reads) diff --git a/packages/credentials/credentials-local/README.i18n.yaml b/packages/credentials/credentials-local/README.i18n.yaml index 57be8084b5..b4401964e7 100644 --- a/packages/credentials/credentials-local/README.i18n.yaml +++ b/packages/credentials/credentials-local/README.i18n.yaml @@ -24,8 +24,8 @@ en: fccad7d354c2af71 zh: 5b95b5890e21f80f /deepseek-ai-dsh-credentials-local/use-this-package/storing-and-removing-keys: - en: 892c025758def492 - zh: 2b04ea8dabee95aa + en: 5e3d45470142b9dd + zh: 1f8358f987769d3a /deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from: en: a55fac148b62e007 zh: fdb3d19ccae676ee diff --git a/packages/credentials/credentials-local/README.md b/packages/credentials/credentials-local/README.md index 54fed52119..c3d15999be 100644 --- a/packages/credentials/credentials-local/README.md +++ b/packages/credentials/credentials-local/README.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value await ctx.credentials.unset(ref) // remove ``` -A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the full value. Stored keys longer than 12 characters expose only their first and last four characters in `preview`; shorter keys are fully masked. Environment credentials have no preview. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). +A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). ### Where keys come from diff --git a/packages/credentials/credentials-local/README.zh.md b/packages/credentials/credentials-local/README.zh.md index 47e31a979c..5249827cde 100644 --- a/packages/credentials/credentials-local/README.zh.md +++ b/packages/credentials/credentials-local/README.zh.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value await ctx.credentials.unset(ref) // remove ``` -你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回完整值。超过 12 个字符的已保存密钥只在 `preview` 中显示首尾各四个字符;较短密钥全部遮住。环境凭据不提供摘要。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 +你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 ### 密钥从哪里来 diff --git a/packages/credentials/credentials-local/src/index.ts b/packages/credentials/credentials-local/src/index.ts index c8d52a317c..48ae487c6d 100644 --- a/packages/credentials/credentials-local/src/index.ts +++ b/packages/credentials/credentials-local/src/index.ts @@ -633,10 +633,7 @@ export class LocalCredentialProvider extends CredentialProvider { override describe(ref: CredentialRef): Promise { const stored = this.values.get(ref) - if (stored !== undefined) return Promise.resolve({ - configured: true, source: 'file', writable: true, - preview: stored.length > 12 ? `${stored.slice(0, 4)}…${stored.slice(-4)}` : '••••••••', - }) + if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true }) // Every reference is writable: a set writes the managed file, which // outranks every fallback, and an unset exposes the fallback again. if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true }) diff --git a/packages/credentials/credentials-local/tests/local.spec.ts b/packages/credentials/credentials-local/tests/local.spec.ts index 40e320f828..d1436e0731 100644 --- a/packages/credentials/credentials-local/tests/local.spec.ts +++ b/packages/credentials/credentials-local/tests/local.spec.ts @@ -59,23 +59,6 @@ describe('resolveSpec', () => { }) describe('layering and reads', () => { - it.each([ - ['a', '••••••••'], - ['123456789012', '••••••••'], - ['1234567890123', '1234…0123'], - ['sk-managed-secret-abcd', 'sk-m…abcd'], - ])('describes a stored credential with a masked preview (%s)', async (value, preview) => { - const dir = await tempDir() - const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) - await ctx.credentials.set(KEY, value) - const info = await ctx.credentials.describe(KEY) - expect(info).toEqual({ configured: true, source: 'file', writable: true, preview }) - expect(info.preview).not.toBe(value) - expect(await ctx.credentials.resolve(KEY)).toEqual({ value, source: 'file' }) - await ctx.credentials.unset(KEY) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: false, writable: true }) - }) - it('treats an absent file as an empty writable store', async () => { const dir = await tempDir() const ctx = await boot({ path: join(dir, '.credentials.yaml'), watch: false }) @@ -90,7 +73,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' }) expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) }) it('lets the managed file win over a non-empty process environment', async () => { @@ -100,7 +83,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', 'from-env') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) }) it('treats an empty environment value as absent, falling through to the file', async () => { @@ -110,7 +93,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', '') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) }) it('fails boot loud when the document exists but cannot be read', async () => { @@ -148,7 +131,7 @@ describe('layer ladder', () => { expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) // A key sitting in the user's .env does not make the stored one // unwritable. - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) await expect(ctx.credentials.set(KEY, 'rotated')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' }) }) @@ -247,7 +230,7 @@ describe('layer ladder', () => { { source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } }, ]) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' }) }) @@ -399,7 +382,7 @@ describe('document writes', () => { const reread = await boot({ path, watch: false }) expect(await reread.credentials.resolve(KEY)).toEqual({ value: multiLine, source: 'file' }) expect(await reread.credentials.resolve(OTHER)).toEqual({ value: mixedQuotes, source: 'file' }) - expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, preview: 'line… two' }) + expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) }) it('unsets only the owning entry, with its own annotation, and keeps an absent unset silent', async () => { diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 3d4ea94773..3f2265caf7 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: d354985614dafc0d - zh: 3ff9fdd480521283 + en: fa334e2d4438e0b6 + zh: 009b9252ed046886 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 95ccc9ed8e..85ed5a68b0 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the full value. A provider may supply a masked `preview` for a managed key; ambient credentials have no preview. +Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. ### Storing, updating, and removing records diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index 8388b99c61..c73f0c68bf 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, preview?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回完整值。提供方可为托管密钥提供脱敏的 `preview`;环境凭据不提供摘要。 +用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。 ### 存储、更新与移除记录 diff --git a/packages/credentials/credentials/src/types.ts b/packages/credentials/credentials/src/types.ts index b0e2d88cb4..5c9ae99350 100644 --- a/packages/credentials/credentials/src/types.ts +++ b/packages/credentials/credentials/src/types.ts @@ -61,16 +61,14 @@ export type CredentialRecord = ApiKeyRecord | GrantRecord /** * Source and writability facts for one reference, safe for configuration UIs — - * never the full value. Providers may include a masked preview of a managed - * credential; ambient credentials do not expose a preview. + * never the value. The view has no slot a value could ride in, which is what + * lets the whole read half cross the Remote wire. */ export interface CredentialInfo { /** Whether resolving the reference would currently return a value. */ configured: boolean /** Source layer currently supplying the value; absent while unconfigured. */ source?: string - /** Masked managed value for display only; short values must be fully masked. */ - preview?: string /** Whether the active provider can write this reference. */ writable: boolean } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 242f81f8eb..74a5703129 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -6280,7 +6280,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CredentialInfo', - declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n preview?: string;\n writable: boolean;\n}', + declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}', }, { name: 'CredentialKey', diff --git a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts index b90c1a8d2b..183c590e2b 100644 --- a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts +++ b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts @@ -323,7 +323,7 @@ describe('llm-deepseek real dynamic composition', () => { const home = root! await boot.ctx.get('credentials')!.set(KEY_REF, 'stored-by-ui') expect(await boot.ctx.get('credentials')!.describe(KEY_REF)) - .toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + .toEqual({ configured: true, source: 'file', writable: true }) await assemble(boot.ctx, { model: 'deepseek-v4-flash', messages: [] }) expect(first.headers[0]?.['x-api-key']).toBe('stored-by-ui') await boot.ctx.fiber.dispose() @@ -335,7 +335,7 @@ describe('llm-deepseek real dynamic composition', () => { // The stored key is still the provider's own file entry — not a // launch-environment value, which is what hoisting it would have made it. expect(await credentials.resolve(KEY_REF)).toEqual({ value: 'stored-by-ui', source: 'file' }) - expect(await credentials.describe(KEY_REF)).toEqual({ configured: true, source: 'file', writable: true, preview: '••••••••' }) + expect(await credentials.describe(KEY_REF)).toEqual({ configured: true, source: 'file', writable: true }) // Rotation still works after the restart, and the next request uses it. await credentials.set(KEY_REF, 'rotated-after-restart') await assemble(restarted.ctx, { model: 'deepseek-v4-flash', messages: [] }) From 7d81a915773bb8d19f93bb0f1b965a082dde8453 Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 17:49:27 +0800 Subject: [PATCH 046/103] fix(settings): keep saved-key editing within the existing input --- .../tests/deepseek-messages-settings.e2e.ts | 16 ++--- .../cards.expected.md | 2 +- .../clear-key.expected.md | 1 - .../default-models.expected.md | 2 +- .../models.expected.md | 2 +- docs/user/guide/providers.i18n.yaml | 4 +- docs/user/guide/providers.md | 2 +- docs/user/guide/providers.zh.md | 2 +- .../ui-settings-models/README.i18n.yaml | 8 +-- packages/client/ui-settings-models/README.md | 4 +- .../client/ui-settings-models/README.zh.md | 4 +- .../src/client/ApiKeyInput.tsx | 6 +- .../src/client/ProviderEditor.tsx | 28 +++----- .../ui-settings-models/src/client/locales.ts | 24 ------- .../tests/components.client.spec.tsx | 67 +++++++------------ 15 files changed, 60 insertions(+), 112 deletions(-) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 232257bab3..f364b6cd72 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -83,7 +83,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' const edit = dialog.getByRole('button', { name: `编辑 ${messages ? 'DeepSeek (deepseek-official)' : provider}`, exact: true }) await edit.click() const key = dialog.getByLabel('API 密钥', { exact: true }) - await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click() + await key.press('Delete') expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() expect((await runtime.credentials.resolve(ref))?.source).toBe('file') @@ -92,7 +92,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' await dialog.getByRole('button', { name: '取消', exact: true }).click() expect((await runtime.credentials.resolve(ref))?.source).toBe('file') await edit.click() - await dialog.getByRole('button', { name: '清除已保存密钥', exact: true }).click() + await key.press('Delete') await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect.poll(() => key.count()).toBe(0) await generate() @@ -137,12 +137,13 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki const key = dialog.getByLabel('API 密钥', { exact: true }) expect(await key.getAttribute('placeholder')).toBe('••••••••') expect(await key.inputValue()).toBe('') - expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') await key.press('Backspace') await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') - await dialog.getByRole('button', { name: '撤销清除', exact: true }).click() + await dialog.getByRole('button', { name: '取消', exact: true }).click() + await edit.click() expect(await key.getAttribute('placeholder')).toBe('••••••••') await key.fill('fixture-new-key') await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() @@ -158,7 +159,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki expect(await key.getAttribute('placeholder')).toBe('••••••••') expect(await key.inputValue()).toBe('') expect(await key.getAttribute('type')).toBe('password') - expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) + expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key') } finally { try { await browser?.close() } finally { await scaffold.close() } @@ -279,9 +280,8 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett await key.fill('sk-cancelled-replacement') expect(await messages.getByText('已保存 API key', { exact: true }).count()).toBe(0) await key.fill('') - await messages.getByText('已保存 API key', { exact: true }).waitFor() - await messages.getByRole('button', { name: '保存', exact: true }).click() - await dialog.getByText('已保存 DeepSeek (deepseek-official)。', { exact: true }).waitFor() + await messages.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + await messages.getByRole('button', { name: '取消', exact: true }).click() expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) await page.keyboard.press('Escape') await connectFreshWorkspaceZh(page, scaffold.workspaceCwd, 'messages-settings-e2e') diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 16292f4f76..00047d85bc 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -16,9 +16,9 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - - button "清除已保存密钥" - textbox "API 密钥": - /placeholder: •••••••• + - button "显示密钥" [disabled] - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 diff --git a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md index 2882ca8a34..75d09113c7 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md @@ -16,7 +16,6 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - - button "撤销清除" - textbox "API 密钥": - /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY) - paragraph: 保存后清除已保存密钥,并使用环境认证 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 36c34db458..1f1f7061e3 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -16,9 +16,9 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - - button "清除已保存密钥" - textbox "API 密钥": - /placeholder: •••••••• + - button "显示密钥" [disabled] - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 2bd3311246..d929cbdc3f 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -16,9 +16,9 @@ - button "编辑 DeepSeek (deepseek-official)": 编辑 - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - - button "清除已保存密钥" - textbox "API 密钥": - /placeholder: •••••••• + - button "显示密钥" [disabled] - paragraph: 已保存 API key - group: - text: 自定义设置 API 地址 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index becdd6b82f..e45c55c920 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: c0993fb8f0131a5e - zh: 8932850d36a0f3d7 + en: 0fba478a235bd89e + zh: 74db74867f720418 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 12250389ea..e8fc46e972 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,7 +20,7 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential displays a fixed mask in the input and a green saved-key hint. The mask does not expose the key or its length. Saved keys cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Select **Clear saved key**, then **Save**, to remove the stored override and use environment authentication. **Keep saved key** or **Cancel** preserves the key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays a fixed mask in the input and a green saved-key hint. The mask does not expose the key or its length. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index a50dd918b6..7f70d7cefa 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,7 +20,7 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据在输入框中显示固定掩码,下方显示绿色的已保存密钥提示。掩码不暴露密钥或长度。已保存密钥不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。选择**清除已保存密钥**,再点**保存**,即可移除存储覆盖并使用环境认证。保存前,**撤销清除**或**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中显示固定掩码,下方显示绿色的已保存密钥提示。掩码不暴露密钥或长度。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index d63c348a8b..d7111fcbf7 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: 980f4a0dcc47c6e0 - zh: 603ea270e1b6f79d + en: 2075f43f7f5a25f9 + zh: d88830eb581067b7 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: b4f40dfd8857e64e - zh: 21486ade0dc4c259 + en: 8888adf7b6eb3997 + zh: 383da13ca0954b61 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 09f8c21558..c3ef3566fb 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,7 +41,7 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display a fixed mask as a placeholder, never a credential value or its length. They have no reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. +API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display a fixed mask as a placeholder, never a credential value or its length. They disable the existing reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. @@ -49,7 +49,7 @@ The editor uses redacted `CredentialInfo` to choose the saved-credential placeho ### Editing a provider -A blank key field preserves existing authentication. A saved credential shows a fixed input mask and a green saved-key notice. Otherwise the field offers environment authentication. **Clear saved key** stages removal until Save; Undo or Cancel preserves the key. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, without Undo; Close leaves that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +Leaving the saved mask untouched preserves existing authentication. A saved credential shows a fixed input mask and a green saved-key notice. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 20aa8a3604..9381e79119 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,7 +41,7 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥以固定掩码占位显示,不表示凭据值或长度;不提供显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 +API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥以固定掩码占位显示,不表示凭据值或长度;禁用原有显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 @@ -49,7 +49,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 ### 编辑提供商 -密钥字段留空时保留现有认证。已保存凭据显示固定的输入掩码和绿色的已保存密钥提示。否则提示使用环境认证。**清除已保存密钥**将删除操作暂存到「保存」时执行;撤销或取消会保留密钥。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;不再提供撤销,「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +保持已保存掩码不变时保留现有认证。已保存凭据显示固定的输入掩码和绿色的已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index 2a157caaa1..a9757972b1 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -32,7 +32,7 @@ export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): Re
0 ? styles['keyInputFilled'] : ''}`} + className={`${styles['input']} ${saved !== undefined || value.length > 0 ? styles['keyInputFilled'] : ''}`} type={revealed ? 'text' : 'password'} autoComplete="new-password" value={value} @@ -50,12 +50,12 @@ export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): Re props.onChange?.(event) }} /> - {value.length === 0 ? null : - : null} { setKeyDraft({ ref: removalRef }); setFailure(undefined) } } : {}, + ...detected[1].writable + ? { clear: () => { setKeyDraft({ ref: detected[0] }); setFailure(undefined) } } : {}, }, } : {}} placeholder={keyPlaceholder} @@ -512,7 +499,12 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { required={props.credentialRequired === true || protocolNeedsKeyHere} autoFocus={props.autoFocusCredential === true} disabled={disabled || keyRemoval?.removed === true} - onChange={(event) => { setKeyDraft(event.target.value); setFailure(undefined) }} + onChange={(event) => { + setKeyDraft(event.target.value === '' && savedCredential + ? detected[1].writable ? { ref: detected[0] } : undefined + : event.target.value) + setFailure(undefined) + }} /> {credentialHint === undefined ? null :

{credentialHint}

} {/* A key the protocol requires is a requirement still to meet, not a fault. */} diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index 5b7861878a..3e55c6fec9 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -41,10 +41,7 @@ export const en = { keyHide: 'Hide secret', keyPlaceholder: 'Enter your API key', keyPlaceholderFallback: 'Leave blank to use env as auth ({hint})', - keyPlaceholderSaved: 'Leave blank to keep current authentication (API key saved)', keySaved: 'API key saved', - keyRemove: 'Clear saved key', - keyRemoveUndo: 'Keep saved key', keyRemovePending: 'Save to clear the saved key and use environment authentication.', keyRemoveApplied: 'Key cleared. Retry Save to finish settings; this deletion cannot be undone.', keyFallbackMissing: 'Env var not detected. Enter an API key, or configure {hint} in your env.', @@ -222,10 +219,7 @@ export const zh: { [Key in keyof typeof en]: string } = { keyHide: '隐藏密钥', keyPlaceholder: '输入 API 密钥', keyPlaceholderFallback: '留空使用环境认证({hint})', - keyPlaceholderSaved: '留空保留现有认证(已保存 API key)', keySaved: '已保存 API key', - keyRemove: '清除已保存密钥', - keyRemoveUndo: '撤销清除', keyRemovePending: '保存后清除已保存密钥,并使用环境认证', keyRemoveApplied: '密钥已清除,请重试保存以完成配置更新;此删除无法撤销', keyFallbackMissing: '未检测到环境变量。请填写 API 密钥,或设置环境变量 {hint}。', @@ -400,10 +394,7 @@ export const ja = { 'keyHide': 'シークレットを非表示', 'keyPlaceholder': 'APIキーを入力', 'keyPlaceholderFallback': '空欄のままにすると環境変数を認証に使用します ({hint})', - 'keyPlaceholderSaved': '空欄のままにすると現在の認証を保持します(APIキー保存済み)', 'keySaved': 'APIキー保存済み', - 'keyRemove': '保存済みキーを削除', - 'keyRemoveUndo': '削除を取り消す', 'keyRemovePending': '保存すると保存済みキーを削除し、環境変数の認証を使用します。', 'keyRemoveApplied': 'キーは削除済みです。保存を再試行して設定を更新してください。削除は取り消せません。', 'keyFallbackMissing': '環境変数が検出されません。APIキーを入力するか、環境変数に{hint}を設定してください。', @@ -578,10 +569,7 @@ export const es = { keyHide: 'Ocultar secreto', keyPlaceholder: 'Ingrese su clave API', keyPlaceholderFallback: 'Déjelo en blanco para usar env como autenticación ({hint})', - keyPlaceholderSaved: 'Déjelo en blanco para conservar la autenticación actual (clave API guardada)', keySaved: 'Clave API guardada', - keyRemove: 'Borrar clave guardada', - keyRemoveUndo: 'Deshacer borrado', keyRemovePending: 'Guarde para borrar la clave guardada y usar la autenticación del entorno.', keyRemoveApplied: 'Clave borrada. Reintente guardar para completar la configuración; no se puede deshacer.', keyFallbackMissing: 'No se detectó la variable de entorno. Ingrese una clave API o configure {hint} en su entorno.', @@ -756,10 +744,7 @@ export const fr = { keyHide: 'Cacher le secret', keyPlaceholder: 'Entrez votre clé API', keyPlaceholderFallback: 'Laissez vide pour utiliser env comme authentification ({hint})', - keyPlaceholderSaved: 'Laissez vide pour conserver l’authentification actuelle (clé API enregistrée)', keySaved: 'Clé API enregistrée', - keyRemove: 'Effacer la clé enregistrée', - keyRemoveUndo: 'Annuler l’effacement', keyRemovePending: 'Enregistrez pour effacer la clé enregistrée et utiliser l’authentification de l’environnement.', keyRemoveApplied: 'Clé supprimée. Réessayez d’enregistrer pour terminer les paramètres ; la suppression est irréversible.', keyFallbackMissing: "Var d'environnement non détectée. Entrez une clé API ou configurez {hint} dans votre environnement.", @@ -934,10 +919,7 @@ export const de = { keyHide: 'Geheimnis verbergen', keyPlaceholder: 'Geben Sie Ihren API-Schlüssel ein', keyPlaceholderFallback: 'Lassen Sie das Feld leer, um env als Authentifizierung zu verwenden ({hint})', - keyPlaceholderSaved: 'Leer lassen, um die aktuelle Authentifizierung beizubehalten (API-Schlüssel gespeichert)', keySaved: 'API-Schlüssel gespeichert', - keyRemove: 'Gespeicherten Schlüssel löschen', - keyRemoveUndo: 'Löschen rückgängig machen', keyRemovePending: 'Speichern, um den gespeicherten Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.', keyRemoveApplied: 'Schlüssel gelöscht. Speichern erneut versuchen, um die Einstellungen abzuschließen; das Löschen ist unwiderruflich.', keyFallbackMissing: 'Umgebungsvariable nicht erkannt. Geben Sie einen API-Schlüssel ein oder konfigurieren Sie {hint} in Ihrer Umgebung.', @@ -1112,10 +1094,7 @@ export const ru = { keyHide: 'Скрыть секрет', keyPlaceholder: 'Введите свой ключ API', keyPlaceholderFallback: 'Оставьте пустым, чтобы использовать env в качестве аутентификации ({hint})', - keyPlaceholderSaved: 'Оставьте поле пустым, чтобы сохранить текущую аутентификацию (API-ключ сохранён)', keySaved: 'API-ключ сохранён', - keyRemove: 'Удалить сохранённый ключ', - keyRemoveUndo: 'Отменить удаление', keyRemovePending: 'Сохраните, чтобы удалить сохранённый ключ и использовать аутентификацию из окружения.', keyRemoveApplied: 'Ключ удалён. Повторите сохранение настроек; удаление нельзя отменить.', keyFallbackMissing: 'Переменная Env не обнаружена. Введите ключ API или настройте {hint} в своей среде.', @@ -1290,10 +1269,7 @@ export const pt = { keyHide: 'Ocultar segredo', keyPlaceholder: 'Insira sua chave API', keyPlaceholderFallback: 'Deixe em branco para usar env como autenticação ({hint})', - keyPlaceholderSaved: 'Deixe em branco para manter a autenticação atual (chave API salva)', keySaved: 'Chave API salva', - keyRemove: 'Limpar chave salva', - keyRemoveUndo: 'Desfazer limpeza', keyRemovePending: 'Salve para limpar a chave salva e usar a autenticação do ambiente.', keyRemoveApplied: 'Chave apagada. Tente salvar novamente para concluir as configurações; a exclusão não pode ser desfeita.', keyFallbackMissing: 'Env var não detectado. Insira uma chave API ou configure {hint} em seu ambiente.', diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index 076b625075..fd8da3d7d7 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -2221,7 +2221,7 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing expect(screen.queryByText(/^API key source:/)).toBeNull() expect(input.getAttribute('aria-describedby')).toBeNull() fireEvent.change(input, { target: { value: '' } }) - if (source === 'file') expect(screen.getByText(en.keySaved)).toBeTruthy() + if (source === 'file') expect(screen.getByText(en.keyRemovePending)).toBeTruthy() else expect(screen.getAllByText(hint)).toHaveLength(1) }) @@ -2233,7 +2233,8 @@ it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects expect(input.value).toBe('') expect(input.type).toBe('password') expect(input.placeholder).toBe('••••••••') - expect(screen.queryByLabelText(en.keyReveal)).toBeNull() + expect(screen.queryByRole('button', { name: 'Clear saved key' })).toBeNull() + expect(screen.getByRole('button', { name: en.keyReveal }).disabled).toBe(true) expect(fireEvent.copy(input)).toBe(false) expect(fireEvent.cut(input)).toBe(false) fireEvent.change(input, { target: { value: 'replacement-key' } }) @@ -2244,15 +2245,16 @@ it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects expect(fireEvent.copy(input)).toBe(true) expect(fireEvent.cut(input)).toBe(true) fireEvent.change(input, { target: { value: '' } }) - expect(screen.getByText(en.keySaved)).toBeTruthy() - expect(input.placeholder).toBe(en.keyPlaceholderSaved) + expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(input.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'TEAM_API_KEY')) expect(screen.queryByLabelText(en.keyReveal)).toBeNull() }) -it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and can undo it', async (key) => { +it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and can cancel it', async (key) => { const { unset } = await mountSection() - fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) - const input = screen.getByLabelText(en.keyInput) + const edit = () => screen.getByRole('button', { name: openaiCopy(en.editProvider) }) + fireEvent.click(edit()) + let input = screen.getByLabelText(en.keyInput) expect(input.placeholder).toBe('••••••••') fireEvent.keyDown(input, { key: 'ArrowLeft' }) expect(input.placeholder).toBe('••••••••') @@ -2260,7 +2262,10 @@ it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and ca expect(input.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) expect(screen.getByText(en.keyRemovePending)).toBeTruthy() expect(unset).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) + fireEvent.click(screen.getByRole('button', { name: en.cancel })) + expect(unset).not.toHaveBeenCalled() + fireEvent.click(edit()) + input = screen.getByLabelText(en.keyInput) expect(input.placeholder).toBe('••••••••') fireEvent.keyDown(input, { key }) fireEvent.click(screen.getByRole('button', { name: en.apply })) @@ -2275,7 +2280,9 @@ it('keeps a saved read-only credential masked when deletion is unavailable', () fireEvent.keyDown(input, { key: 'Delete' }) expect(input.placeholder).toBe('••••••••') expect(screen.queryByText(en.keyRemovePending)).toBeNull() - expect(screen.queryByRole('button', { name: en.keyRemove })).toBeNull() + fireEvent.change(input, { target: { value: 'replacement' } }) + fireEvent.change(input, { target: { value: '' } }) + expect(input.placeholder).toBe('••••••••') }) it('keeps a hidden OAuth reference out of the saved API-key controls', () => { @@ -2285,29 +2292,10 @@ it('keeps a hidden OAuth reference out of the saved API-key controls', () => { const input = screen.getByLabelText(en.keyInput) expect(input.value).toBe('') expect(input.placeholder).toBe(en.keyPlaceholder) - expect(screen.queryByRole('button', { name: en.keyRemove })).toBeNull() fireEvent.keyDown(input, { key: 'Delete' }) expect(screen.queryByText(en.keyRemovePending)).toBeNull() }) -it('stages key removal and lets Undo or Cancel retain the saved credential', async () => { - const { unset, set } = await mountSection() - fireEvent.click(screen.getByRole('button', { name: openaiCopy(en.editProvider) })) - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) - expect(screen.getByText(en.keyRemovePending)).toBeTruthy() - expect(screen.getByLabelText(en.keyInput).placeholder) - .toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) - expect(screen.queryByText(en.keySaved)).toBeNull() - expect(unset).not.toHaveBeenCalled() - fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) - expect(screen.getByText(en.keySaved)).toBeTruthy() - expect(screen.getByLabelText(en.keyInput).placeholder).toBe('••••••••') - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) - fireEvent.click(screen.getByRole('button', { name: en.cancel })) - expect(unset).not.toHaveBeenCalled() - expect(set).not.toHaveBeenCalled() -}) - it.each([ ['google', 'GOOGLE_API_KEY', { env: ['GEMINI_API_KEY'], oauth: false }, true], ['openai', 'TEAM_API_KEY', { env: ['OPENAI_API_KEY'], oauth: false }, false], @@ -2320,7 +2308,7 @@ it.each([ settingsPath={['providers', provider]} schema={settingsSchema} operations={operationsWith(face)} t={t} readOnly={false} onClose={closed} {...nativeAuth === undefined ? {} : { nativeAuth }} credential={{ configured: true, source: 'file', writable: true }} />) - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) expect(screen.getByLabelText(en.keyInput).placeholder) .toBe(en.keyPlaceholderFallback.replace('{hint}', removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref)) fireEvent.click(screen.getByText(en.customized)) @@ -2334,7 +2322,7 @@ it.each([ else expect(mutate).not.toHaveBeenCalled() }) -it.each(['undo', 'cancel', 'replace'])('keeps authentication unchanged after refused deletion, then %s', async (action) => { +it.each(['cancel', 'replace'])('keeps authentication unchanged after refused deletion, then %s', async (action) => { const { face, unset, set, mutate } = scriptedFace({ unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))), }) @@ -2344,7 +2332,7 @@ it.each(['undo', 'cancel', 'replace'])('keeps authentication unchanged after ref settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)} t={t} readOnly={false} onClose={closed} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }} credential={{ configured: true, source: 'file', writable: true }} />) - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('credential store locked') expect(mutate).not.toHaveBeenCalled() @@ -2353,17 +2341,11 @@ it.each(['undo', 'cancel', 'replace'])('keeps authentication unchanged after ref fireEvent.click(screen.getByRole('button', { name: en.cancel })) expect(closed).toHaveBeenCalledWith(false) } else { - if (action === 'undo') { - fireEvent.click(screen.getByRole('button', { name: en.keyRemoveUndo })) - expect(screen.getByLabelText(en.keyInput).placeholder).toBe('••••••••') - } else { - fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } }) - } + fireEvent.change(screen.getByLabelText(en.keyInput), { target: { value: 'new-key' } }) expect(screen.queryByText('credential store locked')).toBeNull() fireEvent.click(screen.getByRole('button', { name: en.apply })) await waitFor(() => { expect(closed).toHaveBeenCalledWith(true) }) - if (action === 'replace') expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') - else expect(set).not.toHaveBeenCalled() + expect(set).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY', 'new-key') } expect(unset).toHaveBeenCalledExactlyOnceWith('GOOGLE_API_KEY') expect(mutate).not.toHaveBeenCalled() @@ -2380,11 +2362,10 @@ it.each(['retry', 'close'])('reports a completed deletion when settings fail, th settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)} t={t} readOnly={false} onClose={closed} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }} credential={{ configured: true, source: 'file', writable: true }} />) - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('settings locked') expect(screen.getByText(en.keyRemoveApplied)).toBeTruthy() - expect(screen.queryByRole('button', { name: en.keyRemoveUndo })).toBeNull() expect(screen.getByLabelText(en.keyInput).disabled).toBe(true) if (action === 'retry') { fireEvent.click(screen.getByRole('button', { name: en.apply })) @@ -2406,7 +2387,7 @@ it('clears the selected reference when refreshed metadata names a different cred t, readOnly: false, onClose: vi.fn(), credential: { configured: true, source: 'file', writable: true }, } const view = render() - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) view.rerender() fireEvent.click(screen.getByRole('button', { name: en.apply })) await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('OLD_KEY') }) @@ -2419,7 +2400,7 @@ it('clears the detected native key instead of an unused derived reference', asyn settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)} t={t} readOnly={false} onClose={vi.fn()} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }} credentialChecks={{ GEMINI_API_KEY: { configured: true, source: 'file', writable: true } }} />) - fireEvent.click(screen.getByRole('button', { name: en.keyRemove })) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('GEMINI_API_KEY') }) expect(mutate).not.toHaveBeenCalled() From 1fa3a9d19111e8c9a02aa90f175a71933f70b311 Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 20:11:09 +0800 Subject: [PATCH 047/103] fix(settings): explain saved-key actions and environment fallback --- .../tests/deepseek-messages-settings.e2e.ts | 14 +++-- .../cards.expected.md | 2 +- .../clear-key.expected.md | 2 +- .../default-models.expected.md | 2 +- .../models.expected.md | 2 +- docs/user/guide/providers.i18n.yaml | 4 +- docs/user/guide/providers.md | 2 +- docs/user/guide/providers.zh.md | 2 +- .../ui-settings-models/README.i18n.yaml | 4 +- packages/client/ui-settings-models/README.md | 2 +- .../client/ui-settings-models/README.zh.md | 2 +- .../src/client/ProviderEditor.tsx | 21 ++++--- .../ui-settings-models/src/client/locales.ts | 62 ++++++++++++------- .../tests/components.client.spec.tsx | 30 +++++++-- 14 files changed, 95 insertions(+), 56 deletions(-) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index f364b6cd72..2c29f0ca0e 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -85,7 +85,7 @@ it.skipIf(webSnapshotMode() === 'record').each(['deepseek-official', 'google', ' const key = dialog.getByLabel('API 密钥', { exact: true }) await key.press('Delete') expect(await key.getAttribute('placeholder')).toBe(`留空使用环境认证(${envRef})`) - await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + await dialog.getByText(`保存以清除已保存的 API key。之后使用环境认证(${envRef})。`, { exact: true }).waitFor() expect((await runtime.credentials.resolve(ref))?.source).toBe('file') if (messages) await compareOrRefreshGolden(join(EXPECTED, 'clear-key.expected.md'), await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode()) @@ -140,12 +140,13 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') await key.press('Backspace') - await dialog.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + await dialog.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') await dialog.getByRole('button', { name: '取消', exact: true }).click() await edit.click() expect(await key.getAttribute('placeholder')).toBe('••••••••') await key.fill('fixture-new-key') + await dialog.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() expect(await key.getAttribute('type')).toBe('text') expect(await key.inputValue()).toBe('fixture-new-key') @@ -248,7 +249,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const key = messages.getByLabel('API 密钥', { exact: true }) expect(await key.inputValue()).toBe('') expect(await key.getAttribute('placeholder')).toBe('••••••••') - await messages.getByText('已保存 API key', { exact: true }).waitFor() + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) .toBe('https://api.deepseek.com/anthropic(默认使用环境 DEEPSEEK_BASE_URL)') @@ -275,12 +276,13 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett expect(await page.locator('body').innerText()).not.toContain('sk-e2e-') await dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }).click() expect(await key.inputValue()).toBe('') - await messages.getByText('已保存 API key', { exact: true }).waitFor() + await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() expect(await key.getAttribute('type')).toBe('password') await key.fill('sk-cancelled-replacement') - expect(await messages.getByText('已保存 API key', { exact: true }).count()).toBe(0) + await messages.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() + expect(await messages.getByText('使用已保存的 API key。', { exact: true }).count()).toBe(0) await key.fill('') - await messages.getByText('保存后清除已保存密钥,并使用环境认证', { exact: true }).waitFor() + await messages.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() await messages.getByRole('button', { name: '取消', exact: true }).click() expect(await readFile(join(scaffold.harnessHome, '.credentials.yaml'), 'utf8')).toBe(credentials) await page.keyboard.press('Escape') diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 00047d85bc..a3878a3bdf 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -19,7 +19,7 @@ - textbox "API 密钥": - /placeholder: •••••••• - button "显示密钥" [disabled] - - paragraph: 已保存 API key + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md index 75d09113c7..b1c8c2f328 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/clear-key.expected.md @@ -18,7 +18,7 @@ - button "认证说明": "?" - textbox "API 密钥": - /placeholder: 留空使用环境认证(DEEPSEEK_API_KEY) - - paragraph: 保存后清除已保存密钥,并使用环境认证 + - paragraph: 保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。 - group: 自定义设置 - button "取消" - button "保存" diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 1f1f7061e3..003f32f36d 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -19,7 +19,7 @@ - textbox "API 密钥": - /placeholder: •••••••• - button "显示密钥" [disabled] - - paragraph: 已保存 API key + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index d929cbdc3f..43cbbb0f28 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -19,7 +19,7 @@ - textbox "API 密钥": - /placeholder: •••••••• - button "显示密钥" [disabled] - - paragraph: 已保存 API key + - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 - textbox "API 地址": diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index e45c55c920..ddb8a4c70a 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: 0fba478a235bd89e - zh: 74db74867f720418 + en: e813f9e5aaa213fc + zh: 2257b5b45b9f54b5 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index e8fc46e972..8509e4ce30 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,7 +20,7 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential displays a fixed mask in the input and a green saved-key hint. The mask does not expose the key or its length. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A nonempty input shows no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays a fixed mask in the input and a green hint that the saved key will be used. The mask does not expose the key or its length. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index 7f70d7cefa..af8f80bcf7 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,7 +20,7 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据在输入框中显示固定掩码,下方显示绿色的已保存密钥提示。掩码不暴露密钥或长度。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。输入非空时,不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中显示固定掩码,下方显示绿色的使用已保存密钥提示。掩码不暴露密钥或长度。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index d7111fcbf7..5cb4d4bc1f 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2075f43f7f5a25f9 zh: d88830eb581067b7 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 8888adf7b6eb3997 - zh: 383da13ca0954b61 + en: 6756a578138e88bf + zh: 371611209d82149d /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index c3ef3566fb..a4baf12d9e 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -49,7 +49,7 @@ The editor uses redacted `CredentialInfo` to choose the saved-credential placeho ### Editing a provider -Leaving the saved mask untouched preserves existing authentication. A saved credential shows a fixed input mask and a green saved-key notice. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A nonempty input shows no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +Leaving the saved mask untouched preserves existing authentication. A saved credential shows a fixed input mask and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 9381e79119..5ab65ddae9 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -49,7 +49,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 ### 编辑提供商 -保持已保存掩码不变时保留现有认证。已保存凭据显示固定的输入掩码和绿色的已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。输入非空时,不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +保持已保存掩码不变时保留现有认证。已保存凭据显示固定的输入掩码和绿色的使用已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index bb44d66e58..2a88a6179c 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -441,15 +441,18 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { const detectedVisibleRef = detectedRef === undefined || !visibleRefs.includes(detectedRef) ? undefined : detectedRef const missingRefs = checkedRefs.length > 0 && checkedRefs.every(([, info]) => info?.configured === false) const savedCredential = detected?.[1]?.source === 'file' && detectedVisibleRef !== undefined - const credentialHint = keyText.length > 0 || props.credentialRequired === true + const credentialHint = props.credentialRequired === true ? undefined - : keyRemoval !== undefined ? t(keyRemoval.removed === true ? 'keyRemoveApplied' : 'keyRemovePending') - : keyHint === undefined ? undefined - : savedCredential - ? t('keySaved') - : t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked' - : detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected') - .replace('{hint}', () => detectedVisibleRef ?? keyHint) + : keyText.length > 0 ? savedCredential ? t('keyReplacePending') : undefined + : keyRemoval !== undefined ? keyRemoval.removed === true ? t('keyRemoveApplied') + : keyHint === undefined ? t('keyRemovePending') + : t('keyRemovePendingEnvironment').replace('{hint}', () => keyHint) + : keyHint === undefined ? undefined + : savedCredential + ? t('keySaved') + : t(detectedRef === undefined ? missingRefs ? 'keyFallbackMissing' : 'keyFallbackUnchecked' + : detectedVisibleRef === undefined ? 'keyFallbackDetectedHidden' : 'keyFallbackDetected') + .replace('{hint}', () => detectedVisibleRef ?? keyHint) const keyHelp = visibleRefs.length === 0 ? undefined : t('keyHelp').replace('{env}', () => visibleRefs.join(' / ')) @@ -506,7 +509,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { setFailure(undefined) }} /> - {credentialHint === undefined ? null :

{credentialHint}

} + {credentialHint === undefined ? null :

0 || detectedRef === undefined ? 'advancedHint' : 'savedNotice']}>{credentialHint}

} {/* A key the protocol requires is a requirement still to meet, not a fault. */} {shownKeyFailure === undefined ? null diff --git a/packages/client/ui-settings-models/src/client/locales.ts b/packages/client/ui-settings-models/src/client/locales.ts index 3e55c6fec9..5dec1bdac3 100644 --- a/packages/client/ui-settings-models/src/client/locales.ts +++ b/packages/client/ui-settings-models/src/client/locales.ts @@ -41,9 +41,11 @@ export const en = { keyHide: 'Hide secret', keyPlaceholder: 'Enter your API key', keyPlaceholderFallback: 'Leave blank to use env as auth ({hint})', - keySaved: 'API key saved', - keyRemovePending: 'Save to clear the saved key and use environment authentication.', - keyRemoveApplied: 'Key cleared. Retry Save to finish settings; this deletion cannot be undone.', + keySaved: 'Use the existing saved API key.', + keyReplacePending: 'Apply to replace the saved API key.', + keyRemovePending: 'Apply to clear the saved API key and use environment authentication.', + keyRemovePendingEnvironment: 'Apply to clear the saved API key. Environment authentication will be used ({hint}).', + keyRemoveApplied: 'Key cleared. Apply again to finish settings; this deletion cannot be undone.', keyFallbackMissing: 'Env var not detected. Enter an API key, or configure {hint} in your env.', keyFallbackDetected: 'Env var detected. ({hint})', keyFallbackDetectedHidden: 'Env var detected.', @@ -219,8 +221,10 @@ export const zh: { [Key in keyof typeof en]: string } = { keyHide: '隐藏密钥', keyPlaceholder: '输入 API 密钥', keyPlaceholderFallback: '留空使用环境认证({hint})', - keySaved: '已保存 API key', - keyRemovePending: '保存后清除已保存密钥,并使用环境认证', + keySaved: '使用已保存的 API key。', + keyReplacePending: '保存以替换已保存的 API key。', + keyRemovePending: '保存以清除已保存的 API key,并改用环境认证。', + keyRemovePendingEnvironment: '保存以清除已保存的 API key。之后使用环境认证({hint})。', keyRemoveApplied: '密钥已清除,请重试保存以完成配置更新;此删除无法撤销', keyFallbackMissing: '未检测到环境变量。请填写 API 密钥,或设置环境变量 {hint}。', keyFallbackDetected: '已检测到环境变量({hint})', @@ -394,9 +398,11 @@ export const ja = { 'keyHide': 'シークレットを非表示', 'keyPlaceholder': 'APIキーを入力', 'keyPlaceholderFallback': '空欄のままにすると環境変数を認証に使用します ({hint})', - 'keySaved': 'APIキー保存済み', - 'keyRemovePending': '保存すると保存済みキーを削除し、環境変数の認証を使用します。', - 'keyRemoveApplied': 'キーは削除済みです。保存を再試行して設定を更新してください。削除は取り消せません。', + 'keySaved': '保存済みのAPIキーを使用します。', + 'keyReplacePending': '適用すると保存済みのAPIキーを置き換えます。', + 'keyRemovePending': '適用すると保存済みのAPIキーを削除し、環境変数の認証を使用します。', + 'keyRemovePendingEnvironment': '適用すると保存済みのAPIキーを削除します。その後、環境変数の認証({hint})を使用します。', + 'keyRemoveApplied': 'キーは削除済みです。再度適用して設定を更新してください。削除は取り消せません。', 'keyFallbackMissing': '環境変数が検出されません。APIキーを入力するか、環境変数に{hint}を設定してください。', 'keyFallbackDetected': '環境変数を検出しました。({hint})', 'keyFallbackDetectedHidden': '環境変数を検出しました。', @@ -569,9 +575,11 @@ export const es = { keyHide: 'Ocultar secreto', keyPlaceholder: 'Ingrese su clave API', keyPlaceholderFallback: 'Déjelo en blanco para usar env como autenticación ({hint})', - keySaved: 'Clave API guardada', - keyRemovePending: 'Guarde para borrar la clave guardada y usar la autenticación del entorno.', - keyRemoveApplied: 'Clave borrada. Reintente guardar para completar la configuración; no se puede deshacer.', + keySaved: 'Se usará la clave API guardada.', + keyReplacePending: 'Aplique para reemplazar la clave API guardada.', + keyRemovePending: 'Aplique para borrar la clave API guardada y usar la autenticación del entorno.', + keyRemovePendingEnvironment: 'Aplique para borrar la clave API guardada. Se usará la autenticación del entorno ({hint}).', + keyRemoveApplied: 'Clave borrada. Aplique de nuevo para completar la configuración; no se puede deshacer.', keyFallbackMissing: 'No se detectó la variable de entorno. Ingrese una clave API o configure {hint} en su entorno.', keyFallbackDetected: 'Se detectó var env. ({hint})', keyFallbackDetectedHidden: 'Se detectó var env.', @@ -744,9 +752,11 @@ export const fr = { keyHide: 'Cacher le secret', keyPlaceholder: 'Entrez votre clé API', keyPlaceholderFallback: 'Laissez vide pour utiliser env comme authentification ({hint})', - keySaved: 'Clé API enregistrée', - keyRemovePending: 'Enregistrez pour effacer la clé enregistrée et utiliser l’authentification de l’environnement.', - keyRemoveApplied: 'Clé supprimée. Réessayez d’enregistrer pour terminer les paramètres ; la suppression est irréversible.', + keySaved: 'La clé API enregistrée sera utilisée.', + keyReplacePending: 'Appliquez pour remplacer la clé API enregistrée.', + keyRemovePending: 'Appliquez pour effacer la clé API enregistrée et utiliser l’authentification de l’environnement.', + keyRemovePendingEnvironment: 'Appliquez pour effacer la clé API enregistrée. L’authentification de l’environnement sera utilisée ({hint}).', + keyRemoveApplied: 'Clé supprimée. Appliquez à nouveau pour terminer les paramètres ; la suppression est irréversible.', keyFallbackMissing: "Var d'environnement non détectée. Entrez une clé API ou configurez {hint} dans votre environnement.", keyFallbackDetected: "Var d'environnement détectée. ({hint})", keyFallbackDetectedHidden: "Var d'environnement détectée.", @@ -919,9 +929,11 @@ export const de = { keyHide: 'Geheimnis verbergen', keyPlaceholder: 'Geben Sie Ihren API-Schlüssel ein', keyPlaceholderFallback: 'Lassen Sie das Feld leer, um env als Authentifizierung zu verwenden ({hint})', - keySaved: 'API-Schlüssel gespeichert', - keyRemovePending: 'Speichern, um den gespeicherten Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.', - keyRemoveApplied: 'Schlüssel gelöscht. Speichern erneut versuchen, um die Einstellungen abzuschließen; das Löschen ist unwiderruflich.', + keySaved: 'Der gespeicherte API-Schlüssel wird verwendet.', + keyReplacePending: 'Anwenden, um den gespeicherten API-Schlüssel zu ersetzen.', + keyRemovePending: 'Anwenden, um den gespeicherten API-Schlüssel zu löschen und die Umgebungsauthentifizierung zu verwenden.', + keyRemovePendingEnvironment: 'Anwenden, um den gespeicherten API-Schlüssel zu löschen. Danach wird die Umgebungsauthentifizierung verwendet ({hint}).', + keyRemoveApplied: 'Schlüssel gelöscht. Erneut anwenden, um die Einstellungen abzuschließen; das Löschen ist unwiderruflich.', keyFallbackMissing: 'Umgebungsvariable nicht erkannt. Geben Sie einen API-Schlüssel ein oder konfigurieren Sie {hint} in Ihrer Umgebung.', keyFallbackDetected: 'Umgebungsvariable erkannt. ({hint})', keyFallbackDetectedHidden: 'Umgebungsvariable erkannt.', @@ -1094,9 +1106,11 @@ export const ru = { keyHide: 'Скрыть секрет', keyPlaceholder: 'Введите свой ключ API', keyPlaceholderFallback: 'Оставьте пустым, чтобы использовать env в качестве аутентификации ({hint})', - keySaved: 'API-ключ сохранён', - keyRemovePending: 'Сохраните, чтобы удалить сохранённый ключ и использовать аутентификацию из окружения.', - keyRemoveApplied: 'Ключ удалён. Повторите сохранение настроек; удаление нельзя отменить.', + keySaved: 'Используется сохранённый API-ключ.', + keyReplacePending: 'Примените, чтобы заменить сохранённый API-ключ.', + keyRemovePending: 'Примените, чтобы удалить сохранённый API-ключ и использовать аутентификацию из окружения.', + keyRemovePendingEnvironment: 'Примените, чтобы удалить сохранённый API-ключ. Будет использована аутентификация из окружения ({hint}).', + keyRemoveApplied: 'Ключ удалён. Примените ещё раз для завершения настройки; удаление нельзя отменить.', keyFallbackMissing: 'Переменная Env не обнаружена. Введите ключ API или настройте {hint} в своей среде.', keyFallbackDetected: 'Обнаружена переменная Env. ({hint})', keyFallbackDetectedHidden: 'Обнаружена переменная Env.', @@ -1269,9 +1283,11 @@ export const pt = { keyHide: 'Ocultar segredo', keyPlaceholder: 'Insira sua chave API', keyPlaceholderFallback: 'Deixe em branco para usar env como autenticação ({hint})', - keySaved: 'Chave API salva', - keyRemovePending: 'Salve para limpar a chave salva e usar a autenticação do ambiente.', - keyRemoveApplied: 'Chave apagada. Tente salvar novamente para concluir as configurações; a exclusão não pode ser desfeita.', + keySaved: 'A chave API salva será usada.', + keyReplacePending: 'Aplique para substituir a chave API salva.', + keyRemovePending: 'Aplique para limpar a chave API salva e usar a autenticação do ambiente.', + keyRemovePendingEnvironment: 'Aplique para limpar a chave API salva. A autenticação do ambiente será usada ({hint}).', + keyRemoveApplied: 'Chave apagada. Aplique novamente para concluir as configurações; a exclusão não pode ser desfeita.', keyFallbackMissing: 'Env var não detectado. Insira uma chave API ou configure {hint} em seu ambiente.', keyFallbackDetected: 'Variável de ambiente detectada. ({hint})', keyFallbackDetectedHidden: 'Variável de ambiente detectada.', diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index fd8da3d7d7..ef24386913 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -2219,9 +2219,14 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing fireEvent.change(input, { target: { value: 'new-key' } }) expect(screen.queryByText(hint)).toBeNull() expect(screen.queryByText(/^API key source:/)).toBeNull() - expect(input.getAttribute('aria-describedby')).toBeNull() + if (source === 'file') { + expect(document.getElementById(input.getAttribute('aria-describedby')!)?.textContent).toBe(en.keyReplacePending) + } else { + expect(screen.queryByText(en.keyReplacePending)).toBeNull() + expect(input.getAttribute('aria-describedby')).toBeNull() + } fireEvent.change(input, { target: { value: '' } }) - if (source === 'file') expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + if (source === 'file') expect(screen.getByText(en.keyRemovePendingEnvironment.replace('{hint}', 'OPENAI_API_KEY'))).toBeTruthy() else expect(screen.getAllByText(hint)).toHaveLength(1) }) @@ -2239,13 +2244,14 @@ it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects expect(fireEvent.cut(input)).toBe(false) fireEvent.change(input, { target: { value: 'replacement-key' } }) expect(screen.queryByText(en.keySaved)).toBeNull() + expect(document.getElementById(input.getAttribute('aria-describedby')!)?.textContent).toBe(en.keyReplacePending) fireEvent.click(screen.getByRole('button', { name: en.keyReveal })) expect(input.type).toBe('text') expect(input.value).toBe('replacement-key') expect(fireEvent.copy(input)).toBe(true) expect(fireEvent.cut(input)).toBe(true) fireEvent.change(input, { target: { value: '' } }) - expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(screen.getByText(en.keyRemovePendingEnvironment.replace('{hint}', 'TEAM_API_KEY'))).toBeTruthy() expect(input.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'TEAM_API_KEY')) expect(screen.queryByLabelText(en.keyReveal)).toBeNull() }) @@ -2260,7 +2266,7 @@ it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and ca expect(input.placeholder).toBe('••••••••') fireEvent.keyDown(input, { key }) expect(input.placeholder).toBe(en.keyPlaceholderFallback.replace('{hint}', 'OPENAI_API_KEY')) - expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(screen.getByText(en.keyRemovePendingEnvironment.replace('{hint}', 'OPENAI_API_KEY'))).toBeTruthy() expect(unset).not.toHaveBeenCalled() fireEvent.click(screen.getByRole('button', { name: en.cancel })) expect(unset).not.toHaveBeenCalled() @@ -2309,8 +2315,10 @@ it.each([ t={t} readOnly={false} onClose={closed} {...nativeAuth === undefined ? {} : { nativeAuth }} credential={{ configured: true, source: 'file', writable: true }} />) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) + const envRef = removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref expect(screen.getByLabelText(en.keyInput).placeholder) - .toBe(en.keyPlaceholderFallback.replace('{hint}', removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref)) + .toBe(en.keyPlaceholderFallback.replace('{hint}', envRef)) + expect(screen.getByText(en.keyRemovePendingEnvironment.replace('{hint}', envRef))).toBeTruthy() fireEvent.click(screen.getByText(en.customized)) expect(screen.getByRole('button', { name: en.fetchModels }).disabled).toBe(true) fireEvent.click(screen.getByRole('button', { name: en.apply })) @@ -2322,6 +2330,16 @@ it.each([ else expect(mutate).not.toHaveBeenCalled() }) +it('keeps the clear hint generic when native authentication has no visible environment reference', () => { + renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { + nativeAuth: { env: [], oauth: false }, + credential: { configured: true, source: 'file', writable: true }, + }) + fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) + expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(screen.getByLabelText(en.keyInput).placeholder).toBe(en.keyPlaceholder) +}) + it.each(['cancel', 'replace'])('keeps authentication unchanged after refused deletion, then %s', async (action) => { const { face, unset, set, mutate } = scriptedFace({ unset: vi.fn(() => Promise.resolve(remoteFail('credential store locked'))), @@ -2336,7 +2354,7 @@ it.each(['cancel', 'replace'])('keeps authentication unchanged after refused del fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('credential store locked') expect(mutate).not.toHaveBeenCalled() - expect(screen.getByText(en.keyRemovePending)).toBeTruthy() + expect(screen.getByText(en.keyRemovePendingEnvironment.replace('{hint}', 'GEMINI_API_KEY'))).toBeTruthy() if (action === 'cancel') { fireEvent.click(screen.getByRole('button', { name: en.cancel })) expect(closed).toHaveBeenCalledWith(false) From ef3a02167a0cfd2a25c571072fcd1544bb9089cc Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 20:31:45 +0800 Subject: [PATCH 048/103] fix(settings): preserve saved API key mask length --- .../tests/deepseek-messages-settings.e2e.ts | 8 ++-- .../cards.expected.md | 2 +- .../default-models.expected.md | 2 +- .../models.expected.md | 2 +- apps/web/tests/models-settings.e2e.ts | 2 +- .../tests/onboarding-deepseek-config.e2e.ts | 7 ++-- docs/event-producer-consumer.md | 4 +- docs/event-producer-consumer.zh.md | 4 +- docs/subsystems/credentials.i18n.yaml | 4 +- docs/subsystems/credentials.md | 6 ++- docs/subsystems/credentials.zh.md | 6 ++- docs/user/guide/providers.i18n.yaml | 4 +- docs/user/guide/providers.md | 2 +- docs/user/guide/providers.zh.md | 2 +- .../api/settings-controller/README.i18n.yaml | 4 +- packages/api/settings-controller/README.md | 2 +- packages/api/settings-controller/README.zh.md | 2 +- .../settings-controller/src/credentials.ts | 1 + .../tests/credentials-controller.host.spec.ts | 5 ++- .../ui-settings-models/README.i18n.yaml | 8 ++-- packages/client/ui-settings-models/README.md | 4 +- .../client/ui-settings-models/README.zh.md | 4 +- .../src/client/ApiKeyInput.tsx | 5 ++- .../src/client/ProviderEditor.tsx | 1 + .../tests/components.client.spec.tsx | 41 ++++++++++++------- .../credentials-local/README.i18n.yaml | 4 +- .../credentials/credentials-local/README.md | 4 +- .../credentials-local/README.zh.md | 4 +- .../credentials-local/src/index.ts | 2 +- .../credentials-local/tests/local.spec.ts | 15 ++++--- .../credentials/credentials/README.i18n.yaml | 4 +- packages/credentials/credentials/README.md | 4 +- packages/credentials/credentials/README.zh.md | 4 +- packages/credentials/credentials/src/index.ts | 2 +- packages/credentials/credentials/src/types.ts | 2 + .../extensions/tool-cordis/src/api-catalog.ts | 4 +- .../tests/loader-composition.spec.ts | 7 +++- 37 files changed, 108 insertions(+), 80 deletions(-) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 2c29f0ca0e..3d88fdbf6c 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -135,7 +135,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki const edit = dialog.getByRole('button', { name: '编辑 DeepSeek (deepseek-official)', exact: true }) await edit.click() const key = dialog.getByLabel('API 密钥', { exact: true }) - expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-protected-old-key'.length)) expect(await key.inputValue()).toBe('') expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') @@ -144,7 +144,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki expect(await key.getAttribute('placeholder')).toBe('留空使用环境认证(DEEPSEEK_API_KEY)') await dialog.getByRole('button', { name: '取消', exact: true }).click() await edit.click() - expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-protected-old-key'.length)) await key.fill('fixture-new-key') await dialog.getByText('保存以替换已保存的 API key。', { exact: true }).waitFor() await dialog.getByRole('button', { name: '显示密钥', exact: true }).click() @@ -157,7 +157,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki await dialog.getByRole('button', { name: '保存', exact: true }).click() await expect.poll(() => key.count()).toBe(0) await edit.click() - expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length)) expect(await key.inputValue()).toBe('') expect(await key.getAttribute('type')).toBe('password') expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) @@ -248,7 +248,7 @@ describe.skipIf(webSnapshotMode() === 'record')('web e2e: DeepSeek Messages sett const messages = dialog const key = messages.getByLabel('API 密钥', { exact: true }) expect(await key.inputValue()).toBe('') - expect(await key.getAttribute('placeholder')).toBe('••••••••') + expect(await key.getAttribute('placeholder')).toBe('•'.repeat('sk-messages-onboarding'.length)) await messages.getByText('使用已保存的 API key。', { exact: true }).waitFor() await messages.getByText('自定义设置', { exact: true }).click() expect(await messages.getByLabel('API 地址', { exact: true }).getAttribute('placeholder')) diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index a3878a3bdf..1304d5467b 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -17,7 +17,7 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: •••••••• + - /placeholder: •••••••••••••••••••••• - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 003f32f36d..40f08ec904 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -17,7 +17,7 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: •••••••• + - /placeholder: •••••••••••••••••••••••••••••••••••••••••••• - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 43cbbb0f28..509fbd7745 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -17,7 +17,7 @@ - text: DeepSeek deepseek-official API 密钥 - button "认证说明": "?" - textbox "API 密钥": - - /placeholder: •••••••• + - /placeholder: •••••••••••••••••••••••••••••••••••••••••••• - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: diff --git a/apps/web/tests/models-settings.e2e.ts b/apps/web/tests/models-settings.e2e.ts index 8ab5654d88..d467ccc230 100644 --- a/apps/web/tests/models-settings.e2e.ts +++ b/apps/web/tests/models-settings.e2e.ts @@ -221,7 +221,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-models-customized')) const dialog = page.getByRole('dialog', { name: '设置' }) await dialog.getByRole('button', { name: '编辑 minimax-cn' }).click() - await dialog.getByPlaceholder('••••••••', { exact: true }).waitFor({ timeout: 10_000 }) + await dialog.getByPlaceholder('•'.repeat('sk-e2e-minimax'.length), { exact: true }).waitFor({ timeout: 10_000 }) expect(await dialog.textContent()).not.toContain('API 密钥来源:') expect(await dialog.textContent()).not.toMatch(/oauth/i) await dialog.getByText('自定义设置').click() diff --git a/apps/web/tests/onboarding-deepseek-config.e2e.ts b/apps/web/tests/onboarding-deepseek-config.e2e.ts index b8a66b6600..70efd8dbb2 100644 --- a/apps/web/tests/onboarding-deepseek-config.e2e.ts +++ b/apps/web/tests/onboarding-deepseek-config.e2e.ts @@ -33,6 +33,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup let page: Page let tripwire: ReturnType const browserConsole: string[] = [] + const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test` beforeAll(async () => { scaffold = await launchWebScaffold({ deepSeekMissingCredential: true, welcomeNoticePending: true }) @@ -86,8 +87,6 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup const initial = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MISSING_EXPECTED, initial, MODE) - // Keep the displayed prefix and suffix stable while the credential remains unique. - const secret = `dsh_onboarding_${randomBytes(12).toString('hex')}_test` await keyInput.fill(secret) await credentialStep.getByRole('button', { name: '保存并继续' }).click() await credentialStep.waitFor({ state: 'detached', timeout: 15_000 }) @@ -116,7 +115,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => configuredInput.getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('••••••••') + ).toBe('•'.repeat(secret.length)) const secondReloadWarnings = tripwire.warnings.length await page.reload({ waitUntil: 'load' }) @@ -258,7 +257,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup await expect.poll( () => settings.getByLabel('API 密钥', { exact: true }).getAttribute('placeholder'), { timeout: 10_000 }, - ).toBe('••••••••') + ).toBe('•'.repeat(secret.length)) const modelEditor = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) await compareOrRefreshGolden(MODELS_EXPECTED, modelEditor, MODE) await settings.getByRole('button', { name: '保存', exact: true }).click() diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 7e1a837be5..f309851827 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -40,8 +40,8 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index 85f0623eaf..2924a21051 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -42,8 +42,8 @@ | `cordis/inspect-query-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:401`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:371`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | | `cordis/request-run-resolved` | `emit` | [`packages/extensions/cordis-host-runner/src/types.ts:377`](../packages/extensions/cordis-host-runner/src/types.ts) | [`cordis-host-runner`](../packages/extensions/cordis-host-runner) (`emit`) | `remotes` | -| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:99`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | -| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:87`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | +| `credentials/record-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:101`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`authorization`](../packages/credentials/authorization), [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform), `remotes` | +| `credentials/reference-updated` | `emit` | [`packages/credentials/credentials/src/types.ts:89`](../packages/credentials/credentials/src/types.ts) | [`credentials`](../packages/credentials/credentials) (`events.dispatch`) | [`mcp-client`](../packages/mcp/mcp-client), `remotes` | | `deepseek-account/model-sign-in-required` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:97`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account`](../packages/credentials/deepseek-account) (`emit`) | `remotes` | | `deepseek-account/session-expired` | `emit` | [`packages/credentials/deepseek-account/src/types.ts:93`](../packages/credentials/deepseek-account/src/types.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | `account-controller`, `remotes` | | `deepseek-account/signed-out` | `emit` | [`packages/credentials/deepseek-account/src/index.ts:12`](../packages/credentials/deepseek-account/src/index.ts) | [`deepseek-account-platform`](../packages/credentials/deepseek-account-platform) (`emit`) | [`deepseek-account`](../packages/credentials/deepseek-account) | diff --git a/docs/subsystems/credentials.i18n.yaml b/docs/subsystems/credentials.i18n.yaml index bad9827407..ee4f21fa62 100644 --- a/docs/subsystems/credentials.i18n.yaml +++ b/docs/subsystems/credentials.i18n.yaml @@ -12,8 +12,8 @@ en: baaab4bca76bea6b zh: 54ccdc03ffd44f63 /user-credentials/description: - en: f7b09588c0f34952 - zh: 1b93d673c5bf6a80 + en: ee7e06c97c9e8fed + zh: fefff12b380ac76b /user-credentials/change-commits: en: 464315a953330eb2 zh: d9815591f3abc2cb diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index 2a084fb29f..2776b3fe2d 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -32,7 +32,7 @@ interface ResolvedCredential { ## Description -`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. +`describe(ref)` answers configuration surfaces without ever exposing a value: whether the reference resolves, from which layer, and whether `set` would currently succeed. The optional `length` discloses the stored value’s UTF-16 length without key characters. The local provider ranks its managed file above the launch environment, so saving a value always creates the effective writable layer; removing it reveals the launch environment or `.env` fallback again. ```ts type-equiv /** @@ -47,6 +47,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Stored value length in UTF-16 code units, when disclosed; never the value. */ + length?: number } ``` @@ -156,7 +158,7 @@ abstract resolve(ref: CredentialRef): Promise * Describe one reference for configuration surfaces without exposing the * value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional stored-value length. */ abstract describe(ref: CredentialRef): Promise diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 1e9221699a..895af599a9 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -32,7 +32,7 @@ interface ResolvedCredential { ## 描述 -`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 +`describe(ref)` 在绝不暴露值的前提下回应配置界面:引用当前是否可解析、来自哪一层、`set` 当前能否成功。可选的 `length` 只描述已保存值的 UTF-16 长度,不包含密钥字符。本地提供方将其管理的文件排在启动环境之前,因此保存值总会成为生效且可写的那一层;移除后会重新使用启动环境或 `.env` 后备值。 ```ts type-equiv /** @@ -47,6 +47,8 @@ interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Stored value length in UTF-16 code units, when disclosed; never the value. */ + length?: number } ``` @@ -156,7 +158,7 @@ abstract resolve(ref: CredentialRef): Promise * Describe one reference for configuration surfaces without exposing the * value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional stored-value length. */ abstract describe(ref: CredentialRef): Promise diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index ddb8a4c70a..973892eac6 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: e813f9e5aaa213fc - zh: 2257b5b45b9f54b5 + en: 268a2069183197f4 + zh: 308efb099ff923f6 /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 8509e4ce30..49fa14336b 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,7 +20,7 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential displays a fixed mask in the input and a green hint that the saved key will be used. The mask does not expose the key or its length. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays one dot per character in the input and a green hint that the saved key will be used. The mask exposes only the key’s length, with no key characters. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index af8f80bcf7..b519b308fe 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,7 +20,7 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据在输入框中显示固定掩码,下方显示绿色的使用已保存密钥提示。掩码不暴露密钥或长度。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中按每个字符一个点显示掩码,下方显示绿色的使用已保存密钥提示。掩码只反映密钥长度,不暴露密钥字符。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 diff --git a/packages/api/settings-controller/README.i18n.yaml b/packages/api/settings-controller/README.i18n.yaml index 4b3f0d24d3..5ad2ca1008 100644 --- a/packages/api/settings-controller/README.i18n.yaml +++ b/packages/api/settings-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 3a654e12f423946b zh: 4e3a19aaee58f8a7 /settings-controller/use-this-package: - en: cf2f4de5bee8be55 - zh: b2630dcba4be5ae8 + en: 919b101f30707609 + zh: 5c5aec141b5d7bcf /settings-controller/configuration: en: e0297f144b649af7 zh: e70ed56edffd97f0 diff --git a/packages/api/settings-controller/README.md b/packages/api/settings-controller/README.md index b38072546d..3ce09e810e 100644 --- a/packages/api/settings-controller/README.md +++ b/packages/api/settings-controller/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) Mount this package as a Loader entry in a profile that serves browser configuration. The entry registers both namespaces independently of their providers so a missing provider produces a named configuration error at invocation. Its generated descriptors enter the strict Typert registry, while the settings and credential Definitions remain plain Cordis Services with no wire obligations of their own. -`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Secret values cross in this direction only: no method here returns one. +`describe(refs)` answers one map keyed by the requested names, so a settings page describing every reference its rows carry settles those rows together. It accepts at most 64 names per call, reports an invalid name or empty write value as `bad-request`, and copies each answer field by field — a provider returning more than `CredentialInfo` declares cannot widen what crosses. The view may include the stored value’s `length`, without any key characters. Valid `set(ref, value)` and `unset(ref)` calls report a provider refusal as `credential-rejected`, carrying the provider's message with only the reference in its details. Secret values cross in this direction only: no method here returns one. `settings.describe()` returns deployment facts and every namespace under `redactSecrets: true`. `settings.update`, `settings.replace`, and `settings.mutate` expose the settings service's three write operations and return the namespace's new redacted view; stale writes use `settings-conflict` and other provider refusals use `settings-rejected`. diff --git a/packages/api/settings-controller/README.zh.md b/packages/api/settings-controller/README.zh.md index 3c9e876740..f6bb656b00 100644 --- a/packages/api/settings-controller/README.zh.md +++ b/packages/api/settings-controller/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" 请把本包作为 Loader entry 挂载到提供浏览器配置的 profile 中。本 entry 不依赖提供方是否存在而注册两个 namespace,因此缺少提供方会在调用时产生具名配置错误。它生成的 descriptor 进入严格 Typert 注册表,而 settings 与凭据 Definition 仍是普通 Cordis 服务,自身不承担任何 wire 义务。 -`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 +`describe(refs)` 以请求的名字为键返回一份 map,因此设置页描述其各行携带的全部引用时,这些行会一起落定。单次调用最多接受 64 个名字,无效名字或空写入值报告为 `bad-request`,并逐字段复制每个答案——提供方返回超出 `CredentialInfo` 声明的内容也无法扩大跨越 wire 的字段。视图可包含已保存值的 `length`,不含密钥字符。有效的 `set(ref, value)` 与 `unset(ref)` 调用把提供方拒绝报告为 `credential-rejected`,携带提供方的消息,details 中只有该引用。机密值只在这个方向跨越 wire:这里没有任何方法会返回它。 `settings.describe()` 返回部署信息,以及在 `redactSecrets: true` 下读取的所有 namespace。`settings.update`、`settings.replace` 与 `settings.mutate` 暴露 settings 服务的三种写入操作,并返回该 namespace 的新脱敏视图;陈旧写入使用 `settings-conflict`,其他提供方拒绝使用 `settings-rejected`。 diff --git a/packages/api/settings-controller/src/credentials.ts b/packages/api/settings-controller/src/credentials.ts index 3889669048..6e66596206 100644 --- a/packages/api/settings-controller/src/credentials.ts +++ b/packages/api/settings-controller/src/credentials.ts @@ -47,6 +47,7 @@ function projectCredentialInfo(info: CredentialInfo): CredentialInfo { configured: info.configured, ...info.source === undefined ? {} : { source: info.source }, writable: info.writable, + ...info.length === undefined ? {} : { length: info.length }, } } diff --git a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts index 5eeb190385..4b3c335a51 100644 --- a/packages/api/settings-controller/tests/credentials-controller.host.spec.ts +++ b/packages/api/settings-controller/tests/credentials-controller.host.spec.ts @@ -9,7 +9,7 @@ import { MemoryCredentials } from '../../../credentials/credentials/tests/memory class LeakyCredentials extends MemoryCredentials { override describe(): Promise { return Promise.resolve( - { configured: true, source: 'memory', writable: true, value: 'sk-leaked' } as CredentialInfo, + { configured: true, source: 'memory', writable: true, length: 9, value: 'sk-leaked', preview: 'sk…ed' } as CredentialInfo, ) } } @@ -101,8 +101,9 @@ describe('the credentials Remote namespace a configuration surface calls', () => it('answers only the fields the view declares, whatever a provider returns', async () => { const controller = await boot({}, LeakyCredentials) const described = await controller.describe(['DEEPSEEK_API_KEY']) - expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true }) + expect(described.DEEPSEEK_API_KEY).toEqual({ configured: true, source: 'memory', writable: true, length: 9 }) expect(JSON.stringify(described)).not.toContain('sk-leaked') + expect(JSON.stringify(described)).not.toContain('sk…ed') }) it('stores and removes through the same references the batch describes', async () => { diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 5cb4d4bc1f..7812058b5b 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,11 +18,11 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: 2075f43f7f5a25f9 - zh: d88830eb581067b7 + en: f335b529edb55754 + zh: 30e4b43b19b2da40 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 6756a578138e88bf - zh: 371611209d82149d + en: 2c55f1b66c9452bf + zh: adea0305177c8012 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be zh: dc2a51a5a40138bc diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index a4baf12d9e..0a62302c2b 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,7 +41,7 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display a fixed mask as a placeholder, never a credential value or its length. They disable the existing reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. +API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display one placeholder dot per character, using only stored-length metadata; no key characters reach the Client. A provider that omits length metadata shows the saved-key notice without inventing a mask length. They disable the existing reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. @@ -49,7 +49,7 @@ The editor uses redacted `CredentialInfo` to choose the saved-credential placeho ### Editing a provider -Leaving the saved mask untouched preserves existing authentication. A saved credential shows a fixed input mask and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +Leaving the saved mask untouched preserves existing authentication. A saved credential shows a mask matching its length and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 5ab65ddae9..129381ff47 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,7 +41,7 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥以固定掩码占位显示,不表示凭据值或长度;禁用原有显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 +API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥的占位掩码只使用长度元数据,每个字符显示一个点,不将密钥字符读入 Client。提供方未提供长度元数据时,仅显示使用已保存密钥的提示,不猜测掩码长度;禁用原有显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 @@ -49,7 +49,7 @@ API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自 ### 编辑提供商 -保持已保存掩码不变时保留现有认证。已保存凭据显示固定的输入掩码和绿色的使用已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 +保持已保存掩码不变时保留现有认证。已保存凭据显示与密钥等长的输入掩码和绿色的使用已保存密钥提示。否则提示使用环境认证。在已保存掩码上按 Backspace 或 Delete,会将删除操作暂存到「保存」时执行;取消会保留密钥。清空替换草稿也会暂存删除已保存密钥。不新增单独的清除按钮。输入新密钥会替换待删除草稿。删除被拒绝时,设置保持不变。删除成功但设置失败时,编辑器说明密钥已删除,并提供「保存」重试设置;「关闭」会保留这一部分提交结果。目录路由会移除用户层中的派生引用以恢复原生认证;与 `_API_KEY` 不同的别名、继承引用和自定义路由保留原引用以使用环境后备。手写的同名常规引用与页面派生引用按相同方式处理。隐藏的 OAuth 引用不提供已保存 API 密钥掩码或清除控件。待删除期间暂不允许获取模型列表。脱敏的 `credentials.describe` 检查区分已检测到环境引用、未检测到变量和读取状态未确认。缺少变量时使用黄色提示,并列出应配置的首个变量名。已检测到环境引用时使用绿色。地址配置变量不计作凭据。隐藏的认证引用仍参与检测;使用不含变量名的通用检测提示。检测不验证凭据、不测试连接,也不检查 AWS profile 或 Google 应用默认凭据等提供商管理的文件。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。页面读取原生变量名和具名引用,每批最多 64 项,不将变量值读入 Client。 目录未提供固定默认端点时,输入框下方显示提供方的 `baseURLEnv` 配置变量名。Profile 中的端点仍是占位符的首选。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index a9757972b1..100710514b 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -12,8 +12,9 @@ const EYE_OFF_PATH = `${EYE_CONTOUR}M2.5 2.5L13.5 13.5` interface ApiKeyInputProps extends Omit, 'value' | 'type' | 'className' | 'autoComplete'> { /** Unsaved input; stored credentials are never read into this field. */ readonly value: string - /** Saved-key actions; the mask never contains the stored credential. */ + /** Saved-key length and actions; the mask never contains the stored credential. */ readonly saved?: { + readonly length: number readonly clear?: () => void } /** Section copy, including the same reveal labels as SecretText. */ @@ -36,7 +37,7 @@ export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): Re type={revealed ? 'text' : 'password'} autoComplete="new-password" value={value} - placeholder={saved === undefined ? props.placeholder : '••••••••'} + placeholder={saved === undefined ? props.placeholder : '•'.repeat(saved.length)} onCopy={(event) => { if (saved !== undefined) event.preventDefault() }} onCut={(event) => { if (saved !== undefined) event.preventDefault() }} onKeyDown={(event) => { diff --git a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx index 2a88a6179c..d6b3bc9cba 100644 --- a/packages/client/ui-settings-models/src/client/ProviderEditor.tsx +++ b/packages/client/ui-settings-models/src/client/ProviderEditor.tsx @@ -491,6 +491,7 @@ export function ProviderEditor(props: ProviderEditorProps): ReactNode { value={keyText} {...keyDraft === undefined && savedCredential ? { saved: { + length: detected[1].length ?? 0, ...detected[1].writable ? { clear: () => { setKeyDraft({ ref: detected[0] }); setFailure(undefined) } } : {}, }, diff --git a/packages/client/ui-settings-models/tests/components.client.spec.tsx b/packages/client/ui-settings-models/tests/components.client.spec.tsx index ef24386913..ac17133275 100644 --- a/packages/client/ui-settings-models/tests/components.client.spec.tsx +++ b/packages/client/ui-settings-models/tests/components.client.spec.tsx @@ -222,7 +222,7 @@ function scriptedFace(overrides: { Promise.resolve(remoteOk( Object.fromEntries(refs.map(ref => [ref, { configured: ref === 'OPENAI_API_KEY', - ...ref === 'OPENAI_API_KEY' ? { source: 'file' } : {}, + ...ref === 'OPENAI_API_KEY' ? { source: 'file', length: 8 } : {}, writable: true, }])), ))), @@ -2206,7 +2206,7 @@ describe('apiKeyFailure', () => { it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing authentication with a blank input for source %s', (source) => { renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { - credential: { configured: true, source, writable: true }, + credential: { configured: true, source, writable: true, ...source === 'file' ? { length: 8 } : {} }, }) const hint = en.keyFallbackDetected.replace('{hint}', 'OPENAI_API_KEY') const input = screen.getByLabelText(en.keyInput) @@ -2230,14 +2230,16 @@ it.each(['file', 'env', 'project-env', 'user-env'] as const)('shows the existing else expect(screen.getAllByText(hint)).toHaveLength(1) }) -it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects the saved %s key and reveals only its replacement', (provider) => { +it.each([ + ['openai', 1], ['anthropic', 7], ['google', 32], ['deepseek', 64], ['acme-gateway', 128], +] as const)('protects the saved %s key and reveals only its replacement', (provider, length) => { renderPiAiEditor(provider, piAiNamespaceWith(provider, { apiKeyEnv: 'TEAM_API_KEY' }), { - credential: { configured: true, source: 'file', writable: true }, + credential: { configured: true, source: 'file', writable: true, length }, }) const input = screen.getByLabelText(en.keyInput) expect(input.value).toBe('') expect(input.type).toBe('password') - expect(input.placeholder).toBe('••••••••') + expect(input.placeholder).toBe('•'.repeat(length)) expect(screen.queryByRole('button', { name: 'Clear saved key' })).toBeNull() expect(screen.getByRole('button', { name: en.keyReveal }).disabled).toBe(true) expect(fireEvent.copy(input)).toBe(false) @@ -2256,6 +2258,17 @@ it.each(['openai', 'anthropic', 'google', 'deepseek', 'acme-gateway'])('protects expect(screen.queryByLabelText(en.keyReveal)).toBeNull() }) +it('does not invent a mask length when the credential provider omits it', () => { + renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { + credential: { configured: true, source: 'file', writable: true }, + }) + const input = screen.getByLabelText(en.keyInput) + expect(input.value).toBe('') + expect(input.placeholder).toBe('') + expect(screen.getByText(en.keySaved)).toBeTruthy() + expect(screen.getByRole('button', { name: en.keyReveal }).disabled).toBe(true) +}) + it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and can cancel it', async (key) => { const { unset } = await mountSection() const edit = () => screen.getByRole('button', { name: openaiCopy(en.editProvider) }) @@ -2280,7 +2293,7 @@ it.each(['Backspace', 'Delete'])('stages whole saved-key deletion with %s and ca it('keeps a saved read-only credential masked when deletion is unavailable', () => { renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { - credential: { configured: true, source: 'file', writable: false }, + credential: { configured: true, source: 'file', writable: false, length: 8 }, }) const input = screen.getByLabelText(en.keyInput) fireEvent.keyDown(input, { key: 'Delete' }) @@ -2293,7 +2306,7 @@ it('keeps a saved read-only credential masked when deletion is unavailable', () it('keeps a hidden OAuth reference out of the saved API-key controls', () => { renderPiAiEditor('anthropic', piAiNamespaceWith('anthropic', { apiKeyEnv: 'ANTHROPIC_OAUTH_TOKEN' }), { - credential: { configured: true, source: 'file', writable: true }, + credential: { configured: true, source: 'file', writable: true, length: 8 }, }) const input = screen.getByLabelText(en.keyInput) expect(input.value).toBe('') @@ -2313,7 +2326,7 @@ it.each([ render() + credential={{ configured: true, source: 'file', writable: true, length: 8 }} />) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) const envRef = removesReference && nativeAuth !== undefined ? nativeAuth.env[0] : ref expect(screen.getByLabelText(en.keyInput).placeholder) @@ -2333,7 +2346,7 @@ it.each([ it('keeps the clear hint generic when native authentication has no visible environment reference', () => { renderPiAiEditor('openai', piAiNamespaceWith('openai', { apiKeyEnv: 'OPENAI_API_KEY' }), { nativeAuth: { env: [], oauth: false }, - credential: { configured: true, source: 'file', writable: true }, + credential: { configured: true, source: 'file', writable: true, length: 8 }, }) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) expect(screen.getByText(en.keyRemovePending)).toBeTruthy() @@ -2349,7 +2362,7 @@ it.each(['cancel', 'replace'])('keeps authentication unchanged after refused del namespace={piAiNamespaceWith('google', { apiKeyEnv: 'GOOGLE_API_KEY' })} settingsPath={['providers', 'google']} schema={settingsSchema} operations={operationsWith(face)} t={t} readOnly={false} onClose={closed} nativeAuth={{ env: ['GEMINI_API_KEY'], oauth: false }} - credential={{ configured: true, source: 'file', writable: true }} />) + credential={{ configured: true, source: 'file', writable: true, length: 8 }} />) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('credential store locked') @@ -2379,7 +2392,7 @@ it.each(['retry', 'close'])('reports a completed deletion when settings fail, th render() + credential={{ configured: true, source: 'file', writable: true, length: 8 }} />) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await screen.findByText('settings locked') @@ -2402,7 +2415,7 @@ it('clears the selected reference when refreshed metadata names a different cred const props: ProviderEditorProps = { provider: 'openai', displayName: 'OpenAI', namespace: piAiNamespaceWith('openai', { apiKeyEnv: 'OLD_KEY' }), settingsPath: ['providers', 'openai'], schema: settingsSchema, operations: operationsWith(face), - t, readOnly: false, onClose: vi.fn(), credential: { configured: true, source: 'file', writable: true }, + t, readOnly: false, onClose: vi.fn(), credential: { configured: true, source: 'file', writable: true, length: 8 }, } const view = render() fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) @@ -2417,7 +2430,7 @@ it('clears the detected native key instead of an unused derived reference', asyn render() + credentialChecks={{ GEMINI_API_KEY: { configured: true, source: 'file', writable: true, length: 8 } }} />) fireEvent.keyDown(screen.getByLabelText(en.keyInput), { key: 'Delete' }) fireEvent.click(screen.getByRole('button', { name: en.apply })) await waitFor(() => { expect(unset).toHaveBeenCalledExactlyOnceWith('GEMINI_API_KEY') }) @@ -2427,7 +2440,7 @@ it('clears the detected native key instead of an unused derived reference', asyn it.each([ ['unconfigured', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: false, source: 'env', writable: true }], ['unknown source', { apiKeyEnv: 'OPENAI_API_KEY' }, { configured: true, source: 'oauth', writable: true }], - ['native authentication', {}, { configured: true, source: 'file', writable: true }], + ['native authentication', {}, { configured: true, source: 'file', writable: true, length: 8 }], ] as const)('does not guess a source for %s', (_label, profile, credential) => { renderPiAiEditor('openai', piAiNamespaceWith('openai', profile), { credential }) expect(screen.queryByText(/^API key source:/)).toBeNull() diff --git a/packages/credentials/credentials-local/README.i18n.yaml b/packages/credentials/credentials-local/README.i18n.yaml index b4401964e7..00075d6ddd 100644 --- a/packages/credentials/credentials-local/README.i18n.yaml +++ b/packages/credentials/credentials-local/README.i18n.yaml @@ -24,8 +24,8 @@ en: fccad7d354c2af71 zh: 5b95b5890e21f80f /deepseek-ai-dsh-credentials-local/use-this-package/storing-and-removing-keys: - en: 5e3d45470142b9dd - zh: 1f8358f987769d3a + en: 8194c7e7125f7941 + zh: abe217a5edeb0c4f /deepseek-ai-dsh-credentials-local/use-this-package/where-keys-come-from: en: a55fac148b62e007 zh: fdb3d19ccae676ee diff --git a/packages/credentials/credentials-local/README.md b/packages/credentials/credentials-local/README.md index c3d15999be..080ffd3e99 100644 --- a/packages/credentials/credentials-local/README.md +++ b/packages/credentials/credentials-local/README.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable, length? } — never the value await ctx.credentials.unset(ref) // remove ``` -A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). +A key you save is usable by the next request that names it, and `describe` reports whether it is set, where it comes from, and whether you can write to it — never the value itself. A stored file value also reports its UTF-16 `length`; environment fallbacks omit this field. Records persist in the same file, addressed by `/` and managed with the seam's record operations (`readRecord`, `describeRecord`, `listRecords`, `modifyRecord`, `deleteRecord`). ### Where keys come from diff --git a/packages/credentials/credentials-local/README.zh.md b/packages/credentials/credentials-local/README.zh.md index 5249827cde..4d463c9d83 100644 --- a/packages/credentials/credentials-local/README.zh.md +++ b/packages/credentials/credentials-local/README.zh.md @@ -60,11 +60,11 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') await ctx.credentials.set(ref, 'sk-…') // save -await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +await ctx.credentials.describe(ref) // { configured, source?, writable, length? } — never the value await ctx.credentials.unset(ref) // remove ``` -你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 +你保存的密钥会被下一个按名引用它的请求使用;`describe` 报告它是否已设置、来自哪里、能否写入——绝不返回值本身。文件中已保存的值还会报告 UTF-16 `length`;环境后备值不包含此字段。记录也持久化在同一文件中:插件按 `/` 寻址一条记录,并用 seam 的记录操作(`readRecord`、`describeRecord`、`listRecords`、`modifyRecord`、`deleteRecord`)管理它。 ### 密钥从哪里来 diff --git a/packages/credentials/credentials-local/src/index.ts b/packages/credentials/credentials-local/src/index.ts index 48ae487c6d..7e03bca4ec 100644 --- a/packages/credentials/credentials-local/src/index.ts +++ b/packages/credentials/credentials-local/src/index.ts @@ -633,7 +633,7 @@ export class LocalCredentialProvider extends CredentialProvider { override describe(ref: CredentialRef): Promise { const stored = this.values.get(ref) - if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true }) + if (stored !== undefined) return Promise.resolve({ configured: true, source: 'file', writable: true, length: stored.length }) // Every reference is writable: a set writes the managed file, which // outranks every fallback, and an unset exposes the fallback again. if (this.inherited(ref) !== undefined) return Promise.resolve({ configured: true, source: 'env', writable: true }) diff --git a/packages/credentials/credentials-local/tests/local.spec.ts b/packages/credentials/credentials-local/tests/local.spec.ts index d1436e0731..4d61872830 100644 --- a/packages/credentials/credentials-local/tests/local.spec.ts +++ b/packages/credentials/credentials-local/tests/local.spec.ts @@ -73,7 +73,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'plain', source: 'file' }) expect(await ctx.credentials.resolve(OTHER)).toEqual({ value: 'with space', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 5 }) }) it('lets the managed file win over a non-empty process environment', async () => { @@ -83,7 +83,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', 'from-env') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-file', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 9 }) }) it('treats an empty environment value as absent, falling through to the file', async () => { @@ -93,7 +93,7 @@ describe('layering and reads', () => { const ctx = await boot({ path, watch: false }) vi.stubEnv('DSH_CRED_TEST', '') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 6 }) }) it('fails boot loud when the document exists but cannot be read', async () => { @@ -131,7 +131,7 @@ describe('layer ladder', () => { expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) // A key sitting in the user's .env does not make the stored one // unwritable. - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 6 }) await expect(ctx.credentials.set(KEY, 'rotated')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'rotated', source: 'file' }) }) @@ -145,8 +145,10 @@ describe('layer ladder', () => { expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: true }) await ctx.credentials.set(KEY, 'stored') expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 6 }) await ctx.credentials.unset(KEY) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'from-launch', source: 'env' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'env', writable: true }) }) it('serves the user .env only when nothing is stored', async () => { @@ -230,9 +232,10 @@ describe('layer ladder', () => { { source: 'user-env', path: '/home/.dsh/.env', values: { DSH_CRED_TEST: 'from-user-env' } }, ]) expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'stored', source: 'file' }) - expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 6 }) await expect(ctx.credentials.set(KEY, 'next')).resolves.toBeUndefined() expect(await ctx.credentials.resolve(KEY)).toEqual({ value: 'next', source: 'file' }) + expect(await ctx.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: 4 }) }) }) @@ -382,7 +385,7 @@ describe('document writes', () => { const reread = await boot({ path, watch: false }) expect(await reread.credentials.resolve(KEY)).toEqual({ value: multiLine, source: 'file' }) expect(await reread.credentials.resolve(OTHER)).toEqual({ value: mixedQuotes, source: 'file' }) - expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await reread.credentials.describe(KEY)).toEqual({ configured: true, source: 'file', writable: true, length: multiLine.length }) }) it('unsets only the owning entry, with its own annotation, and keeps an absent unset silent', async () => { diff --git a/packages/credentials/credentials/README.i18n.yaml b/packages/credentials/credentials/README.i18n.yaml index 3f2265caf7..1e471a6cbf 100644 --- a/packages/credentials/credentials/README.i18n.yaml +++ b/packages/credentials/credentials/README.i18n.yaml @@ -24,8 +24,8 @@ en: 8f3500119608f91b zh: 147fdb5389affbc0 /deepseek-ai-dsh-credentials/use-this-package/storing-checking-and-removing-keys: - en: fa334e2d4438e0b6 - zh: 009b9252ed046886 + en: ae12e0d21a030bd1 + zh: 9072486f52cf6569 /deepseek-ai-dsh-credentials/use-this-package/storing-updating-and-removing-records: en: 300c3f1f13abdca4 zh: ec7a6486ac88889c diff --git a/packages/credentials/credentials/README.md b/packages/credentials/credentials/README.md index 85ed5a68b0..0cdff47017 100644 --- a/packages/credentials/credentials/README.md +++ b/packages/credentials/credentials/README.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable, length? } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. +Store a key with `set`, remove it with `unset`, check its status with `describe`, and read the current value with `resolve` when an operation needs it. `describe` reports whether the key is set, where it comes from, and whether you can write to it — it never returns the value. Providers may disclose the stored value’s UTF-16 length through the optional `length` field. ### Storing, updating, and removing records diff --git a/packages/credentials/credentials/README.zh.md b/packages/credentials/credentials/README.zh.md index c73f0c68bf..37bee0ff6f 100644 --- a/packages/credentials/credentials/README.zh.md +++ b/packages/credentials/credentials/README.zh.md @@ -53,12 +53,12 @@ declare const ctx: Context const ref = credentialRef('DEEPSEEK_API_KEY') // POSIX shell identifier, branded const hit = await ctx.credentials.resolve(ref) // { value, source } | undefined -const info = await ctx.credentials.describe(ref) // { configured, source?, writable } — never the value +const info = await ctx.credentials.describe(ref) // { configured, source?, writable, length? } — never the value await ctx.credentials.set(ref, 'sk-…') // the stored value outranks environment fallbacks await ctx.credentials.unset(ref) // no-op when absent; an environment fallback then applies again ``` -用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。 +用 `set` 存储密钥、用 `unset` 移除、用 `describe` 检查状态、在操作需要时用 `resolve` 读取当前值。`describe` 报告密钥是否已设置、来自哪里、能否写入——它绝不返回值。提供方可通过可选的 `length` 字段报告已保存值的 UTF-16 长度。 ### 存储、更新与移除记录 diff --git a/packages/credentials/credentials/src/index.ts b/packages/credentials/credentials/src/index.ts index 2e0b56931a..156be45241 100644 --- a/packages/credentials/credentials/src/index.ts +++ b/packages/credentials/credentials/src/index.ts @@ -187,7 +187,7 @@ export abstract class CredentialProvider extends Service { * Describe one reference for configuration surfaces without exposing the * value. * @param ref - the reference to describe. - * @returns configured state, supplying source, and writability. + * @returns configured state, supplying source, writability, and optional stored-value length. */ abstract describe(ref: CredentialRef): Promise diff --git a/packages/credentials/credentials/src/types.ts b/packages/credentials/credentials/src/types.ts index 5c9ae99350..a8dae57489 100644 --- a/packages/credentials/credentials/src/types.ts +++ b/packages/credentials/credentials/src/types.ts @@ -71,6 +71,8 @@ export interface CredentialInfo { source?: string /** Whether the active provider can write this reference. */ writable: boolean + /** Stored value length in UTF-16 code units, when disclosed; never the value. */ + length?: number } declare module '@deepseek-ai/cordis' { diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..dfe102830e 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -846,7 +846,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'abstract describe(ref: CredentialRef): Promise', description: 'Describe one reference for configuration surfaces without exposing the value.', parameters: [{ name: 'ref', description: 'the reference to describe.' }], - returns: 'configured state, supplying source, and writability.', + returns: 'configured state, supplying source, writability, and optional stored-value length.', }, { signature: 'abstract set(ref: CredentialRef, value: string): Promise', @@ -6280,7 +6280,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'CredentialInfo', - declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n}', + declaration: 'export interface CredentialInfo {\n configured: boolean;\n source?: string;\n writable: boolean;\n length?: number;\n}', }, { name: 'CredentialKey', diff --git a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts index 183c590e2b..2b47c869d1 100644 --- a/packages/llm/llm-deepseek/tests/loader-composition.spec.ts +++ b/packages/llm/llm-deepseek/tests/loader-composition.spec.ts @@ -323,7 +323,7 @@ describe('llm-deepseek real dynamic composition', () => { const home = root! await boot.ctx.get('credentials')!.set(KEY_REF, 'stored-by-ui') expect(await boot.ctx.get('credentials')!.describe(KEY_REF)) - .toEqual({ configured: true, source: 'file', writable: true }) + .toEqual({ configured: true, source: 'file', writable: true, length: 'stored-by-ui'.length }) await assemble(boot.ctx, { model: 'deepseek-v4-flash', messages: [] }) expect(first.headers[0]?.['x-api-key']).toBe('stored-by-ui') await boot.ctx.fiber.dispose() @@ -335,9 +335,12 @@ describe('llm-deepseek real dynamic composition', () => { // The stored key is still the provider's own file entry — not a // launch-environment value, which is what hoisting it would have made it. expect(await credentials.resolve(KEY_REF)).toEqual({ value: 'stored-by-ui', source: 'file' }) - expect(await credentials.describe(KEY_REF)).toEqual({ configured: true, source: 'file', writable: true }) + expect(await credentials.describe(KEY_REF)) + .toEqual({ configured: true, source: 'file', writable: true, length: 'stored-by-ui'.length }) // Rotation still works after the restart, and the next request uses it. await credentials.set(KEY_REF, 'rotated-after-restart') + expect(await credentials.describe(KEY_REF)) + .toEqual({ configured: true, source: 'file', writable: true, length: 'rotated-after-restart'.length }) await assemble(restarted.ctx, { model: 'deepseek-v4-flash', messages: [] }) expect(second.headers[0]?.['x-api-key']).toBe('rotated-after-restart') }) From 5e39b7dcb51e49b30038bc5ee0f82ae530024377 Mon Sep 17 00:00:00 2001 From: Magolor Date: Tue, 3 Nov 2026 20:58:41 +0800 Subject: [PATCH 049/103] fix(settings): hide unavailable API key reveal controls --- apps/web/tests/deepseek-messages-settings.e2e.ts | 4 ++-- .../deepseek-messages-settings/cards.expected.md | 1 - .../default-models.expected.md | 1 - .../onboarding-deepseek-config/models.expected.md | 1 - docs/user/guide/providers.i18n.yaml | 4 ++-- docs/user/guide/providers.md | 4 ++-- docs/user/guide/providers.zh.md | 4 ++-- .../client/ui-settings-models/README.i18n.yaml | 6 +++--- packages/client/ui-settings-models/README.md | 4 ++-- packages/client/ui-settings-models/README.zh.md | 2 +- .../ui-settings-models/src/client/ApiKeyInput.tsx | 8 ++++---- .../tests/components.client.spec.tsx | 14 ++++++++++++-- 12 files changed, 30 insertions(+), 23 deletions(-) diff --git a/apps/web/tests/deepseek-messages-settings.e2e.ts b/apps/web/tests/deepseek-messages-settings.e2e.ts index 3d88fdbf6c..fac29bc27f 100644 --- a/apps/web/tests/deepseek-messages-settings.e2e.ts +++ b/apps/web/tests/deepseek-messages-settings.e2e.ts @@ -137,7 +137,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki const key = dialog.getByLabel('API 密钥', { exact: true }) expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-protected-old-key'.length)) expect(await key.inputValue()).toBe('') - expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) expect(await page.locator('body').innerHTML()).not.toContain('fixture-protected-old-key') await key.press('Backspace') await dialog.getByText('保存以清除已保存的 API key。之后使用环境认证(DEEPSEEK_API_KEY)。', { exact: true }).waitFor() @@ -160,7 +160,7 @@ it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webki expect(await key.getAttribute('placeholder')).toBe('•'.repeat('fixture-new-key'.length)) expect(await key.inputValue()).toBe('') expect(await key.getAttribute('type')).toBe('password') - expect(await dialog.getByRole('button', { name: '显示密钥' }).isDisabled()).toBe(true) + expect(await dialog.getByRole('button', { name: '显示密钥' }).count()).toBe(0) expect(await page.locator('body').innerHTML()).not.toContain('fixture-new-key') } finally { try { await browser?.close() } finally { await scaffold.close() } diff --git a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md index 1304d5467b..425d154403 100644 --- a/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md +++ b/apps/web/tests/expected/deepseek-messages-settings/cards.expected.md @@ -18,7 +18,6 @@ - button "认证说明": "?" - textbox "API 密钥": - /placeholder: •••••••••••••••••••••• - - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md index 40f08ec904..88f6fe3f0d 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/default-models.expected.md @@ -18,7 +18,6 @@ - button "认证说明": "?" - textbox "API 密钥": - /placeholder: •••••••••••••••••••••••••••••••••••••••••••• - - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 diff --git a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md index 509fbd7745..c13287dbbf 100644 --- a/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md +++ b/apps/web/tests/expected/onboarding-deepseek-config/models.expected.md @@ -18,7 +18,6 @@ - button "认证说明": "?" - textbox "API 密钥": - /placeholder: •••••••••••••••••••••••••••••••••••••••••••• - - button "显示密钥" [disabled] - paragraph: 使用已保存的 API key。 - group: - text: 自定义设置 API 地址 diff --git a/docs/user/guide/providers.i18n.yaml b/docs/user/guide/providers.i18n.yaml index 973892eac6..e23c521fdb 100644 --- a/docs/user/guide/providers.i18n.yaml +++ b/docs/user/guide/providers.i18n.yaml @@ -9,8 +9,8 @@ en: 44852da64a6a39ec zh: 4c280e428f0fec08 /configure-models/add-a-third-party-provider: - en: 268a2069183197f4 - zh: 308efb099ff923f6 + en: c6e99f983e869371 + zh: 4d0a1d2480d710ce /configure-models/add-a-custom-model-api: en: 1f55d7d94cbfbd80 zh: 94e5a8bc7625d760 diff --git a/docs/user/guide/providers.md b/docs/user/guide/providers.md index 49fa14336b..4dfcf1f91b 100644 --- a/docs/user/guide/providers.md +++ b/docs/user/guide/providers.md @@ -20,9 +20,9 @@ Choose **Add model provider**. The card opens on **Third-party model provider**: The authentication **?** explains saved-credential priority and environment fallbacks. Leave the key blank to use a saved credential or try the listed environment variables. A green hint identifies a detected environment variable. A yellow hint means no credential variable was detected; enter an API key or configure the listed variable. An unconfirmed hint means the status read failed. Detection does not validate the credential or test the connection. Provider-managed credential files, including AWS profiles and Google application-default credentials, are outside this check. Providers without native key authentication, such as `openai-codex`, show no key field unless the profile explicitly names a credential reference. -A saved credential displays one dot per character in the input and a green hint that the saved key will be used. The mask exposes only the key’s length, with no key characters. The existing eye button is disabled for saved keys, which cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Save**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Save** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. +A saved credential displays one dot per character in the input and a green hint that the saved key will be used. The mask exposes only the key’s length, with no key characters. Applyd keys have no eye button and cannot be revealed, copied, cut, or partially edited; typing or pasting replaces the whole key. Backspace or Delete stages whole-key removal. Press Backspace or Delete, then **Apply**, to remove the stored override and use environment authentication. Emptying a replacement also stages deletion of the saved key. **Cancel** preserves the saved key before saving. A refused deletion leaves settings unchanged. If the key is removed but settings fail, the warning reports that deletion cannot be undone; retry **Apply** to finish settings, or **Close** to leave the partial result. Clearing a shared credential affects every feature using the same reference. Without an environment credential, the provider has no authentication after clearing. Environment fallback uses **Leave blank to use env as auth** and one detection hint while the input is empty. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. Address configuration variables appear under **Base URL** and do not count as credentials. -A nonempty key input has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. +An editable, nonempty key draft has an eye button. Select **Show secret** to check what you typed, and **Hide secret** to mask it again. Changing the input masks it again. Native password fields do not offer cut; select the draft and press Backspace to erase it, or reveal it before cutting. Stored credentials remain write-only. ## Add a custom model API diff --git a/docs/user/guide/providers.zh.md b/docs/user/guide/providers.zh.md index b519b308fe..30124fab17 100644 --- a/docs/user/guide/providers.zh.md +++ b/docs/user/guide/providers.zh.md @@ -20,9 +20,9 @@ 认证 **?** 说明已保存凭据的优先级和环境后备。密钥留空时,使用已保存凭据,或尝试读取列出的环境变量。绿色提示标明已检测到环境变量。黄色提示表示未检测到凭据变量;请输入 API 密钥或配置列出的变量。状态未确认表示读取失败。检测不验证凭据,也不测试连接。AWS profile 和 Google 应用默认凭据等提供商管理的凭据文件不在检查范围内。没有原生密钥认证的提供商(例如 `openai-codex`)不显示密钥字段,除非 profile 显式指定了凭据引用。 -已保存凭据在输入框中按每个字符一个点显示掩码,下方显示绿色的使用已保存密钥提示。掩码只反映密钥长度,不暴露密钥字符。已保存密钥禁用原有眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 +已保存凭据在输入框中按每个字符一个点显示掩码,下方显示绿色的使用已保存密钥提示。掩码只反映密钥长度,不暴露密钥字符。已保存密钥不显示眼睛按钮,不能显示、复制、剪切或局部编辑;键入或粘贴会整项替换。Backspace 或 Delete 会暂存整项删除。按 Backspace 或 Delete,再点**保存**,即可移除存储覆盖并使用环境认证。清空替换草稿也会暂存删除已保存密钥。保存前,**取消**会保留密钥。删除被拒绝时,设置保持不变。密钥已删除但设置失败时,警告会说明此删除无法撤销;可重试**保存**完成配置更新,或**关闭**并保留部分提交结果。清除共享凭据会影响使用同一引用的全部功能。没有环境凭据时,清除后提供商将没有认证。环境后备使用**留空使用环境认证**占位文字,输入留空时显示一条检测提示。替换草稿显示保存以替换密钥的提示。待删除提示会列出保存后使用的环境变量名(路由声明该变量时)。其他非空输入不显示认证状态文字。地址配置变量显示在**基础 URL**下方,不计作凭据。 -密钥输入非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 +可编辑的密钥草稿非空时,输入框内显示眼睛按钮。选择**显示密钥**检查当前输入,选择**隐藏密钥**重新遮住输入。修改输入后会重新遮住密钥。原生密码框不提供剪切;可选中草稿后按 Backspace 清空,或显示明文后再剪切。已保存凭据仍保持只写。 ## 添加自定义模型 API diff --git a/packages/client/ui-settings-models/README.i18n.yaml b/packages/client/ui-settings-models/README.i18n.yaml index 7812058b5b..a6239a5856 100644 --- a/packages/client/ui-settings-models/README.i18n.yaml +++ b/packages/client/ui-settings-models/README.i18n.yaml @@ -18,10 +18,10 @@ en: db5aaf7f702e1f0c zh: 409a78c14fb2b6e3 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/api-keys: - en: f335b529edb55754 - zh: 30e4b43b19b2da40 + en: ec77bf8e03a4f60e + zh: 69cf968c404c45ed /deepseek-ai-dsh-client-ui-settings-models/use-this-package/editing-a-provider: - en: 2c55f1b66c9452bf + en: 783e8f587ae64d10 zh: adea0305177c8012 /deepseek-ai-dsh-client-ui-settings-models/use-this-package/adding-and-deleting-providers: en: 59472e717c2f87be diff --git a/packages/client/ui-settings-models/README.md b/packages/client/ui-settings-models/README.md index 0a62302c2b..43c182b6dd 100644 --- a/packages/client/ui-settings-models/README.md +++ b/packages/client/ui-settings-models/README.md @@ -41,7 +41,7 @@ Host configuration `credentialOnboarding` defaults to `true`. The Electron prelo ### API keys -API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. A nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display one placeholder dot per character, using only stored-length metadata; no key characters reach the Client. A provider that omits length metadata shows the saved-key notice without inventing a mask length. They disable the existing reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. +API-key inputs use `autocomplete="new-password"` to ask browsers not to autofill saved login passwords. An editable, nonempty draft has the same eye control as masked conversation text: **Show secret** reveals the current input and **Hide secret** masks it. Changing or clearing the input masks it again. Saved keys display one placeholder dot per character, using only stored-length metadata; no key characters reach the Client. A provider that omits length metadata shows the saved-key notice without inventing a mask length. Saved keys hide the reveal control and block copy/cut. Typing or pasting replaces the whole key; Backspace or Delete stages whole-key removal. Stored credentials are never read into the input. Native password fields do not offer cut; select and press Backspace to erase a draft, or reveal it before cutting. The primary field on an editor card is a single **API key** input — the page never asks for an environment-variable name. A typed key stores write-only through `credentials.set` under the profile's reference, deriving `_API_KEY` when the profile has none, and the pi-ai profile records that derivation as `apiKeyEnv`, so `cordis.patch.yml` never carries a key value. Leaving a new pi-ai provider's key blank saves a reference-free profile and preserves provider-native authentication (for example the Bedrock credential chain or Vertex ADC). The field's placeholder and help tooltip use the profile's `apiKeyEnv` when it has one; otherwise they use the credential variables of the route's `nativeAuth`, excluding `baseURLEnv` address variables, in lookup order, as the configurable-provider directory reports them. These display hints omit references containing `oauth` (case-insensitively), and describe saved credentials followed by the displayed environment fallbacks. This presentation filter does not change the [credential resolution order](../../../docs/subsystems/credentials.md#resolution), the adapter's complete environment list, or an explicit reference. A filtered explicit reference still has a usable key input with the plain placeholder and no tooltip. A native route that has no key authentication omits the key field and authentication help entirely; an explicit reference still enables the field. A profile without a reference on a route without `nativeAuth`, such as a hand-declared route, shows the plain key placeholder and no tooltip. A row labels API-key state with a green solid dot only when a referenced credential is confirmed configured, and with a red solid dot only when a named reference is confirmed missing. A successful Apply emits a local accessible status message without echoing secret material. @@ -49,7 +49,7 @@ The editor uses redacted `CredentialInfo` to choose the saved-credential placeho ### Editing a provider -Leaving the saved mask untouched preserves existing authentication. A saved credential shows a mask matching its length and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Save; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Save to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. +Leaving the saved mask untouched preserves existing authentication. A saved credential shows a mask matching its length and a green hint that the saved key will be used. Otherwise the field offers environment authentication. Backspace or Delete on a saved mask stages removal until Apply; Cancel preserves the key. Emptying a replacement also stages removal of the saved key. No separate clear button is added. Entering a new key replaces the removal draft. A refused deletion leaves settings unchanged. If deletion succeeds but settings fail, the editor reports the completed deletion and offers Apply to retry settings, with Close leaving that partial result in place. A catalog route drops its user-layer derived reference to restore native authentication; aliases that differ from `_API_KEY`, inherited references, and custom routes retain their reference for environment fallback. A manually written conventional reference is treated like a page-derived reference. Hidden OAuth references have no saved API-key mask or clear control. A pending removal disables model discovery until saved. Redacted `credentials.describe` checks distinguish a detected environment reference, no detected variables, and an unconfirmed read. A missing-variable hint uses the warning color and names the first variable to configure. A detected environment reference uses green. Address configuration variables do not count as credentials. Hidden authentication references still participate in detection; a generic detected hint keeps their names hidden. Detection does not validate credentials, test a connection, or inspect provider-managed files such as AWS profiles and Google application-default credentials. A replacement draft shows a reminder to apply the new key. Pending removal names the environment variable used after applying, when the route declares one. Other nonempty inputs show no authentication status text. The page reads native variable names as well as named references, in batches of at most 64, and never reads their values into the Client. An endpoint without a fixed catalog default shows the provider's `baseURLEnv` configuration names below the input. A profile endpoint remains the first placeholder choice. diff --git a/packages/client/ui-settings-models/README.zh.md b/packages/client/ui-settings-models/README.zh.md index 129381ff47..d5c7ad8bb3 100644 --- a/packages/client/ui-settings-models/README.zh.md +++ b/packages/client/ui-settings-models/README.zh.md @@ -41,7 +41,7 @@ Host 配置 `credentialOnboarding` 默认为 `true`。Electron preload 标记会 ### API 密钥 -API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。输入非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥的占位掩码只使用长度元数据,每个字符显示一个点,不将密钥字符读入 Client。提供方未提供长度元数据时,仅显示使用已保存密钥的提示,不猜测掩码长度;禁用原有显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 +API 密钥输入框通过 `autocomplete="new-password"` 请求浏览器不要自动填入已保存的登录密码。可编辑的草稿非空时,显示与会话密钥遮罩一致的眼睛按钮:**显示密钥**展示当前输入,**隐藏密钥**重新遮住输入。修改或清空输入后会重新遮住密钥。已保存密钥的占位掩码只使用长度元数据,每个字符显示一个点,不将密钥字符读入 Client。提供方未提供长度元数据时,仅显示使用已保存密钥的提示,不猜测掩码长度。已保存密钥隐藏显示按钮,并阻止复制和剪切。键入或粘贴会整项替换,Backspace 或 Delete 会暂存整项删除。已保存凭据从不读入输入框。原生密码框不提供剪切;可选中后按 Backspace 清空草稿,或显示明文后再剪切。 编辑卡片上的主字段是单独一个 **API 密钥**输入框——页面从不询问环境变量名。键入的密钥经 `credentials.set` 以**只写**方式存入 profile 的引用之下,profile 没有引用时便派生 `_API_KEY`,pi-ai profile 会把这次派生记录为 `apiKeyEnv`,因此 `cordis.patch.yml` 从不携带密钥值。为新的 pi-ai 提供商留空密钥会保存一个不带引用的 profile,从而保留提供商原生认证(例如 Bedrock 凭据链或 Vertex ADC)。profile 有 `apiKeyEnv` 时,字段的占位文字与帮助提示采用该引用;否则按查找顺序采用可配置提供商目录为该路由报告的 `nativeAuth` 凭据变量,并排除 `baseURLEnv` 地址变量。这些显示提示会忽略包含 `oauth` 的引用(不区分大小写),并说明优先使用已保存凭据,其后为显示的环境后备。这项显示过滤不改变[凭据解析顺序](../../../docs/subsystems/credentials.zh.md#resolution)、适配器的完整环境变量列表或显式引用。被过滤的显式引用仍有可用的密钥输入框,使用普通占位文字且不显示帮助提示。没有密钥认证的原生路由不显示密钥字段及认证帮助;显式引用仍会启用该字段。路由没有 `nativeAuth`(例如手动声明的路由)且 profile 没有引用时,显示普通的密钥占位文字,且不显示帮助提示。只有确认引用的凭据已配置时,行才会以绿色实心点标示 API 密钥状态;只有确认具名引用缺失时,才会以红色实心点标示。「应用」成功后会发出本地无障碍状态消息,且绝不回显任何机密内容。 diff --git a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx index 100710514b..66459df4a6 100644 --- a/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx +++ b/packages/client/ui-settings-models/src/client/ApiKeyInput.tsx @@ -28,12 +28,13 @@ interface ApiKeyInputProps extends Omit, ' */ export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): ReactNode { const [revealedValue, setRevealedValue] = useState() - const revealed = saved === undefined && value.length > 0 && revealedValue === value + const canReveal = saved === undefined && value.length > 0 && props.disabled !== true + const revealed = canReveal && revealedValue === value return (
0 ? styles['keyInputFilled'] : ''}`} + className={`${styles['input']} ${canReveal ? styles['keyInputFilled'] : ''}`} type={revealed ? 'text' : 'password'} autoComplete="new-password" value={value} @@ -51,12 +52,11 @@ export function ApiKeyInput({ value, saved, t, ...props }: ApiKeyInputProps): Re props.onChange?.(event) }} /> - {value.length === 0 && saved === undefined ? null : + })} +
} + + +} diff --git a/packages/client/ui-account-notifications/src/client/index.ts b/packages/client/ui-account-notifications/src/client/index.ts new file mode 100644 index 0000000000..3b5adafe27 --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/index.ts @@ -0,0 +1,68 @@ +/** Account notifications driven by the existing account UI stream. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-api-remotes/client' +import type {} from '@deepseek-ai/dsh-client-locale/client' +import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' +import type { AccountUiState } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from '../config.ts' +import { AccountNotifications, type AccountNotificationsInjected } from './AccountNotifications.tsx' +import { createNotificationController, type AccountNotice } from './notification-controller.ts' +import { en, zh, ja, es, fr, de, ru, pt } from './locales.ts' +export type { AccountNotificationsInjected, AccountNotificationsProps } from './AccountNotifications.tsx' + +/** Services used for notification lifecycle and presentation. */ +export const inject = ['slots', 'locale', 'remote', 'remote.account', 'accountUi'] + +/** @param ctx - client plugin context sharing the account owner's existing state stream. */ +export function apply(ctx: Context): void { + const page = globalThis as Partial> + const config = Config(page[NOTIFICATIONS_CONFIG_GLOBAL] ?? {}) + ctx.effect(() => ctx.locale.register('account.notifications', { en, zh, ja, es, fr, de, ru, pt }), 'notifications: dictionaries') + let snapshot: readonly AccountNotice[] = [] + const listeners = new Set<() => void>() + const controller = createNotificationController({ + locale: ctx.locale.getSnapshot().active, + pollIntervalMs: config.notificationPollIntervalMs, + read: async (locale) => { + const result = await ctx.remote.account.getNotifications(ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification read failed') + return result.value + }, + readContent: async (id, locale) => { + const result = await ctx.remote.account.getNotificationContent(id, ctx.accountUi.clientMetadata(locale)) + if (!result.ok) throw new Error('account notification content read failed') + return result.value + }, + reportEvent: async (id, event) => { + const result = await ctx.remote.account.reportNotificationEvent(id, event, + ctx.accountUi.clientMetadata(ctx.locale.getSnapshot().active)) + if (!result.ok) throw new Error('account notification event report failed') + return result.value + }, + publish: (notices) => { snapshot = notices; for (const listener of listeners) listener() }, + }) + const update = (state: AccountUiState, reset: boolean): void => { + const signedIn = state.view?.status === 'credential-stored' && !state.failed + if (reset || !signedIn) controller.end() + if (signedIn && reset) controller.begin() + } + ctx.effect(() => () => { controller.end() }, 'notifications: account lifetime') + ctx.on('account-ui/change', update) + ctx.on('account-ui/refresh', () => controller.refresh()) + ctx.on('locale/change', (state) => { void controller.setLocale(state.active) }) + update(ctx.accountUi.getSnapshot(), true) + const state = { + getSnapshot: () => snapshot, + subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener) } }, + } + const injected: AccountNotificationsInjected = { + hooks: { notices: state }, + shown: (id) => { controller.shown(id) }, + ctaClicked: (id) => { controller.ctaClicked(id) }, + dismiss: (id) => { controller.dismiss(id) }, + } + ctx.slots.inject('settings.launcher.notifications', () => ctx.slots.register({ + name: 'settings.launcher.notifications', locale: 'account.notifications', + inject: () => injected, + }, AccountNotifications)) +} diff --git a/packages/client/ui-account-notifications/src/client/locales.ts b/packages/client/ui-account-notifications/src/client/locales.ts new file mode 100644 index 0000000000..be4ef4fd3f --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/locales.ts @@ -0,0 +1,18 @@ +/** Close-control copy owned by account notifications; notification content is server-localized. */ +export const en = { close: 'Close' } +/** Chinese notification controls. */ +export const zh = { close: '关闭' } +/** Japanese notification controls. */ +export const ja = { close: '閉じる' } +/** Spanish notification controls. */ +export const es = { close: 'Cerrar' } +/** French notification controls. */ +export const fr = { close: 'Fermer' } +/** German notification controls. */ +export const de = { close: 'Schließen' } +/** Russian notification controls. */ +export const ru = { close: 'Закрыть' } +/** Portuguese notification controls. */ +export const pt = { close: 'Fechar' } +/** Localized notification control keys. */ +export type NotificationKey = keyof typeof en diff --git a/packages/client/ui-settings-account/src/client/notice-transition.ts b/packages/client/ui-account-notifications/src/client/notice-transition.ts similarity index 100% rename from packages/client/ui-settings-account/src/client/notice-transition.ts rename to packages/client/ui-account-notifications/src/client/notice-transition.ts diff --git a/packages/client/ui-account-notifications/src/client/notification-controller.ts b/packages/client/ui-account-notifications/src/client/notification-controller.ts new file mode 100644 index 0000000000..6c1ba0d01b --- /dev/null +++ b/packages/client/ui-account-notifications/src/client/notification-controller.ts @@ -0,0 +1,248 @@ +/** + * Lifecycle of account notifications: one foreground card in a stack, one read result in + * force at a time, and independent display, action-click, and dismissal reports. Account activation + * and Settings entry replace the polling cycle with an immediate read. Each read + * settles before the next delay begins; the server owns unconsumed notifications. + * + * A displayed event is sent once the foreground card reports a presented frame: the card has + * a position, the document is visible, and it painted one frame. The card measures + * no cover, so a card painted under the open Settings overlay reports like any + * other. Business-action clicks report without waiting or closing the card. + * Explicit dismissal sends only a dismissed event. + * Expiry and account cleanup do not report dismissal. + * + * One lifecycle covers one signed-in session. Login-progress updates retain the + * card and active poll. Credential and connection changes end + * that lifecycle before another begins. Signing out and unloading also clear + * the cards; a later sign-in shows whatever the server offers. + * @module @deepseek-ai/dsh-client-ui-account-notifications/src/client/notification-controller + */ +import type { + AccountNotification, AccountNotificationBatch, AccountNotificationEvent, AccountNotificationId, +} from '@deepseek-ai/dsh-deepseek-account/types' + +/** Notification content currently available to the sidebar presentation. */ +export type AccountNotice = AccountNotification + +/** Collaborators and polling interval of one account notification lifecycle. */ +export interface NotificationControllerOptions { + /** Initial delay for each poll, retained until the server provides a new one. */ + readonly pollIntervalMs: number + /** UI language in effect when the controller starts. */ + readonly locale: string + /** Read the signed-in account's unconsumed notifications. @returns the batch, or null when no account is signed in. */ + read: (locale: string) => Promise + /** + * Query localized content for an existing card without changing consumption. + * @param id - notification requested by stable identity. + * @param locale - language captured for this request. + * @returns content, or null when the account changed; failures reject. + */ + readContent: (id: AccountNotificationId, locale: string) => Promise + /** + * Report one notification interaction. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @returns false when the account changed or signed out; a protocol failure rejects. + */ + reportEvent: (id: AccountNotificationId, event: AccountNotificationEvent) => Promise + /** @param notices - notices in front-to-back order; empty when none are shown. */ + publish: (notices: readonly AccountNotice[]) => void +} + +/** Commands the account plugin issues to the account notification lifecycle. */ +export interface NotificationController { + /** + * Start the signed-in lifecycle and restart polling with an immediate read. + * Re-entry retains cards; the caller ends the lifecycle on credential or connection changes. + */ + begin(): void + /** Stop the lifecycle, drop the displayed notice, and ignore late event failures. */ + end(): void + /** + * Restart polling with an immediate read, retaining cards. + * @returns after the immediate read settles, without waiting for later polls. + */ + refresh(): Promise + /** + * Refresh current cards in a new UI language, retaining order and consumption. + * @param locale - active UI language; an unchanged value issues no request. + * @returns after content requests settle; failures retain the previous content. + */ + setLocale(locale: string): Promise + /** @param id - notice whose card passed a presented frame while visible. */ + shown(id: AccountNotificationId): void + /** @param id - foreground notice whose non-dismiss action was clicked; reports without removing the card. */ + ctaClicked(id: AccountNotificationId): void + /** @param id - foreground notice the user explicitly closed; reports only a dismissed event. */ + dismiss(id: AccountNotificationId): void +} + +/** One replaceable query cycle; an obsolete request cannot publish or schedule another read. */ +interface NotificationPoll { + intervalMs: number + timer?: ReturnType +} + +/** + * @param displayUntil - server expiration timestamp. + * @param at - milliseconds since epoch. + * @returns whether the notification can no longer be shown. + */ +function expired(displayUntil: string | null, at: number): boolean { + if (displayUntil === null) return false + const expires = Date.parse(displayUntil) + // An unparsable timestamp is not evidence of expiry, so the notice still shows. + return !Number.isNaN(expires) && expires <= at +} + +/** + * Own the read, display, and interaction reporting lifecycle of account notifications. + * @param options - collaborators and timings. + * @returns the controller the account plugin drives from account and settings state. + */ +export function createNotificationController(options: NotificationControllerOptions): NotificationController { + let scope: object | undefined + let locale = options.locale + let contentGeneration = 0 + /** Notice currently published to the sidebar, including the expiration checked at display time. */ + let current: readonly AccountNotice[] = [] + let poll: NotificationPoll | undefined + /** Notifications the card on screen already reported, so one mount cannot report display twice. */ + const reported = new Set() + const setCurrent = (notices: readonly AccountNotice[]): void => { + if (notices.length === current.length && notices.every((notice, index) => { + return JSON.stringify(notice) === JSON.stringify(current[index]) + })) return + const retained = new Set(notices.map(notice => notice.id)) + for (const id of reported) if (!retained.has(id)) reported.delete(id) + current = notices + options.publish(notices) + } + /** + * Keep a presented foreground card until dismissal or expiration, refreshing + * its copy when offered again; other live candidates follow in server order. + */ + const apply = (batch: AccountNotificationBatch, preserveCopy: boolean): void => { + const notifications = batch.notifications.map((notice) => { + const previous = preserveCopy ? current.find(value => value.id === notice.id) : undefined + return previous === undefined ? notice : { ...notice, title: previous.title, body: previous.body, actions: previous.actions } + }) + const foreground = current[0] + const retained = foreground !== undefined && reported.has(foreground.id) + ? notifications.find(notice => notice.id === foreground.id) ?? foreground + : undefined + const at = Date.now() + const candidates = notifications.filter(notice => !expired(notice.displayUntil, at)) + setCurrent(retained !== undefined && !expired(retained.displayUntil, at) + ? [retained, ...candidates.filter(notice => notice.id !== retained.id)] + : candidates) + } + + /** Refresh only cards that still belong to this account and language when the replies settle. */ + async function refreshContent(): Promise { + const scopeAtCall = scope + if (scopeAtCall === undefined || current.length === 0) return + const generation = ++contentGeneration + const requestedLocale = locale + const responses = await Promise.allSettled(current.map(async notice => options.readContent(notice.id, requestedLocale))) + if (scope !== scopeAtCall || generation !== contentGeneration) return + if (responses.some(response => response.status === 'rejected')) console.error('[deepseek-account] notification content read failed') + const updates = responses.flatMap(response => response.status === 'fulfilled' && response.value !== null ? [response.value] : []) + setCurrent(current.map((notice) => { + const update = updates.find(value => value.id === notice.id) + return update == null ? notice : { ...notice, title: update.title, body: update.body, actions: update.actions } + })) + } + + /** + * Read once for the active poll, retaining cards on failure. Replacement and + * sign-out discard late replies and prevent another read from being scheduled. + * @param pollAtRead - query cycle that owns this read. + * @returns after this read settles. + */ + async function runRead(pollAtRead: NotificationPoll): Promise { + const requestedLocale = locale + let batch: AccountNotificationBatch | null + try { batch = await options.read(requestedLocale) } + catch (_error) { + if (poll !== pollAtRead) return + console.error('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + batch = null + } + if (poll !== pollAtRead) return + if (batch !== null) { + pollAtRead.intervalMs = batch.nextPollAfterSeconds * 1_000 + apply(batch, requestedLocale !== locale) + if (requestedLocale !== locale) await refreshContent() + } + if (poll !== pollAtRead) return + pollAtRead.timer = setTimeout(() => { void runRead(pollAtRead) }, pollAtRead.intervalMs) + } + + const stopPolling = (): void => { + if (poll?.timer !== undefined) clearTimeout(poll.timer) + poll = undefined + } + const restartPolling = (): Promise => { + stopPolling() + poll = { intervalMs: options.pollIntervalMs } + return runRead(poll) + } + + /** Attempt each interaction once without changing the card on failure. */ + const report = async (id: AccountNotificationId, event: AccountNotificationEvent): Promise => { + const scopeAtReport = scope + if (scopeAtReport === undefined || current[0]?.id !== id || (event === 'displayed' && reported.has(id))) return + if (event === 'displayed') reported.add(id) + try { await options.reportEvent(id, event) } + catch (_error) { + if (scope === scopeAtReport) { + console.error('[deepseek-account] notification event report failed; keeping local state without retry', { event }) + } + } + } + + const endLifecycle = (): void => { + if (scope === undefined) return + stopPolling() + scope = undefined + contentGeneration++ + reported.clear() + setCurrent([]) + } + + return { + begin() { + scope ??= {} + void restartPolling() + }, + end: endLifecycle, + refresh(): Promise { + if (scope === undefined) return Promise.resolve() + return restartPolling() + }, + async setLocale(value) { + if (value === locale) return + locale = value + contentGeneration++ + await refreshContent() + }, + shown(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'displayed') + }, + ctaClicked(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'cta_clicked') + }, + dismiss(id) { + setCurrent(current.filter(notice => !expired(notice.displayUntil, Date.now()))) + if (current[0]?.id !== id) return + void report(id, 'dismissed') + setCurrent(current.slice(1).filter(notice => !expired(notice.displayUntil, Date.now()))) + }, + } +} diff --git a/packages/client/ui-account-notifications/src/config.ts b/packages/client/ui-account-notifications/src/config.ts new file mode 100644 index 0000000000..4a37e8392a --- /dev/null +++ b/packages/client/ui-account-notifications/src/config.ts @@ -0,0 +1,14 @@ +/** Public polling configuration shared by the notification Host and Client halves. */ +import Schema from '@deepseek-ai/schemastery' + +/** Initial polling interval before the server supplies its next delay. */ +export interface Config { + /** Initial query delay in milliseconds, replaced by each successful server response. */ + notificationPollIntervalMs: number +} +/** Validate notification polling configuration. */ +export const Config = Schema.object({ + notificationPollIntervalMs: Schema.natural().min(1).max(2_147_483_647).default(600_000), +}) +/** Bootstrap key for public notification configuration. */ +export const NOTIFICATIONS_CONFIG_GLOBAL = '__DSH_ACCOUNT_NOTIFICATIONS_CONFIG__' diff --git a/packages/client/ui-account-notifications/src/css-modules.d.ts b/packages/client/ui-account-notifications/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/client/ui-account-notifications/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/client/ui-account-notifications/src/index.ts b/packages/client/ui-account-notifications/src/index.ts new file mode 100644 index 0000000000..45b84f3cea --- /dev/null +++ b/packages/client/ui-account-notifications/src/index.ts @@ -0,0 +1,12 @@ +/** Publishes public configuration for the account notification client plugin. */ +import type { Context } from '@deepseek-ai/cordis' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { Config, NOTIFICATIONS_CONFIG_GLOBAL } from './config.ts' +export { Config } from './config.ts' + +/** @param ctx - Host page bootstrap collector. @param config - validated notification configuration. */ +export function apply(ctx: Context, config: Config): void { + ctx.on('webserver/index-inject', (table) => { + table.push({ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: config }) + }) +} diff --git a/packages/client/ui-account-notifications/tests/apply.client.spec.ts b/packages/client/ui-account-notifications/tests/apply.client.spec.ts new file mode 100644 index 0000000000..ba0b42bfd2 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/apply.client.spec.ts @@ -0,0 +1,350 @@ +// @vitest-environment jsdom +/** Notification integration shares the account plugin's single state stream. */ +import { afterEach, beforeEach, expect, onTestFinished, vi } from 'vitest' +import { ok } from '@deepseek-ai/dsh-remote-mock' +import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' +import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' +import type { AccountNotificationBatch, AccountNotificationId, AccountDetails, AccountView, SignInAttemptId } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountSectionInjected } from '@deepseek-ai/dsh-client-ui-settings-account/client' +import type { AccountNotificationsInjected } from '../src/client/AccountNotifications.tsx' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' +import { notification } from './notification-fixture.ts' + +const it = createClientTest({ roster: webApp }) +const SELF = '@deepseek-ai/dsh-client-ui-settings-account' +const view: AccountView = { status: 'signed-out', attempt: null, + links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } +const stored: AccountView = { ...view, status: 'credential-stored' } +function bonus(orderId: string, message = 'Awarded 5.00'): AccountNotificationBatch { + return { nextPollAfterSeconds: 300, notifications: [notification(orderId, { body: message, displayUntil: '2099-01-01T00:00:00Z' })] } +} +function operations(c: TestClient): AccountSectionInjected { + const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!() + return injected as AccountSectionInjected +} +function notificationOperations(c: TestClient): AccountNotificationsInjected { + const injected: object = c.ctx.slots.entries('settings.launcher.notifications')[0]!.inject!() + return injected as AccountNotificationsInjected +} +beforeEach(() => { vi.stubEnv('DSH_CLIENT_VERSION', '0.0.0-test') }) +afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); vi.restoreAllMocks() }) + +it('reads the unnotified bonus in the active locale and acknowledges only after the card renders', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' })) + // A successful read is not a display, so nothing may be acknowledged yet. + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + notificationOperations(c).shown(orderId as AccountNotificationId) + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'displayed', expect.objectContaining({ locale: 'en' })) + }) + notificationOperations(c).ctaClicked(orderId as AccountNotificationId) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith( + orderId, 'cta_clicked', expect.objectContaining({ locale: 'en' })) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(orderId) + notificationOperations(c).dismiss(orderId as AccountNotificationId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + await vi.waitFor(() => { + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledWith(orderId, 'dismissed', expect.objectContaining({ locale: 'en' })) + }) +}, 60_000) + +it('starts one notification poll across the credential commit and login-success frames', async ({ start }) => { + const c = await start() + c.mock.remote.session.initializeDefaultModel.mockResolvedValue(ok(undefined)) + const reads = c.mock.remote.account.getNotifications + const id = 'one-login' as SignInAttemptId + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'committing' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...stored, attempt: { id, phase: 'succeeded' } } }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) +}, 60_000) + +for (const outcome of ['null', 'failure'] as const) it(`queries a replacement credential without adopting the old ${outcome} reply`, async ({ start }) => { + const c = await start() + const previous = Promise.withResolvers>>() + const reads = c.mock.remote.account.getNotifications + reads.mockReturnValueOnce(previous.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + reads.mockResolvedValueOnce(ok(bonus('replacement-notice'))) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(2) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') + if (outcome === 'null') previous.resolve(ok(null)) + else previous.reject(new Error('obsolete credential')) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe('replacement-notice') +}, 60_000) + +it('clears notification cards and ignores old event failures when credentials change despite a failed replacement list', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + const event = Promise.withResolvers>>() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockReturnValueOnce(event.promise) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(id) + await vi.advanceTimersByTimeAsync(0) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + c.mock.remote.account.getNotifications.mockRejectedValueOnce(new Error('replacement offline')) + c.mock.streams.push('account/watch', { type: 'credentials-changed', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + event.reject(new Error('old request failed')) + await vi.advanceTimersByTimeAsync(3_000) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + expect(log).toHaveBeenCalledWith('[deepseek-account] notification read failed; retaining cards and retrying on the next poll') + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice without retrying its event across repeated signed-in frames', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const orderId = '4c1b0000-0000-4000-8000-000000000000' as AccountNotificationId + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + notificationOperations(c).shown(orderId) + await vi.advanceTimersByTimeAsync(0) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + await vi.advanceTimersByTimeAsync(60_000) + notificationOperations(c).shown(orderId) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId }) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledOnce() + expect(log).toHaveBeenCalledWith( + '[deepseek-account] notification event report failed; keeping local state without retry', { event: 'displayed' }) + } finally { vi.useRealTimers() } +}, 60_000) + +it('keeps the notice absent when the bonus read is refused, then shows the next read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const orderId = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValueOnce({ + ok: false, error: new RemoteError('gateway/internal', 'offline', {}), + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledOnce() }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + expect(c.mock.remote.account.reportNotificationEvent).not.toHaveBeenCalled() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(orderId))) + await actions.refreshAccount() + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toMatchObject({ id: orderId, body: 'Awarded 5.00' }) + }) +}, 60_000) + +it('drops the previous account notice and stops reading after sign-out', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000001'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') + }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]).toBeUndefined() + // Signing out ends the lifecycle, so no further read follows. + const reads = c.mock.remote.account.getNotifications.mock.calls.length + await new Promise((resolve) => { setTimeout(resolve, 20) }) + expect(c.mock.remote.account.getNotifications.mock.calls.length).toBe(reads) +}, 60_000) + +it('refreshes balances and notifications immediately on Settings entry', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + const balance: AccountDetails['balance'] = { + status: 'ready', value: [{ currency: 'CNY', balance: '12.34' }], bonusWallets: [{ currency: 'CNY', balance: '5.00' }], + } + c.mock.remote.account.getBalance.mockResolvedValue(ok(balance)) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + // Account activation starts with an immediate read. + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + // Signing in already read the wallet once through the details refresh. + const balances = c.mock.remote.account.getBalance.mock.calls.length + await actions.refreshAccount() + expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(balances + 1) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) + // The bonus read carries the active UI language. + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'en' })) +}, 60_000) + +it('replaces polling on startup, sign-in and Settings entry and stops on sign-out or unload', async ({ start }) => { + vi.stubGlobal(NOTIFICATIONS_CONFIG_GLOBAL, { notificationPollIntervalMs: 1_000 }) + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + vi.useFakeTimers() + try { + await c.reload(SELF) + await c.flush() + const actions = operations(c) + const reads = c.mock.remote.account.getNotifications + reads.mockClear() + // Startup receives the stored account in its initial stream snapshot. + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(500) + await actions.refreshAccount() + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(500) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(3) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(reads).toHaveBeenCalledTimes(4) + await c.unload(SELF) + await vi.advanceTimersByTimeAsync(2_000) + expect(reads).toHaveBeenCalledTimes(4) + } finally { vi.useRealTimers() } +}, 60_000) + +it('publishes a failed balance from a Settings entry without dropping the bonus read', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const actions = operations(c) + c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + await actions.refreshAccount() + expect(actions.hooks.account.getSnapshot().details?.balance).toEqual({ status: 'failed' }) + // The bonus read still ran: a failed wallet read does not cancel it. + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(2) +}, 60_000) + +it('refreshes consumed notification content on a locale change without reading the unconsumed list again', async ({ start }) => { + vi.stubGlobal('dshDesktop', {}) + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.reportNotificationEvent.mockResolvedValue(ok(true)) + c.mock.remote.account.getNotificationContent.mockResolvedValue(ok(notification(id, { title: '公告', body: '新的中文内容' }))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.id).toBe(id) }) + notificationOperations(c).shown(id as AccountNotificationId) + await vi.waitFor(() => { expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) }) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('新的中文内容') }) + expect(c.mock.remote.account.getNotificationContent).toHaveBeenCalledWith( id, expect.objectContaining({ locale: 'zh' })) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + expect(c.mock.remote.account.reportNotificationEvent).toHaveBeenCalledTimes(1) +}, 60_000) + +it('retains notification content when the localization RPC is refused', async ({ start }) => { + const c = await start() + const id = '4c1b0000-0000-4000-8000-000000000000' + const output = vi.spyOn(console, 'error').mockImplementation(() => {}) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus(id))) + c.mock.remote.account.getNotificationContent.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + c.mock.remote.settings.mutate.mockResolvedValue(ok({ + ns: 'locale', autoGenerate: false, schema: { type: 'object' }, value: { preference: 'zh' }, + applies: 'live', secrets: [], revision: 1, + })) + c.ctx.locale.setLocale('zh') + await vi.waitFor(() => { expect(output).toHaveBeenCalledWith('[deepseek-account] notification content read failed') }) + expect(notificationOperations(c).hooks.notices.getSnapshot()?.[0]?.body).toBe('Awarded 5.00') +}, 60_000) + +it('clears notifications and stops polling when the account carrier fails', async ({ start }) => { + const c = await start() + const open = c.ctx.remote.$stream.bind(c.ctx.remote) + let fail: (() => void) | undefined + vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { + if (options.name === 'account') fail = () => { options.carrierFailed?.(new Error('connection lost')) } + return open(options) + }) + await c.reload(SELF) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000000'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toHaveLength(1) + const reads = c.mock.remote.account.getNotifications.mock.calls.length + vi.useFakeTimers() + try { + fail?.() + expect(notificationOperations(c).hooks.notices.getSnapshot()).toEqual([]) + await vi.advanceTimersByTimeAsync(600_000) + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(reads) + } finally { vi.useRealTimers() } +}, 60_000) + +it('reloads notifications without opening another account stream', async ({ start }) => { + const c = await start() + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('retained'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + const stream = vi.spyOn(c.ctx.remote, '$stream') + const before = c.mock.remote.account.getNotifications.mock.calls.length + await c.reload('@deepseek-ai/dsh-client-ui-account-notifications') + await c.flush() + expect(stream).not.toHaveBeenCalled() + expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(before + 1) + expect(notificationOperations(c).hooks.notices.getSnapshot()[0]?.id).toBe('retained') +}) + +it('publishes notification changes through one stable source and releases its subscribers', async ({ start }) => { + const c = await start() + const source = notificationOperations(c).hooks.notices + expect(notificationOperations(c).hooks.notices).toBe(source) + const listener = vi.fn() + const dispose = source.subscribe(listener) + onTestFinished(dispose) + c.mock.remote.account.getNotifications.mockResolvedValue(ok(bonus('first'))) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await c.flush() + expect(source.getSnapshot()[0]?.id).toBe('first') + expect(listener).toHaveBeenCalled() + dispose() + listener.mockClear() + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) + await c.flush() + expect(source.getSnapshot()).toEqual([]) + expect(listener).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/config.client.spec.ts b/packages/client/ui-account-notifications/tests/config.client.spec.ts new file mode 100644 index 0000000000..7c479ec7f4 --- /dev/null +++ b/packages/client/ui-account-notifications/tests/config.client.spec.ts @@ -0,0 +1,27 @@ +/** Notification configuration reaches the client without account secrets. */ +import { Context } from '@deepseek-ai/cordis' +import { expect, it, onTestFinished } from 'vitest' +import type { IndexInjection, WebServer } from '@deepseek-ai/dsh-host-webserver' +import { apply, Config } from '../src/index.ts' +import { NOTIFICATIONS_CONFIG_GLOBAL } from '../src/config.ts' + +it('publishes polling configuration and removes the publisher on disposal', async () => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + await ctx.plugin({ apply, Config }, { notificationPollIntervalMs: 250 }) + const table: IndexInjection[] = [] + const peer = { principal: { kind: 'owner' } } as Parameters[1] + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([{ kind: 'global', name: NOTIFICATIONS_CONFIG_GLOBAL, value: { notificationPollIntervalMs: 250 } }]) + await ctx.fiber.dispose() + table.length = 0 + ctx.emit('webserver/index-inject', table, peer) + expect(table).toEqual([]) +}) + +it('defaults to ten minutes and rejects intervals outside browser timer limits', () => { + expect(Config({}).notificationPollIntervalMs).toBe(600_000) + for (const notificationPollIntervalMs of [0, -1, 1.5, 2_147_483_648]) { + expect(() => Config({ notificationPollIntervalMs })).toThrow() + } +}) diff --git a/packages/client/ui-settings-account/tests/expected/notice.txt b/packages/client/ui-account-notifications/tests/expected/notice.txt similarity index 100% rename from packages/client/ui-settings-account/tests/expected/notice.txt rename to packages/client/ui-account-notifications/tests/expected/notice.txt diff --git a/packages/client/ui-settings-account/tests/notice-transition.client.spec.ts b/packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts similarity index 100% rename from packages/client/ui-settings-account/tests/notice-transition.client.spec.ts rename to packages/client/ui-account-notifications/tests/notice-transition.client.spec.ts diff --git a/packages/client/ui-settings-account/tests/notice.client.spec.tsx b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx similarity index 50% rename from packages/client/ui-settings-account/tests/notice.client.spec.tsx rename to packages/client/ui-account-notifications/tests/notice.client.spec.tsx index 5fbbfc3994..6491f93619 100644 --- a/packages/client/ui-settings-account/tests/notice.client.spec.tsx +++ b/packages/client/ui-account-notifications/tests/notice.client.spec.tsx @@ -1,17 +1,38 @@ // @vitest-environment jsdom /** * The bonus notice card reports display only when the server's copy is - * actually on screen: it needs an anchor position, a visible document, and one - * presented frame. Closing counts as seen because the user acted on it. + * actually on screen: it needs a visible sidebar and document, and one presented + * frame. Closing counts as seen because the user acted on it. */ -import { createRef } from 'react' import { cleanup, fireEvent, render, screen } from '@testing-library/react' import { act } from 'react' import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import type { AccountBonusOrderId } from '@deepseek-ai/dsh-deepseek-account/types' -import { AccountNoticeStack } from '../src/client/AccountNotice.tsx' +import { AccountNoticeStack } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' const disconnect = vi.fn() +const observers: VisibilityObserver[] = [] +let intersecting = true + +class VisibilityObserver implements IntersectionObserver { + readonly root = null + readonly rootMargin = '0px' + readonly scrollMargin = '0px' + readonly thresholds = [0] + private target!: Element + constructor(private readonly callback: IntersectionObserverCallback) { observers.push(this) } + observe(target: Element): void { this.target = target; this.notify(intersecting) } + unobserve(): void {} + disconnect = disconnect + takeRecords(): IntersectionObserverEntry[] { return [] } + notify(visible: boolean): void { + const rect = new DOMRect(0, 0, 260, 100) + this.callback([{ + target: this.target, isIntersecting: visible, intersectionRatio: visible ? 1 : 0, + time: 0, boundingClientRect: rect, intersectionRect: rect, rootBounds: null, + }], this) + } +} let visibility: 'visible' | 'hidden' = 'visible' /** Frame callbacks the card scheduled, in order. */ let frames: (() => void)[] = [] @@ -23,7 +44,10 @@ function setVisibility(value: 'visible' | 'hidden'): void { beforeEach(() => { visibility = 'visible' + intersecting = true + observers.length = 0 frames = [] + vi.stubGlobal('IntersectionObserver', VisibilityObserver) Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => visibility }) // jsdom drives requestAnimationFrame from its own clock, so the test presents frames explicitly. vi.stubGlobal('requestAnimationFrame', (callback: () => void) => { frames.push(callback); return frames.length }) @@ -32,15 +56,13 @@ beforeEach(() => { afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); vi.restoreAllMocks(); disconnect.mockClear() }) function mount(id: string, onShown = vi.fn(), onDismiss = vi.fn()) { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() + const onCtaClicked = vi.fn() const view = render(<> -
- + {}} + notices={[notification(id, { displayUntil: '2099-01-01T00:00:00Z' })]} + onShown={onShown} onCtaClicked={onCtaClicked} onDismiss={onDismiss} /> ) - return { view, onShown, onDismiss } + return { view, onShown, onCtaClicked, onDismiss } } /** @@ -89,12 +111,13 @@ it('waits for another visible frame when the document hides before the follow-up expect(onShown).toHaveBeenCalledExactlyOnceWith('order-1') }) -it('reports dismissal so closing the card counts as seen', async () => { - const { onShown, onDismiss } = mount('order-1') +it('reports dismissal without a CTA click when the close icon is clicked', async () => { + const { onShown, onCtaClicked, onDismiss } = mount('order-1') await presentFrames() fireEvent.click(screen.getByRole('button', { name: 'Close' })) expect(onDismiss).toHaveBeenCalledWith('order-1') expect(onShown).toHaveBeenCalledOnce() + expect(onCtaClicked).not.toHaveBeenCalled() }) it('reports neither display nor dismissal when unmounted before its frame', async () => { @@ -140,17 +163,14 @@ it.each([true, false])('cancels the presentation task when the card unmounts fir }) it('keeps back cards mounted but inaccessible and reports them only after promotion', async () => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect = disconnect }) - const anchor = createRef() const onShown = vi.fn() const onDismiss = vi.fn() - const notices = ['first', 'second', 'third'].map(id => ({ - orderId: id as AccountBonusOrderId, title: id, message: `${id} copy`, expiresAt: '', + const notices = ['first', 'second', 'third'].map(id => notification(id, { + title: id, body: `${id} copy`, actions: [{ label: 'Dismiss', style: 'secondary', target: { type: 'dismiss' } }], })) const tree = (remaining: typeof notices) => <> -
- + {}} + onShown={onShown} onCtaClicked={vi.fn()} onDismiss={onDismiss} /> const view = render(tree(notices)) const second = screen.getByText('second copy').closest('aside') @@ -170,12 +190,84 @@ it('keeps back cards mounted but inaccessible and reports them only after promot expect(onShown).toHaveBeenCalledTimes(2) }) -it('does not acknowledge a notice before an anchor is mounted', async () => { - const onShown = vi.fn() - render(()} title="News" closeLabel="Close" - notices={[{ orderId: 'notice' as AccountBonusOrderId, message: 'News', expiresAt: '' }]} - onShown={onShown} onDismiss={vi.fn()} />) +it('keeps sidebar cards mounted without reporting until they enter the viewport', async () => { + intersecting = false + const { view, onShown, onDismiss } = mount('notice') + const card = view.container.querySelector('aside') + expect(card).not.toBeNull() + expect(view.container.contains(screen.getByRole('status'))).toBe(true) await presentFrames() expect(onShown).not.toHaveBeenCalled() - expect(screen.queryByRole('status')).toBeNull() + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + act(() => { observers[0]!.notify(false); observers[0]!.notify(true) }) + await presentFrames() + expect(view.container.querySelector('aside')).toBe(card) + expect(onShown).toHaveBeenCalledOnce() + expect(onDismiss).not.toHaveBeenCalled() +}) + +it.each(['hidden', 'inert'])('does not report when its sidebar becomes %s before the presentation task', async (attribute) => { + const { view, onShown } = mount('notice') + await presentFrames(() => { view.container.setAttribute(attribute, '') }) + expect(onShown).not.toHaveBeenCalled() + view.container.removeAttribute(attribute) + act(() => { observers[0]!.notify(true) }) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') +}) + +it('does not report when the card leaves the viewport before the presentation task', async () => { + const { onShown } = mount('notice') + await presentFrames(() => { observers[0]!.notify(false) }) + expect(onShown).not.toHaveBeenCalled() +}) + +it.each(['primary', 'secondary'] as const)('reports non-dismiss %s actions and keeps focus while localized content changes', async (style) => { + const onShown = vi.fn() + const onDismiss = vi.fn() + const onOpenAccount = vi.fn() + const onCtaClicked = vi.fn() + const content = (chinese: boolean) => notification('notice', { + title: chinese ? '产品公告' : 'Product news', body: chinese ? '新功能已上线' : 'New features', + actions: [ + { label: chinese ? '查看余额' : 'View balance', style, target: { type: 'app_route', name: 'account' } }, + { label: chinese ? '知道了' : 'Got it', style, target: { type: 'dismiss' } }, + ], + }) + const tree = (chinese: boolean) => <> + + + const view = render(tree(false)) + await presentFrames() + const button = screen.getByRole('button', { name: 'View balance' }) + button.focus() + fireEvent.click(button) + expect(onOpenAccount).toHaveBeenCalledOnce() + expect(onCtaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(onDismiss).not.toHaveBeenCalled() + view.rerender(tree(true)) + expect(screen.getByRole('button', { name: '查看余额' })).toBe(button) + expect(document.activeElement).toBe(button) + await presentFrames() + expect(onShown).toHaveBeenCalledExactlyOnceWith('notice') + fireEvent.click(screen.getByRole('button', { name: '知道了' })) + expect(onDismiss).toHaveBeenCalledExactlyOnceWith('notice') + expect(onCtaClicked).toHaveBeenCalledOnce() +}) + +it('renders separate buttons for repeated action targets', () => { + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + render(<> + {}} + onShown={vi.fn()} onCtaClicked={vi.fn()} onDismiss={vi.fn()} notices={[notification('notice', { actions: [ + { label: 'Got it', style: 'primary', target: { type: 'dismiss' } }, + { label: 'Later', style: 'secondary', target: { type: 'dismiss' } }, + ] })]} /> + ) + expect(screen.getByRole('button', { name: 'Got it' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Later' })).toBeTruthy() + expect(output).not.toHaveBeenCalled() }) diff --git a/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts new file mode 100644 index 0000000000..211f8e58cd --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-controller.client.spec.ts @@ -0,0 +1,822 @@ +// @vitest-environment jsdom +/** + * Notification lifecycle: account activation and Settings entry replace polling + * with an immediate query. Display reports follow a presented frame. + * Each event is attempted once; nothing + * about a notice survives sign-out or unload. + */ +import { afterEach, expect, it, vi } from 'vitest' +import type { AccountNotificationBatch, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' +import { createNotificationController, type AccountNotice, type NotificationController } from '../src/client/notification-controller.ts' +import { notification } from './notification-fixture.ts' + +const TIMING = { pollIntervalMs: 600_000 } +const controllers = new Set() + +/** + * @param id - notification identifier. + * @param displayUntil - server expiration. + * @returns one unconsumed notification as the Host projects it. + */ +function batch(id: string, displayUntil: string | null = '2099-01-01T00:00:00Z'): AccountNotificationBatch { + return { + nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: [notification(id, { displayUntil })], + } +} + +function setup() { + const read = vi.fn(async (): Promise => null) + const readContent = vi.fn(async (): Promise => null) + const displayed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const dismissed = vi.fn(async (_id: AccountNotificationId): Promise => true) + const clicked = vi.fn(async (_id: AccountNotificationId): Promise => true) + const stacks: (readonly AccountNotice[])[] = [] + const published: (AccountNotice | null)[] = [] + const controller = createNotificationController({ + ...TIMING, locale: 'en', read, readContent, + reportEvent: (id, event) => ({ displayed: displayed, cta_clicked: clicked, dismissed })[event](id), + publish: (notices) => { stacks.push(notices); published.push(notices[0] ?? null) }, + }) + controllers.add(controller) + /** @returns the most recently published notice. */ + const latest = (): AccountNotice | null | undefined => published.at(-1) + return { controller, read, readContent, displayed, clicked, dismissed, published, latest, stacks } +} + +afterEach(() => { + for (const controller of controllers) controller.end() + controllers.clear() + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it('reads immediately and starts the next delay only after the current request settles', async () => { + vi.useFakeTimers() + const { controller, read } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + controller.begin() + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 3) + expect(read).toHaveBeenCalledTimes(1) + finish(null) + await vi.advanceTimersByTimeAsync(0) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + controller.end() +}) + +it.each(['begin', 'refresh'] as const)('restarts polling immediately on %s and cancels the previous delay', async (trigger) => { + vi.useFakeTimers() + const { controller, read } = setup() + controller.begin() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + if (trigger === 'begin') controller.begin() + else await controller.refresh() + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + controller.end() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('discards a superseded request without publishing or resuming its poll', async () => { + vi.useFakeTimers() + const { controller, read, latest } = setup() + let finish!: (value: AccountNotificationBatch | null) => void + read.mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) + read.mockResolvedValue(batch('new')) + controller.begin() + await controller.refresh() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + finish(batch('old')) + await vi.advanceTimersByTimeAsync(0) + expect(latest()?.id).toBe('new') + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs / 2) + expect(read).toHaveBeenCalledTimes(3) +}) + +it('does not report or reschedule an obsolete request failure', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + let reject!: (error: Error) => void + read.mockReturnValueOnce(new Promise((_resolve, fail) => { reject = fail })) + controller.begin() + controller.end() + reject(new Error('offline')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(read).toHaveBeenCalledTimes(1) + expect(log).not.toHaveBeenCalled() +}) + +it('does not resume polling after sign-out while a list reply is refreshing language content', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + const content = Promise.withResolvers() + read.mockReturnValueOnce(response.promise) + readContent.mockReturnValueOnce(content.promise) + controller.begin() + await controller.setLocale('zh') + response.resolve(batch('first')) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledWith('first', 'zh') + controller.end() + content.resolve(notification('first')) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs * 2) + expect(latest()).toBeNull() + expect(read).toHaveBeenCalledOnce() +}) + +it('retains the shown card on failure and polls again after the configured delay', async () => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read, latest, displayed } = setup() + read.mockResolvedValueOnce(batch('first')).mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue(batch('second')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(latest()?.id).toBe('first') + expect(log).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(read).toHaveBeenCalledTimes(3) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledOnce() +}) + +it('uses each server delay in seconds, retains it after failure, and resets it when polling restarts', async () => { + vi.useFakeTimers() + vi.spyOn(console, 'error').mockImplementation(() => {}) + const { controller, read } = setup() + read.mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 2 }) + .mockResolvedValueOnce({ ...batch('first'), notifications: [], nextPollAfterSeconds: 5 }) + .mockRejectedValueOnce(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(1_999) + expect(read).toHaveBeenCalledOnce() + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(4_999) + expect(read).toHaveBeenCalledTimes(3) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(4) + await controller.refresh() + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs - 1) + expect(read).toHaveBeenCalledTimes(5) + await vi.advanceTimersByTimeAsync(1) + expect(read).toHaveBeenCalledTimes(6) +}) + +it('publishes the server copy for the first unconsumed notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + controller.end() +}) + +it('reports display only after a presented frame and keeps the card until it is closed', async () => { + const { controller, read, displayed, published, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + expect(displayed).not.toHaveBeenCalled() + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + // A refresh still offering the notification must not republish the open card. + const publishedBefore = published.length + await controller.refresh() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(2) }) + expect(published.length).toBe(publishedBefore) + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + expect(latest()).toBeNull() + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it.each(['aborted', 'null'] as const)("does not adopt the replaced credential's in-flight read when it answers %s", async (answer) => { + vi.useFakeTimers() + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockRejectedValue(new Error('offline')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + // Account A's next signed-in frame starts a read the Host abandons when the + // credential is replaced by B. B's frame must not inherit it: A's answer names + // the replaced account, so adopting it would leave B with no read of its own. + const abandoned = Promise.withResolvers() + read.mockReturnValueOnce(abandoned.promise) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + expect(read).toHaveBeenCalledTimes(3) + expect(latest()).toMatchObject({ id: 'notice-2' }) + if (answer === 'aborted') abandoned.reject(new Error('aborted')) + else abandoned.resolve(null) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + // The abandoned answer cannot restore the previous account's card. + expect(latest()).toMatchObject({ id: 'notice-2' }) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('refreshes the copy of the notification already on screen when a read offers it again', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', body: 'Server copy 5.00' }) }) + // The same notification arrives with new copy: its card updates in place instead of being replaced. + read.mockResolvedValue({ ...batch('notice-1'), notifications: [{ ...batch('notice-1').notifications[0]!, title: 'Updated title', body: 'Updated copy' }] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1', title: 'Updated title', body: 'Updated copy' }) + controller.end() +}) + +it('withdraws a card the user never saw when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // The card never reported a presented frame, so an empty read withdraws it. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it.each(['omitted', 'reordered'] as const)('keeps the displayed card in front when the next read leaves it %s', async (placement) => { + vi.useFakeTimers() + const { controller, read, displayed, stacks } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const next = ['second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: placement === 'reordered' ? [...next, ...batch('first', null).notifications] : next }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['first', 'second', 'third']) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second', 'third']) + controller.shown('second' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(2) + expect(displayed).toHaveBeenLastCalledWith('second') + } finally { + controller.end() + } +}) + +it.each(['elapsed', 'updated'] as const)('removes a displayed card whose expiration %s before the next read', async (expiration) => { + vi.useFakeTimers() + vi.setSystemTime(new Date('2026-10-27T00:00:00Z')) + const { controller, read, stacks } = setup() + try { + read.mockResolvedValue(batch('first', '2026-10-28T00:00:00Z')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + if (expiration === 'elapsed') vi.setSystemTime(new Date('2026-10-28T00:00:00Z')) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...expiration === 'updated' ? batch('first', '2026-10-27T00:00:00Z').notifications : [], + ...batch('second', null).notifications, + ] }) + await controller.refresh() + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['second']) + } finally { + controller.end() + } +}) + +it('ignores a dismissal that names a notification the card does not show', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.dismiss('notice-2' as AccountNotificationId) + // The other notification's dismissal neither withdraws this card nor reports its display. + expect(latest()).toMatchObject({ id: 'notice-1' }) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays a notification offered again after a previous sign-in reported it', async () => { + const first = setup() + first.read.mockResolvedValue(batch('notice-1')) + first.controller.begin() + await vi.waitFor(() => { expect(first.latest()).toMatchObject({ id: 'notice-1' }) }) + first.controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(first.displayed).toHaveBeenCalledTimes(1) }) + first.controller.end() + // Nothing is remembered, so the same notification the server still offers displays again. + const second = setup() + second.read.mockResolvedValue(batch('notice-1')) + second.controller.begin() + await vi.waitFor(() => { expect(second.latest()).toMatchObject({ id: 'notice-1' }) }) + second.controller.end() +}) + +it('discards the previous account card when a credential is replaced without a signed-out frame', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + displayed.mockResolvedValue(false) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledOnce() }) + // The credential is replaced in place: another signed-in frame arrives, the read + // names the other account, and no signed-out frame ever describes the switch. + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('reports each new display of a notification offered again after dismissal', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + // Closing the card withdraws it; the next read of the same notification is a new card. + controller.dismiss('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + await controller.refresh() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(2) }) + controller.end() +}) + +it('keeps the visible card when a read offers no notification', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + // A card the user has already seen keeps its place. + controller.shown('notice-1' as AccountNotificationId) + // A Settings entry whose read returns nothing must not pull the card out from under the user. + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [] }) + await controller.refresh() + expect(latest()).toMatchObject({ id: 'notice-1' }) + controller.dismiss('notice-1' as AccountNotificationId) + await controller.refresh() + expect(latest()).toBeNull() + controller.end() +}) + +it('withdraws the displayed card when the signed-in account changes', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + controller.end() + read.mockResolvedValue(batch('notice-2')) + controller.begin() + await Promise.resolve() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-2' }) }) + controller.end() +}) + +it('never reports display after the plugin unloads', async () => { + vi.useFakeTimers() + const { controller, read, displayed } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.end() + controller.shown('notice-1' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + expect(displayed).not.toHaveBeenCalled() +}) + +it('suppresses a notification that expired before its first presented frame', async () => { + const { controller, read, latest } = setup() + read.mockResolvedValue(batch('notice-1', '2000-01-01T00:00:00Z')) + controller.begin() + await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(1) }) + expect(latest()).toBeUndefined() + controller.end() +}) + +it('does not record a display when the award expired before the card could render', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1')) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1' }) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + // The card refuses to render an expired award, so no display is reported. + controller.shown('notice-1' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + controller.end() +}) + +it('displays and reports a notice without expiration', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('notice-1', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()).toMatchObject({ id: 'notice-1', displayUntil: null }) }) + controller.shown('notice-1' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledWith('notice-1') }) + controller.end() +}) + +it('publishes every live notice and reports display only for the foreground card', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + const notifications = ['first', 'second', 'third'].flatMap(id => batch(id, null).notifications) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toEqual(notifications) }) + controller.shown('second' as AccountNotificationId) + controller.dismiss('third' as AccountNotificationId) + expect(displayed).not.toHaveBeenCalled() + expect(stacks.at(-1)).toEqual(notifications) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledExactlyOnceWith('first') }) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(1)) + expect(displayed).toHaveBeenCalledTimes(1) + controller.shown('second' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenLastCalledWith('second') }) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual(notifications.slice(2)) + controller.dismiss('third' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed.mock.calls).toEqual([['first'], ['second'], ['third']]) + controller.end() +}) + +it('drops queued notices that expire before promotion without reporting display', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', null).notifications, + ...batch('expired', '2099-01-01T00:00:00Z').notifications, + ...batch('last', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(3) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('first' as AccountNotificationId) + expect(stacks.at(-1)?.map(notice => notice.id)).toEqual(['last']) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + controller.end() +}) + +it('publishes a title-only refresh without reporting the same display twice', async () => { + const { controller, read, displayed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.waitFor(() => { expect(latest()?.id).toBe('first') }) + controller.shown('first' as AccountNotificationId) + await vi.waitFor(() => { expect(displayed).toHaveBeenCalledTimes(1) }) + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, + notifications: batch('first', null).notifications.map(notice => ({ ...notice, title: 'Updated title' })) }) + await controller.refresh() + expect(latest()?.title).toBe('Updated title') + controller.shown('first' as AccountNotificationId) + expect(displayed).toHaveBeenCalledTimes(1) + controller.end() +}) + +it('does not read or report display outside an active account lifecycle', async () => { + const { controller, read, displayed } = setup() + await controller.refresh() + expect(read).not.toHaveBeenCalled() + expect(displayed).not.toHaveBeenCalled() +}) + +it('closes the visible notice when the preceding card expires before its display callback', async () => { + const { controller, read, displayed, dismissed, stacks } = setup() + read.mockResolvedValue({ nextPollAfterSeconds: TIMING.pollIntervalMs / 1_000, notifications: [ + ...batch('first', '2099-01-01T00:00:00Z').notifications, + ...batch('second', null).notifications, + ] }) + controller.begin() + await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(2) }) + vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) + controller.dismiss('second' as AccountNotificationId) + expect(stacks.at(-1)).toEqual([]) + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).toHaveBeenCalledExactlyOnceWith('second') + controller.end() +}) + +it('refreshes a consumed card in place on language changes without another list or display report', async () => { + vi.useFakeTimers() + const { controller, read, readContent, displayed, latest } = setup() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + const actions = [{ label: '知道了', style: 'secondary', target: { type: 'dismiss' } }] as const + readContent.mockResolvedValue(notification('first', { title: '通知', body: '新的中文内容', actions })) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()).toMatchObject({ id: 'first', title: '通知', body: '新的中文内容', actions }) + expect(read).toHaveBeenCalledTimes(1) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(1) + await controller.setLocale('zh') + expect(readContent).toHaveBeenCalledTimes(1) + } finally { controller.end() } +}) + +it('ignores an earlier language response after a later language change', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const first = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(first.promise) + const changing = controller.setLocale('zh') + readContent.mockResolvedValueOnce(notification('first', { body: 'Latest English content' })) + await controller.setLocale('en') + first.resolve(notification('first', { body: '过时的中文内容' })) + await changing + expect(latest()?.body).toBe('Latest English content') + } finally { first.resolve(null); controller.end() } +}) + +it.each(['dismiss', 'sign-out', 'account-change'] as const)('does not restore content after %s', async (change) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + readContent.mockReturnValueOnce(response.promise) + const changing = controller.setLocale('zh') + if (change === 'dismiss') controller.dismiss('first' as AccountNotificationId) + else if (change === 'sign-out') controller.end() + else { + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await Promise.resolve() + } + response.resolve(notification('first', { body: '迟到的内容' })) + await changing + expect(latest()?.id ?? null).toBe(change === 'account-change' ? 'second' : null) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['failure', 'absent'] as const)('retains the current content when localization returns %s', async (outcome) => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) + try { + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (outcome === 'failure') readContent.mockRejectedValueOnce(new Error('private-detail')) + await controller.setLocale('zh') + expect(latest()?.body).toBe('Server copy 5.00') + expect(JSON.stringify(output.mock.calls)).not.toContain('private-detail') + expect(output).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + } finally { controller.end() } +}) + +it('localizes notifications returned by a list request started before the language changed', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest } = setup() + const response = Promise.withResolvers() + try { + read.mockReturnValueOnce(response.promise) + controller.begin() + await controller.setLocale('zh') + expect(readContent).not.toHaveBeenCalled() + readContent.mockResolvedValueOnce(notification('first', { body: '当前语言内容' })) + response.resolve(batch('first', null)) + await vi.advanceTimersByTimeAsync(0) + expect(readContent).toHaveBeenCalledExactlyOnceWith('first', 'zh') + expect(latest()?.body).toBe('当前语言内容') + } finally { response.resolve(null); controller.end() } +}) + +it('keeps localized copy while an older list response refreshes other notification fields', async () => { + vi.useFakeTimers() + const { controller, read, readContent, latest, published } = setup() + const response = Promise.withResolvers() + try { + read.mockResolvedValueOnce(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + read.mockReturnValueOnce(response.promise) + const refreshing = controller.refresh() + readContent.mockResolvedValue(notification('first', { body: '新的中文内容' })) + await controller.setLocale('zh') + const count = published.length + response.resolve(batch('first', null)) + await refreshing + expect(latest()?.body).toBe('新的中文内容') + expect(published.slice(count).every(notice => notice?.body === '新的中文内容')).toBe(true) + } finally { response.resolve(null); controller.end() } +}) + +it.each(['shown', 'before-frame'] as const)('reports an explicit dismissal once when closed %s', async (presentation) => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first')) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (presentation === 'shown') { + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() + } + controller.dismiss('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(0) + expect(displayed).toHaveBeenCalledTimes(presentation === 'shown' ? 1 : 0) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') +}) + +it.each(['expiry', 'account-change', 'sign-out', 'unload'] as const)('does not report dismissal on %s cleanup or from a stale callback', async (cleanup) => { + vi.useFakeTimers() + const { controller, read, dismissed } = setup() + const deadline = new Date(Date.now() + 100).toISOString() + read.mockResolvedValue(batch('first', cleanup === 'expiry' ? deadline : null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + if (cleanup === 'expiry') await vi.advanceTimersByTimeAsync(100) + else if (cleanup === 'account-change') { + controller.end() + read.mockResolvedValue(batch('second')) + controller.begin() + await Promise.resolve() + } else controller.end() + controller.dismiss('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(0) + expect(dismissed).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('attempts each display and dismissal once after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + for (const report of [displayed, dismissed]) { + if (outcome === 'failure') report.mockRejectedValue(new Error('private-detail')) + else report.mockResolvedValue(outcome === 'success') + } + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.shown('first' as AccountNotificationId) + await vi.advanceTimersByTimeAsync(TIMING.pollIntervalMs) + controller.begin() + await controller.refresh() + controller.shown('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).toHaveBeenCalledExactlyOnceWith('first') + controller.dismiss('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + expect(latest()).toBeNull() + await vi.advanceTimersByTimeAsync(60_000) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 2 : 0) + expect(JSON.stringify(log.mock.calls)).not.toContain('private-detail') +}) + +it('reports the next card and dismissal without waiting for an earlier display report', async () => { + vi.useFakeTimers() + const { controller, read, displayed, dismissed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue({ ...batch('first', null), notifications: [notification('first'), notification('second')] }) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.dismiss('first' as AccountNotificationId) + controller.shown('second' as AccountNotificationId) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + } finally { + pending.resolve(true) + await pending.promise + controller.end() + } +}) + +it.each(['success', 'failure'] as const)('ignores a late event %s after changing credentials', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, displayed, latest } = setup() + const pending = Promise.withResolvers() + displayed.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('first' as AccountNotificationId) + controller.end() + read.mockResolvedValue(batch('second', null)) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.shown('second' as AccountNotificationId) + if (outcome === 'success') pending.resolve(true) + else pending.reject(new Error('obsolete')) + await vi.advanceTimersByTimeAsync(60_000) + expect(latest()?.id).toBe('second') + expect(displayed.mock.calls).toEqual([['first'], ['second']]) + expect(log).not.toHaveBeenCalled() +}) + +it.each(['success', 'refused', 'failure'] as const)('reports a CTA click once without dismissing or retrying after %s', async (outcome) => { + vi.useFakeTimers() + const log = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const { controller, read, clicked, displayed, dismissed, latest } = setup() + read.mockResolvedValue(batch('first', null)) + if (outcome === 'failure') clicked.mockRejectedValue(new Error('offline')) + else clicked.mockResolvedValue(outcome === 'success') + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + expect(displayed).not.toHaveBeenCalled() + expect(dismissed).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(60_000) + expect(clicked).toHaveBeenCalledExactlyOnceWith('first') + expect(log).toHaveBeenCalledTimes(outcome === 'failure' ? 1 : 0) + controller.ctaClicked('first' as AccountNotificationId) + expect(clicked).toHaveBeenCalledTimes(2) + await vi.advanceTimersByTimeAsync(0) +}) + +it('keeps dismissal available while a CTA-click report is pending', async () => { + vi.useFakeTimers() + const { controller, read, clicked, dismissed, latest } = setup() + const pending = Promise.withResolvers() + clicked.mockReturnValueOnce(pending.promise) + read.mockResolvedValue(batch('first', null)) + try { + controller.begin() + await vi.advanceTimersByTimeAsync(0) + controller.ctaClicked('first' as AccountNotificationId) + expect(latest()?.id).toBe('first') + controller.dismiss('first' as AccountNotificationId) + expect(dismissed).toHaveBeenCalledExactlyOnceWith('first') + expect(latest()).toBeNull() + } finally { + pending.resolve(true) + await pending.promise + } +}) + +it.each(['back-card', 'expired', 'signed-out'] as const)('ignores a CTA click from a %s notification', async (state) => { + vi.useFakeTimers() + const { controller, read, clicked } = setup() + read.mockResolvedValue({ ...batch('first', null), notifications: [ + notification('first', { displayUntil: '2099-01-01T00:00:00Z' }), notification('second'), + ] }) + controller.begin() + await vi.advanceTimersByTimeAsync(0) + if (state === 'signed-out') controller.end() + else if (state === 'expired') vi.setSystemTime(new Date('2100-01-01T00:00:00Z')) + controller.ctaClicked((state === 'back-card' ? 'second' : 'first') as AccountNotificationId) + expect(clicked).not.toHaveBeenCalled() +}) diff --git a/packages/client/ui-account-notifications/tests/notification-fixture.ts b/packages/client/ui-account-notifications/tests/notification-fixture.ts new file mode 100644 index 0000000000..d60b0da8dc --- /dev/null +++ b/packages/client/ui-account-notifications/tests/notification-fixture.ts @@ -0,0 +1,15 @@ +/** Complete account notification values shared by presentation tests. */ +import type { AccountNotification, AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' + +/** + * Create one notification without wire parsing or account lifecycle effects. + * @param id - stable notification identity. + * @param fields - scenario-specific notification fields. + * @returns localized display content with no actions or deadline unless supplied. + */ +export function notification(id: string, fields: Partial> = {}): AccountNotification { + return { + id: id as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Bonus credited', body: 'Server copy 5.00', actions: [], ...fields, + } +} diff --git a/packages/client/ui-account-notifications/tests/view.client.spec.tsx b/packages/client/ui-account-notifications/tests/view.client.spec.tsx new file mode 100644 index 0000000000..ff9d91438c --- /dev/null +++ b/packages/client/ui-account-notifications/tests/view.client.spec.tsx @@ -0,0 +1,36 @@ +// @vitest-environment jsdom +/** The menu extension preserves notifications while onboarding hides their presentation. */ +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, it, vi } from 'vitest' +import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots' +import { AccountNotifications, type AccountNotificationsProps } from '../src/client/AccountNotifications.tsx' +import { notification } from './notification-fixture.ts' + +afterEach(() => { cleanup(); vi.unstubAllGlobals() }) + +it('shows retained cards inside the menu and opens account settings without dismissing them', () => { + vi.stubGlobal('IntersectionObserver', class { observe() {} disconnect() {} }) + const notices = [notification('notice', { actions: [ + { label: 'View account', style: 'primary', target: { type: 'app_route', name: 'account' } }, + ] })] + const openAccount = vi.fn() + const dismiss = vi.fn() + const ctaClicked = vi.fn() + const props: AccountNotificationsProps = { + ...({} as GlobalStandardProps), active: false, openAccount, ctaClicked, dismiss, shown: vi.fn(), + useNotices: select => select(notices), t: () => 'Close', + } + const view = render() + expect(screen.queryByRole('status')).toBeNull() + view.rerender() + fireEvent.click(screen.getByRole('button', { name: 'View account' })) + expect(openAccount).toHaveBeenCalledOnce() + expect(ctaClicked).toHaveBeenCalledExactlyOnceWith('notice') + expect(screen.getByRole('status')).toBeTruthy() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.queryByRole('status')).toBeNull() + expect(dismiss).not.toHaveBeenCalled() + view.rerender() + expect(screen.getByRole('button', { name: 'View account' })).toBeTruthy() +}) diff --git a/packages/client/ui-account-notifications/tsconfig.json b/packages/client/ui-account-notifications/tsconfig.json new file mode 100644 index 0000000000..3d18f2dc37 --- /dev/null +++ b/packages/client/ui-account-notifications/tsconfig.json @@ -0,0 +1,42 @@ +{ + "extends": "../../../tsconfig.base.client.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../api/remotes/tsconfig.client.json" + }, + { + "path": "../locale/tsconfig.client.json" + }, + { + "path": "../ui-primitives" + }, + { + "path": "../ui-slots" + }, + { + "path": "../ui-settings-account" + }, + { + "path": "../../credentials/deepseek-account" + }, + { + "path": "../../host/webserver" + }, + { + "path": "../ui-renderer" + } + ] +} diff --git a/packages/client/ui-account-notifications/tsdown.config.ts b/packages/client/ui-account-notifications/tsdown.config.ts new file mode 100644 index 0000000000..7aa03cebc1 --- /dev/null +++ b/packages/client/ui-account-notifications/tsdown.config.ts @@ -0,0 +1,3 @@ +import { clientBundle } from '../tsdown.client.ts' + +export default clientBundle(import.meta.dirname, ['lib/types/index.js']) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index d0cb398b89..9e0fff1997 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -15,8 +15,8 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: 2e63a8b01d800894 - zh: 42db1f28e2ddb2a3 + en: ece8b18503977bdd + zh: 2d47640fb8367a3d /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: en: 7ae4e68f9491b068 zh: f7478269bf8d28b3 @@ -33,8 +33,8 @@ en: ca3015e252db0114 zh: ebca9253cf15e8e9 /deepseek-ai-dsh-client-ui-settings-account/known-limitations-and-deferred-work: - en: 7afbd3f7afc20bd8 - zh: f54c57e3d6738c7c + en: d34c8fea4a069317 + zh: 4350aaf02d3190e2 /deepseek-ai-dsh-client-ui-settings-account/known-limitations-and-deferred-work/dev-note: en: ebc93259d9f494e2 zh: dcc679e43cdbd594 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index 2f1bc35161..e03583cfd3 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -38,7 +38,7 @@ Account operations carry this UI's client identity to the Host: build version, a Balances use Platform Web currency formatting: two decimal places and digit grouping, positive amounts truncated to cents, positive sub-cent amounts shown as <0.01, and negative amounts rounded with a minimum displayed magnitude of 0.01. Raw Host balance strings remain unchanged. -Desktop usage, top-up, and onboarding recharge actions open one isolated native Platform view below a 48px return bar. The Desktop host owns a single such view, and opening a page destroys the previous one, so the plugin registers one shared host entry in `shell.overlay` and the Account settings page, the account quota notice, and the Desktop onboarding recharge page all request a page through its `PlatformPages` request channel instead of mounting their own container. Each request retires the previous owner before the newer page shows, and its identity-safe release clears only that request, so a stale owner cannot close a page it no longer owns. On Windows Electron the return bar and the native view start below the Desktop caption strip, so the Application and Edit menu text cannot cover the Back to DeepSeek Harness label. Back destroys the view, restores focus before any deferred Modal takes it, and preserves the Account settings page. Leaving a top-up page waits for any read already running and then reads again, because a top-up may have changed what the account holds. The Account settings page and the account quota notice re-read profile, balance, and unnotified bonus; the onboarding recharge return re-reads profile and balance only, so it never triggers the unnotified-bonus read. Superseding a page, releasing a request, plugin unload, and leaving usage all read nothing. Loading failures retain the return action and show a centered localized error with Retry. Retry reloads the same destination; renderer commands never receive the account token. +Desktop usage, top-up, and onboarding recharge actions open one isolated native Platform view below a 48px return bar. The Desktop host owns a single such view, and opening a page destroys the previous one, so the plugin registers one shared host entry in `shell.overlay` and the Account settings page, the account quota notice, and the Desktop onboarding recharge page all request a page through its `PlatformPages` request channel instead of mounting their own container. Each request retires the previous owner before the newer page shows, and its identity-safe release clears only that request, so a stale owner cannot close a page it no longer owns. On Windows Electron the return bar and the native view start below the Desktop caption strip, so the Application and Edit menu text cannot cover the Back to DeepSeek Harness label. Back destroys the view, restores focus before any deferred Modal takes it, and preserves the Account settings page. Leaving a top-up page waits for any read already running and then reads again, because a top-up may have changed what the account holds. The Account settings page and the account quota notice re-read profile and balance and publish an account refresh for extensions; the onboarding recharge return re-reads profile and balance only. Superseding a page, releasing a request, plugin unload, and leaving usage all read nothing. Loading failures retain the return action and show a centered localized error with Retry. Retry reloads the same destination; renderer commands never receive the account token. Chat offers each live quota failure from a bound Session to the frame-wide `shell.quota-notice` chain from its host in `shell.overlay`, so the notice outlives the Chat panel that reported it. The account entry claims `ACCOUNT_QUOTA`: while an account credential is stored and the shared host entry exists, the Modal offers Cancel and Top up. While a page requested through the shared request channel is showing, the native view covers this document, so the entry paints neither the Modal nor the Toast. A quota failure that arrives while a Settings-opened page is already showing is not retained: it stays subject to newest-notice replacement, and the Modal appears after the viewer returns while that notice is still current. That Modal reports the failure of the original request, not the account's current balance: the top-up re-read is a separate read, and returning neither proves a successful payment nor dismisses the notice on its own. The notice's own Top up is the retained case: it calls `keepOpen()` and requests the `top-up` page through the shared request channel, keeping that notice and its page mounted through later quota failures. With the shared host entry the entry waits for the first account snapshot instead of rendering a Toast that its own timer could discard; a snapshot that reports no stored credential, or a failed account stream with no snapshot, then renders the same neutral warning Toast itself, and without that host entry the entry renders that Toast immediately, instead of relying on the chat host fallback. The entry owns the hold and its page request and releases both when it unmounts, so a later quota failure publishes again without replaying the dropped ones; dismissal or sign-out clears the hold and the page request. Close, Cancel, a sign-out, or leaving the notice's own embedded page takes the notice down without retrying the request. @@ -52,9 +52,7 @@ The account card’s More account information link has no underline and opens th Sign out first queries running account-token tasks and opens a confirmation dialog. The warning describes interruption when such tasks exist; otherwise it explains that data is retained and the account can be signed in again. Cancel, close, and Escape dismiss without signing out. Failed impact queries still open confirmation with an explicit unknown-task warning; failed sign-out keeps the dialog available for retry. -A granted bonus appears as a server-authored notice above the sidebar account launcher without taking focus. The client reads the unnotified bonus when an account becomes active and once per Settings entry; it never polls. The server orders the candidates and owns the copy, so the client stacks every live notice in that order and renders its message verbatim. Only the foreground card is interactive and reports display for acknowledgement. Closing it promotes the next card with a 250ms ease-out position and scale transition, including changes in content height; reduced-motion preferences disable the transition. A server-supplied title replaces the localized bonus title; responses without title retain that default. - -The notice waits until Desktop onboarding no longer covers the workspace, including loading, completion saving, and the exit animation, and until model credential onboarding unmounts. Closing the application during onboarding leaves the bonus unacknowledged. In the main interface, the notice is painted as soon as the server offers it, including underneath the translucent settings panel, once the document is visible and the card has passed one presented frame. That painted frame is the whole display signal: the card measures no cover, so a card behind the open overlay counts exactly as any other, and closing the card counts as a display too. Displaying a card queues its acknowledgement, so one mounted card is acknowledged once. A failed acknowledgement retries with a capped backoff for the rest of the signed-in session and never surfaces as an account UI error. A read that fails leaves the visible card and its pending acknowledgement alone, so a transport reconnect keeps retrying. Nothing is written to browser storage. The second signed-in frame of one sign-in and a reconnected stream's replayed state are one session, not a new one, so they keep the card and its retries; signing out, replacing the credential with another account's, or unloading the plugin discards them. Identity-only updates do not reach the account UI stream. Every signed-in frame reads again, and a newer read supersedes one still in flight, so a credential swapped in place is named by a fresh read rather than inheriting the replaced account's; the batch's account id then drops the previous account's card and queue even with no intervening signed-out state. The next sign-in displays whatever the server still offers, including an order an earlier sign-in acknowledged, and a card the user has already seen stays up until it is closed, even when a later read returns no bonus. +Account notification polling and presentation belong to [ui-account-notifications](../ui-account-notifications/README.md). The account menu positions the notification slot above its launcher inside the sidebar, keeps its DOM mounted while the rail hides it, and publishes account lifecycle and refresh events. ### Desktop onboarding @@ -83,7 +81,6 @@ A terminal account-state stream failure appears in the sign-in dialog or Account The balance card shows recharge funds and bonus credit in separate rows. While signed in, the bonus row appears during loading, after a failed wallet read, and when a wallet holds positive bonus credit; a successful read without positive bonus credit omits the row. A failed wallet read shows the existing unavailable copy as a link to Platform — the same destination and behavior as the Usage action, so the embedded page opens on Desktop and a new tab elsewhere — while the loading state stays plain text. Currencies retain their own amounts, and a notice date is rendered only inside the server’s own message. - A successful login selects the first available `deepseek-account` model as the default when no other provider has a configured API key, even if a previous default was saved. Configured keys preserve the existing default even when their provider has no available models. Session-specific selections remain unchanged. @@ -103,8 +100,6 @@ No model request prefix changes. - Completed installations do not reapply defaults or overwrite later user preferences. Completion does not synchronize across devices or create a per-account history. - Onboarding follows the interface locale and theme, with four Figma illustration sets covering Chinese and English in light and dark appearance. Export canvases include the full illustration geometry; Finder artwork uses the same vertical fade in both themes. -- The notice copy is server-localized for the UI language in effect when the client reads it. Switching language does not itself re-read the unnotified bonus, so a notice already on screen keeps the copy the server sent for the earlier language until the user refreshes or the account lifecycle restarts. - - Web sign-in needs a loopback HTTP page origin (`localhost`, `127.0.0.1`, or `[::1]`), because the Host accepts only those callback origins. A Web UI reached through `--trusted-host` or an HTTPS reverse proxy still shows the entry, but starting sign-in fails with the generic retry state; such deployments add an API key instead. - The Platform view’s dialog marks every other document child inert, including the Desktop-owned caption menu host, so the Application and Edit menu stays visible but cannot be operated until the view closes. Exempting that host needs an inertness contract owned by the Desktop. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index ef91df8958..c6d7a291b3 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -38,7 +38,7 @@ Desktop 与普通 Web 客户端都挂载侧边栏账号菜单、账号设置、 余额沿用 Platform Web 的金额格式:两位小数和千分位分组,正金额截断至分,小于一分的正金额显示为 <0.01,负金额按舍入规则处理且显示绝对值至少为 0.01。Host 返回的原始余额字符串保持不变。 -Desktop 的用量、充值与引导充值操作在 48px 返回栏下方打开同一个隔离的原生 Platform 视图。Desktop 宿主只有一个这样的视图,打开新页面会销毁上一个,因此插件在 `shell.overlay` 注册一个共享宿主条目,Account 设置页、账号欠费提示与 Desktop 引导充值页都通过其 `PlatformPages` 请求通道申请页面,而不再各自挂载容器。新请求会在新页面显示前退掉上一个持有者,其身份安全的释放只清除本次请求,因此过期的持有者无法关闭它已不再持有的页面。在 Windows Electron 中,返回栏与原生视图都从 Desktop 顶栏下方开始,Application 和 Edit 菜单文字不会盖住“返回 DeepSeek Harness”。返回操作销毁视图并保留 Account 设置页,且先恢复焦点,再由任何被延后的 Modal 接管。从充值页返回时会等待任何已在进行的读取结束后再读取,因为充值可能改变账号持有的内容。Account 设置页与账号欠费提示会重读资料、余额与未通知赠金;引导充值返回则只重读资料与余额,因此不会触发未通知赠金的读取。替换页面、释放请求、插件卸载与从用量页返回均不读取。加载失败时保留返回操作,居中显示本地化错误提示和“重试”按钮。重试重新加载同一目标页面;渲染进程命令不接收账号 token。 +Desktop 的用量、充值与引导充值操作在 48px 返回栏下方打开同一个隔离的原生 Platform 视图。Desktop 宿主只有一个这样的视图,打开新页面会销毁上一个,因此插件在 `shell.overlay` 注册一个共享宿主条目,Account 设置页、账号欠费提示与 Desktop 引导充值页都通过其 `PlatformPages` 请求通道申请页面,而不再各自挂载容器。新请求会在新页面显示前退掉上一个持有者,其身份安全的释放只清除本次请求,因此过期的持有者无法关闭它已不再持有的页面。在 Windows Electron 中,返回栏与原生视图都从 Desktop 顶栏下方开始,Application 和 Edit 菜单文字不会盖住“返回 DeepSeek Harness”。返回操作销毁视图并保留 Account 设置页,且先恢复焦点,再由任何被延后的 Modal 接管。从充值页返回时会等待任何已在进行的读取结束后再读取,因为充值可能改变账号持有的内容。Account 设置页与账号欠费提示会重读资料、余额,并向扩展发布账号刷新事件;引导充值返回则只重读资料与余额。替换页面、释放请求、插件卸载与从用量页返回均不读取。加载失败时保留返回操作,居中显示本地化错误提示和“重试”按钮。重试重新加载同一目标页面;渲染进程命令不接收账号 token。 Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交给全局 `shell.quota-notice` 链,提示的生命周期因此长于上报它的 Chat 面板。账号条目认领 `ACCOUNT_QUOTA`:已存储账号凭证且存在共享宿主条目时,Modal 提供取消和去充值。只要通过该共享请求通道请求的页面正在显示,原生视图就会盖住本页,因此该条目既不绘制 Modal 也不绘制 Toast。在 Account 设置页已打开页面的情况下新到达的欠费不会被保持:它仍受最新提示替换规则约束,返回后若该提示仍是最新一条就显示 Modal。该 Modal 报告的是原始请求的失败,而不是账号当前余额:返回时的重读是一次独立读取,返回本身既不证明支付成功,也不会自动撤下该提示。提示自身的去充值属于被保持的情形:它调用 `keepOpen()` 并通过共享请求通道申请 `top-up` 页面,使该提示与其页面在后续欠费期间保持挂载。存在共享宿主条目时,该条目会等待首个账号快照,而不是渲染一个可能被自身计时器丢弃的 Toast;快照报告未存储凭证,或账号流失败且无快照时,才由该条目自行渲染同一段中立警告 Toast,缺少该宿主条目时则立即渲染该 Toast,而不依赖 Chat 宿主回退。该条目持有保持与页面请求,并在自身卸载时释放二者,因此后续欠费会重新发布而不重放已丢弃的提示;关闭与退出登录也会清除保持和页面请求。关闭、取消、退出登录或离开该提示自己的内嵌页面都会撤下提示,且不会重试请求。 @@ -52,9 +52,7 @@ Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交 退出登录先查询正在使用账号 token 的任务,再打开确认弹窗。有此类任务时提示执行将被打断,否则提示数据保留且可重新登录。取消、关闭和 Escape 均不退登。影响查询失败仍打开确认弹窗,并明确提示无法确认任务状态;退登失败保留弹窗以便重试。 -赠金到账时,侧栏账号入口上方显示一条由服务端提供文案的通知,不抢占焦点。客户端仅在账号进入登录态时、以及每次进入设置页时读取一次未通知赠金,不做轮询。候选顺序与文案均由服务端决定,客户端按该顺序层叠展示全部未过期通知并原样渲染消息。只有最前面的卡片可交互,并在实际展示后触发确认。关闭前卡后,下一张卡片通过 250ms ease-out 的位置与缩放过渡(包括内容高度变化)进入前台;偏好减少动态效果时禁用过渡。服务端提供的 title 替换本地化赠金标题;未返回 title 时沿用默认标题。 - -通知等待 Desktop 引导界面不再遮盖主界面且模型凭证引导卸载后才展示,Desktop 引导的等待范围包括加载、完成时的保存和退出动画。在引导期间关闭应用不会确认赠金通知。进入主界面后,服务端返回即绘制通知,包括在设置面板的半透明蒙层之下;同时要求文档可见且卡片已完成一帧绘制。这一帧绘制就是全部的展示信号:卡片不检测遮挡,因此处于打开蒙层之下的卡片与其他情形同样计数,用户关闭卡片同样计入展示。卡片展示后即排队确认,因此同一张挂载的卡只确认一次。确认失败会在本次登录会话内按带上限的退避重试,且不会在账号界面报错。读取失败不会影响已展示的卡片及其待确认队列,因此连接重连后仍会继续重试。不写入浏览器存储。同一次登录的第二个登录态帧以及重连后重放的登录态属于同一会话而非新会话,因此保留卡片与重试;只有退出登录、凭证被换成另一账号,或卸载插件才会丢弃。仅身份信息更新不会进入账号界面订阅流。每个登录态帧都会重新读取,且新的读取会取代仍在进行中的旧读取,因此就地更换的凭证会由一次全新的读取来识别,而不会沿用被替换账号的读取结果;读取结果中的账号 ID 随后会丢弃上一个账号的卡片与队列,即使没有中间的退出登录状态。下一次登录会展示服务端仍然下发的内容,包括上一次登录已确认过的订单;用户已看到的卡片会保留到关闭为止,即使之后的读取没有返回赠金。 +账号通知的轮询与展示由 [ui-account-notifications](../ui-account-notifications/README.zh.md) 负责。账号菜单在侧栏内部将通知插槽定位于入口上方,收起为窄栏时隐藏但保留其 DOM,并发布账号生命周期和刷新事件。 ### Desktop 引导 @@ -83,7 +81,6 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 余额卡片分行展示充值余额与赠金余额。登录态下,赠金行在加载中、余额读取失败以及存在正额赠金时显示;读取成功但没有正额赠金时不显示该行。余额或赠金读取失败时,沿用既有的不可用文案并改为指向 Platform 的链接,目标与行为同“查询用量”一致:Desktop 打开内嵌页面,其它环境新开标签页;加载中仍为纯文本。不同币种分别显示;日期只在服务端自己的消息中出现。 - 登录成功时,若其他提供方均未配置 API key,则将 `deepseek-account` 的第一个可用模型设为默认值,即使此前保存过默认选择。其他提供方只要配置了 key,就保留原默认值,即使其没有可用模型。会话内的显式选择保持不变。 @@ -103,8 +100,6 @@ Desktop preload 标记在账号凭证已存储后启用引导。进度属于本 - 已完成引导的安装不会重新应用默认值或覆盖用户后续调整的偏好。完成状态不跨设备同步,也不创建逐账号历史。 - 引导跟随界面语言和主题,使用中文、英文分别搭配浅色、深色外观的四套 Figma 插图。导出画布包含完整插图范围,Finder 插图在两种主题下使用一致的纵向渐变。 -- 通知文案按客户端读取时的界面语言由服务端本地化。切换语言本身不会重新读取未通知赠金,因此已在屏幕上的通知会沿用服务端先前语言下发的文案,直到用户手动刷新或登录生命周期重新开始。 - - Web 登录要求页面 origin 为回环 HTTP(`localhost`、`127.0.0.1` 或 `[::1]`),因为 Host 只接受这些回调 origin。经 `--trusted-host` 或 HTTPS 反向代理访问的 Web UI 仍显示登录入口,但发起登录会进入通用的失败重试状态;这类部署应改为添加 API Key。 - Platform 视图的弹窗会把文档内其它子节点设为 inert,其中包括 Desktop 拥有的顶栏菜单 host,因此 Application 和 Edit 菜单保持可见,但在视图关闭前无法操作。放行该 host 需要 Desktop 侧提供 inert 契约。 diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.module.css b/packages/client/ui-settings-account/src/client/AccountMenu.module.css index a18e586f6a..773e791722 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.module.css +++ b/packages/client/ui-settings-account/src/client/AccountMenu.module.css @@ -1,5 +1,6 @@ -.root { flex: 1; min-width: 0; } +.root { position: relative; flex: 1; min-width: 0; } .root[data-inset='true'] { margin-inline: 2px; } +.notifications { position: absolute; inset-inline: 0; bottom: calc(100% + 4px); z-index: 1; } .anchor { width: 100%; } .trigger { user-select: none; display: flex; align-items: center; width: 100%; height: 44px; gap: 8px; padding: 6px calc(var(--dsh-sidebar-row-padding) - var(--dsh-sidebar-paint-inset)); border: 0; border-inline: var(--dsh-sidebar-paint-inset) solid transparent; box-sizing: border-box; border-radius: var(--dsw-radius-md); background: transparent; background-clip: padding-box; color: var(--dsw-alias-label-primary); font: inherit; font-size: 14px; cursor: pointer; } .trigger[data-signed-out='false']:not([data-collapsed='true']) { padding: 6px; border-inline: 0; background-clip: border-box; } diff --git a/packages/client/ui-settings-account/src/client/AccountMenu.tsx b/packages/client/ui-settings-account/src/client/AccountMenu.tsx index 0b24f8cacd..58838a5c6c 100644 --- a/packages/client/ui-settings-account/src/client/AccountMenu.tsx +++ b/packages/client/ui-settings-account/src/client/AccountMenu.tsx @@ -1,19 +1,19 @@ /** Sidebar account launcher and locally authoritative sign-out action. */ -import { useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import { Toast, Menu, IconEllipsisOutlineMedium, IconPaperPlaneOutlineMedium, IconSettingsOutlineMedium, IconUserOutlineMedium, } from '@deepseek-ai/dsh-client-ui-primitives' -import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots' +import type { InjectFace, PropsLocale, PropsRuntime, PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots' import type { AccountSectionInjected } from './AccountSection.tsx' import { SignOutDialog } from './SignOutDialog.tsx' import { SignInDialog } from './SignInDialog.tsx' import { LogoutIcon } from './LogoutIcon.tsx' import { AccountAvatar } from './AccountAvatar.tsx' -import { AccountNoticeStack } from './AccountNotice.tsx' +import type {} from './account-ui.ts' import css from './AccountMenu.module.css' /** Account launcher composed by the settings shell. */ -export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<'settings.account'> & InjectFace +export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsRenderSlots<'settings.launcher.notifications'> & PropsLocale<'settings.account'> & InjectFace /** The signed-in label stays empty while the profile loads. * @param props - sidebar geometry, settings navigation and account operations. @@ -21,10 +21,9 @@ export type AccountMenuProps = PropsRuntime<'settings.launcher'> & PropsLocale<' */ export function AccountMenu({ subscribeSessionExpired, subscribeModelSignInRequired, wide, settingsShortcut, openSettings, openOnboarding, settingsOpen, - useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, bonusNoticeShown, bonusNoticeDismissed, + useAccount, useTheme, signOut, hasRunningAccountTasks, refreshAccount, renderSlot, contactUs, showLogin, start, cancel, avatarFailed, t, }: AccountMenuProps) { - const anchor = useRef(null) // The launcher outlives the panel, so a false-to-true edge is one Settings entry: // re-renders, section switches and tab switches inside one open must not read again. const settingsWasOpen = useRef(false) @@ -54,13 +53,13 @@ export function AccountMenu({ } // The plugin's start publishes `loginFailed` before it rejects, so the dialog owns the report. const beginSignIn = (): void => { setOpen(false); void start().catch(() => undefined) } - return
+ const openAccount = useCallback(() => { openSettings('account') }, [openSettings]) + return
{signInNotice > 0 && { setSignInNotice(0) }} />} {expiryNotice && { setExpiryNotice(false) }} />} - {signedIn && !account.desktopOnboardingVisible && !account.onboarding && account.notices && } + { setOpen(value => !value) }}> diff --git a/packages/client/ui-settings-account/src/client/AccountNotice.tsx b/packages/client/ui-settings-account/src/client/AccountNotice.tsx deleted file mode 100644 index a18e209101..0000000000 --- a/packages/client/ui-settings-account/src/client/AccountNotice.tsx +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Sidebar bonus notice. The card reports a display once it has a position, the - * document is visible, and it has painted one frame: that is the whole signal, - * and the card measures no cover, so a painted card behind the open Settings - * overlay reports the same way as any other. Closing counts as a display too, - * because the user acted on it. An award that expired before a render is not - * drawn at all. - */ -import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type RefObject } from 'react' -import { createPortal } from 'react-dom' -import { IconCloseOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' -import type { BonusNotice } from './bonus-notices.ts' -import css from './AccountNotice.module.css' -import { dismissNotice } from './notice-transition.ts' - -/** @param expiresAt - server expiration timestamp. @returns whether the award can still be spent. */ -function live(expiresAt: string): boolean { - if (expiresAt === '') return true - const expires = Date.parse(expiresAt) - // An unparsable timestamp is not evidence of expiry, so the notice still shows. - return Number.isNaN(expires) || expires > Date.now() -} - -/** - * @param run - callback to invoke once one presented frame has passed. - * @returns a canceller for a card that unmounts or hides first. - */ -function afterPaint(run: () => void): () => void { - if (typeof requestAnimationFrame !== 'function') { - // Without a frame clock, the following task is the best available paint boundary. - const timer = setTimeout(run, 0) - return () => { clearTimeout(timer) } - } - let cancelled = false - let timer: ReturnType | undefined - const frame = requestAnimationFrame(() => { - // The frame callback runs before its paint; the following task runs after it. - timer = setTimeout(() => { - if (!cancelled) run() - }, 0) - }) - return () => { - cancelled = true - cancelAnimationFrame(frame) - if (timer !== undefined) clearTimeout(timer) - } -} - -/** @param props - server-ordered notices, localized fallback copy, anchor, and display callbacks. - * @returns a non-modal stack whose foreground card alone can report display or be closed. - */ -export function AccountNoticeStack({ notices, anchor, title, closeLabel, onShown, onDismiss }: { - notices: readonly BonusNotice[] - anchor: RefObject - title: string - closeLabel: string - /** Called after the foreground card has passed a visible presented frame. */ - onShown: (orderId: BonusNotice['orderId']) => void - /** Called when the user closes the foreground card. */ - onDismiss: (orderId: BonusNotice['orderId']) => void -}) { - const [position, setPosition] = useState<{ left: number; bottom: number }>() - useLayoutEffect(() => { - if (!anchor.current) return - const element = anchor.current - const update = () => { - const rect = element.getBoundingClientRect() - setPosition({ left: Math.max(8, Math.min(rect.left, window.innerWidth - 288)), - bottom: Math.max(8, window.innerHeight - rect.top + 4) }) - } - update() - const observer = new ResizeObserver(update) - observer.observe(element) - window.addEventListener('resize', update) - window.addEventListener('scroll', update, true) - return () => { - observer.disconnect() - window.removeEventListener('resize', update) - window.removeEventListener('scroll', update, true) - } - }, [anchor]) - const liveNotices = notices.filter(notice => live(notice.expiresAt)) - return createPortal(
- {liveNotices.map((notice, depth) => )} -
, document.body) -} - -/** One stable card node remains mounted as the cards before it are dismissed. */ -function NoticeCard({ notice, depth, ready, title, closeLabel, onShown, onDismiss }: { - notice: BonusNotice - depth: number - ready: boolean - title: string - closeLabel: string - onShown: (orderId: BonusNotice['orderId']) => void - onDismiss: (orderId: BonusNotice['orderId']) => void -}) { - const foreground = depth === 0 - const reported = useRef(false) - useEffect(() => { - if (!ready || !foreground || reported.current || !live(notice.expiresAt)) return - let cancel: (() => void) | undefined - const attempt = () => { - if (reported.current || cancel !== undefined || !live(notice.expiresAt)) return - if (document.visibilityState === 'hidden') return - cancel = afterPaint(() => { - cancel = undefined - if (reported.current || document.visibilityState === 'hidden' || !live(notice.expiresAt)) return - reported.current = true - onShown(notice.orderId) - }) - } - attempt() - document.addEventListener('visibilitychange', attempt) - return () => { - document.removeEventListener('visibilitychange', attempt) - cancel?.() - } - }, [ready, foreground, notice.orderId, notice.expiresAt, onShown]) - return -} diff --git a/packages/client/ui-settings-account/src/client/AccountSection.tsx b/packages/client/ui-settings-account/src/client/AccountSection.tsx index e65252994e..d2a4674e9a 100644 --- a/packages/client/ui-settings-account/src/client/AccountSection.tsx +++ b/packages/client/ui-settings-account/src/client/AccountSection.tsx @@ -10,14 +10,10 @@ import { formatBalance } from './formatBalance.ts' import { AccountAvatar } from './AccountAvatar.tsx' import type { AccountAvatarSnapshot } from './account-avatar.ts' import { authorizeUrlWithTheme } from './authorize-url.ts' -import type { BonusNotice } from './bonus-notices.ts' import css from './AccountSection.module.css' /** Safe account snapshot shared by the settings page and launcher. */ export interface AccountSnapshot { - /** Server-authored notices in front-to-back order, absent when none are available. */ - notices?: readonly BonusNotice[] - /** Latest Host state, absent until the stream responds. */ view: AccountView | undefined /** Sanitized profile and balance query outcomes, absent while loading. */ @@ -30,7 +26,7 @@ export interface AccountSnapshot { loginVisible?: boolean /** Latest explicit start request failed before a Host state was available. */ loginFailed?: boolean - /** Model credential onboarding owns the login dialog and delays bonus notices while mounted. */ + /** Model credential onboarding owns the login dialog and delays account notifications while mounted. */ onboarding?: boolean /** Desktop introduction covers the workspace during loading, saving, and exit animation. * True on Desktop until shell.overlay reports visibility, false in browsers; Desktop layouts must render that slot. @@ -62,7 +58,7 @@ export interface AccountSectionInjected { theme: HostObservable } /** - * Retry a failed avatar and read the profile, balance, bonus wallets and unnotified bonus once. The Settings launcher + * Retry a failed avatar, read the profile and balances, and notify account refresh extensions. The Settings launcher * calls it on each entry, and a page opener on return from top-up. * @returns after the account queries settle; image loading completes independently. */ @@ -73,10 +69,6 @@ export interface AccountSectionInjected { showLogin: (visible: boolean) => void /** Claim dialog ownership for the onboarding step. */ setOnboarding: (active: boolean) => void - /** @param orderId - notice whose card finished a presented frame while visible. */ - bonusNoticeShown: (orderId: BonusNotice['orderId']) => void - /** @param orderId - notice the user closed. */ - bonusNoticeDismissed: (orderId: BonusNotice['orderId']) => void /** @returns after the login attempt is created. */ start: () => Promise /** @param id - attempt to cancel. @returns after cancellation or an already-admitted commit. */ diff --git a/packages/client/ui-settings-account/src/client/account-ui.ts b/packages/client/ui-settings-account/src/client/account-ui.ts new file mode 100644 index 0000000000..e2c6e696ee --- /dev/null +++ b/packages/client/ui-settings-account/src/client/account-ui.ts @@ -0,0 +1,49 @@ +/** Account state and presentation extension points shared with client plugins. */ +import type { AccountClientMetadata, AccountView } from '@deepseek-ai/dsh-deepseek-account/types' + +/** Latest account-stream availability, without notification state. */ +export interface AccountUiState { + readonly view: AccountView | undefined + readonly failed: boolean +} + +/** Read the account stream already owned by the account settings plugin. */ +export interface AccountUi { + /** Read the current state from the existing account snapshot. + * @returns the latest account state. + */ + getSnapshot(): AccountUiState + /** Build metadata for one account request. + * @param locale - requested language. + * @returns this client's version, language, and timezone. + */ + clientMetadata(locale: string): AccountClientMetadata +} + +/** Account-menu presentation facts supplied to its notification extension. */ +export interface AccountNotificationsOwnerProps { + /** Whether the account menu can display notifications outside onboarding. */ + active: boolean + /** Open the account section in the existing settings shell. */ + openAccount: () => void +} + +declare module '@deepseek-ai/cordis' { + interface Context { accountUi: AccountUi } + interface Events { + /** Account stream update or loss of access. @mode parallel + * @param state - latest account state. + * @param reset - whether account availability, credentials, or the connection lifetime changed. + */ + 'account-ui/change'(state: AccountUiState, reset: boolean): void + /** Explicit account refresh from Settings or a returned Platform page. @mode parallel */ + 'account-ui/refresh'(): Promise + } +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** Notifications anchored at the account menu; the contribution owns its markup and lifecycle. */ + 'settings.launcher.notifications': { kind: 'single'; scope: 'root'; owner: AccountNotificationsOwnerProps } + } +} diff --git a/packages/client/ui-settings-account/src/client/bonus-notices.ts b/packages/client/ui-settings-account/src/client/bonus-notices.ts deleted file mode 100644 index e19f740b49..0000000000 --- a/packages/client/ui-settings-account/src/client/bonus-notices.ts +++ /dev/null @@ -1,269 +0,0 @@ -/** - * Lifecycle of bonus notices: one foreground card in a stack, one read result in - * force at a time, and one acknowledgement per displayed card. Reads happen when - * the account becomes active and when the user asks for a refresh, never on a - * timer; the server owns which bonus is unnotified and what its copy says. - * - * An order is acknowledged once its foreground card reports a presented frame: the card has - * a position, the document is visible, and it painted one frame. The card measures - * no cover, so a card painted under the open Settings overlay reports like any - * other, and closing the card counts as a display too. - * - * One lifecycle covers one signed-in session. A repeated signed-in frame — the - * second commit update of one sign-in, or a reconnected stream's replay — keeps - * the card and its acknowledgement retries and reads again, so a credential - * replaced in place is still named by a fresh read. Signing out, unloading, or a - * read naming another account clears all of it; a later sign-in shows whatever - * the server still offers. - * @module @deepseek-ai/dsh-client-ui-settings-account/src/client/bonus-notices - */ -import type { - AccountBonusBatch, AccountBonusOrderId, AccountUserId, -} from '@deepseek-ai/dsh-deepseek-account/types' - -/** Notice eligible for display; the message is server-authored for the active locale. */ -export interface BonusNotice { - /** Server-localized plain-text title; absent responses use the localized bonus title. */ - readonly title?: string - /** Server order identity. */ - readonly orderId: AccountBonusOrderId - /** Server-localized plain text, including any award amount or expiration. */ - readonly message: string - /** Server expiration, re-checked at display time; an empty string means no expiration. */ - readonly expiresAt: string -} - -/** Deployment-varying acknowledgement retry timings. */ -export interface BonusNoticeTiming { - /** Delay before the first acknowledgement retry, doubled per further failure. */ - readonly ackRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - readonly ackRetryMaxDelayMs: number -} - -/** Collaborators and timings of one bonus notice lifecycle. */ -export interface BonusNoticeControllerOptions extends BonusNoticeTiming { - /** Read the signed-in account's unnotified bonus. @returns the batch, or null when no account is signed in. */ - read: () => Promise - /** - * Record one order as notified. - * @param accountId - account the order belongs to. - * @param orderId - shown order. - * @returns false when the account changed or signed out; a protocol failure rejects. - */ - acknowledge: (accountId: AccountUserId, orderId: AccountBonusOrderId) => Promise - /** @param notices - notices in front-to-back order; empty when none are shown. */ - publish: (notices: readonly BonusNotice[]) => void -} - -/** Commands the account plugin issues to the bonus notice lifecycle. */ -export interface BonusNoticeController { - /** - * Start the signed-in lifecycle and read. Re-entry during a live lifecycle keeps - * the card and its acknowledgement retries and reads again, so a credential - * replaced in place is named by that frame's own read. - */ - begin(): void - /** Stop the lifecycle, drop the displayed notice, and discard pending acknowledgement retries. */ - end(): void - /** - * Read the unnotified bonus once, for one Settings entry. - * @returns after the read settles, so callers can await the whole entry. - */ - refresh(): Promise - /** @param orderId - notice whose card passed a presented frame while visible. */ - shown(orderId: AccountBonusOrderId): void - /** @param orderId - notice the user closed, which counts as seen. */ - dismiss(orderId: AccountBonusOrderId): void -} - -/** Signed-in scope; the account and its pending acknowledgements appear once a read names them. */ -interface NoticeScope { - accountId?: AccountUserId - /** Orders whose card was presented and whose acknowledgement has not settled, oldest first. */ - readonly pending: AccountBonusOrderId[] -} - -/** - * @param expiresAt - server expiration timestamp. - * @param at - milliseconds since epoch. - * @returns whether the bonus can no longer be shown. - */ -function expired(expiresAt: string, at: number): boolean { - if (expiresAt === '') return false - const expires = Date.parse(expiresAt) - // An unparsable timestamp is not evidence of expiry, so the notice still shows. - return !Number.isNaN(expires) && expires <= at -} - -/** - * Own the read, display, and acknowledgement lifecycle of bonus notices. - * @param options - collaborators and timings. - * @returns the controller the account plugin drives from account and settings state. - */ -export function createBonusNoticeController(options: BonusNoticeControllerOptions): BonusNoticeController { - let scope: NoticeScope | undefined - /** Notice currently published to the sidebar, including the expiration checked at display time. */ - let current: readonly BonusNotice[] = [] - /** Newest read; an older read still in flight has its result dropped once a newer one starts. */ - let readGeneration = 0 - let ackTimer: ReturnType | undefined - let ackInFlight = false - let ackDelay = options.ackRetryDelayMs - /** Orders the card on screen already reported, so one mount cannot acknowledge twice. */ - const reported = new Set() - const clearAckTimer = (): void => { if (ackTimer !== undefined) { clearTimeout(ackTimer); ackTimer = undefined } } - const setCurrent = (notices: readonly BonusNotice[]): void => { - if (notices.length === current.length && notices.every((notice, index) => { - const previous = current[index] - return notice.orderId === previous?.orderId && notice.message === previous.message - && notice.title === previous.title && notice.expiresAt === previous.expiresAt - })) return - const retained = new Set(notices.map(notice => notice.orderId)) - for (const orderId of reported) if (!retained.has(orderId)) reported.delete(orderId) - current = notices - options.publish(notices) - } - const scheduleAck = (delay: number): void => { - clearAckTimer() - ackTimer = setTimeout(() => { void runAcks() }, delay) - } - /** Drop acknowledgement work of the previous account or lifecycle, so its carry-over cannot reach the next one. */ - const resetAcks = (): void => { - clearAckTimer() - ackInFlight = false - ackDelay = options.ackRetryDelayMs - } - const startAcks = (): void => { if (scope !== undefined && scope.pending.length > 0) scheduleAck(0) } - - /** - * Apply the server-ordered stack, excluding expired notices. An empty batch - * retains only the foreground card if the user has already seen it. - */ - const apply = (scopeAtRead: NoticeScope, batch: AccountBonusBatch): void => { - if (scopeAtRead.accountId !== batch.accountId) { - // A different account answered: the previous account's card and pending - // acknowledgements belong to it and must not outlive its sign-in. - scopeAtRead.accountId = batch.accountId - scopeAtRead.pending.length = 0 - resetAcks() - setCurrent([]) - } - const candidates = batch.bonuses.filter(notice => !expired(notice.expiresAt, Date.now())) - if (candidates.length === 0) { - // Keep an already presented foreground card until dismissal; unseen cards are withdrawn. - const foreground = current[0] - setCurrent(foreground !== undefined && reported.has(foreground.orderId) ? [foreground] : []) - return - } - setCurrent(candidates) - } - - /** - * Read once for one live lifecycle. A newer read supersedes one in flight: the - * older result is dropped instead of applied, so only the newest read can report - * an account change. - * @param scopeAtRead - lifecycle this read belongs to. - * @returns after this read settles. - */ - function runRead(scopeAtRead: NoticeScope): Promise { - const generation = ++readGeneration - return (async () => { - let batch: AccountBonusBatch | null - try { batch = await options.read() } - catch { - // A failed read reports nothing to the user and leaves the lifecycle as - // it stands, so a pending acknowledgement keeps retrying. - batch = null - } - if (scope !== scopeAtRead || generation !== readGeneration) return - if (batch !== null) apply(scopeAtRead, batch) - })() - } - - /** - * Acknowledge presented orders one at a time. A protocol failure backs off up - * to the ceiling and retries for the rest of the signed-in lifecycle, which - * never persists. A false answer settles the order without a retry: this - * session cannot make the server accept it. A hidden window keeps retrying, - * because the presented frame is what a pending acknowledgement proves. - */ - async function runAcks(): Promise { - const scopeAtCall = scope - if (scopeAtCall === undefined || ackInFlight) return - const accountId = scopeAtCall.accountId - const orderId = scopeAtCall.pending[0] - /* v8 ignore next -- an acknowledgement runs only while a read named the account and left a pending order */ - if (accountId === undefined || orderId === undefined) return - ackInFlight = true - /** @returns whether this call still owns the lifecycle and account it started for. */ - const owns = (): boolean => scope === scopeAtCall && scopeAtCall.accountId === accountId - let acknowledged: boolean - try { acknowledged = await options.acknowledge(accountId, orderId) } - catch { - // The lifecycle ended or another account answered while the call was in flight: - // its pending list, in-flight flag and timer now belong to the new owner. - if (!owns()) return - ackInFlight = false - scheduleAck(ackDelay) - ackDelay = Math.min(ackDelay * 2, options.ackRetryMaxDelayMs) - return - } - if (!owns()) return - ackInFlight = false - // Success needs no record and a refusal has no retry, so either way this order - // is settled for this lifecycle. - /* v8 ignore next -- the call owns the scope, and this order is its head until this shift */ - if (scopeAtCall.pending[0] === orderId) scopeAtCall.pending.shift() - ackDelay = options.ackRetryDelayMs - if (acknowledged && scopeAtCall.pending.length > 0) scheduleAck(0) - else clearAckTimer() - } - - /** Queue a presented order, so an acknowledgement interrupted by a failure retries within this sign-in. */ - const report = (orderId: AccountBonusOrderId): void => { - const scopeAtReport = scope - if (scopeAtReport === undefined || current[0]?.orderId !== orderId || reported.has(orderId)) return - reported.add(orderId) - if (!scopeAtReport.pending.includes(orderId)) scopeAtReport.pending.push(orderId) - ackDelay = options.ackRetryDelayMs - scheduleAck(0) - } - - const endLifecycle = (): void => { - if (scope === undefined) return - // The lifecycle a read started for is gone, so its scope check drops the result. - resetAcks() - scope = undefined - reported.clear() - setCurrent([]) - } - - return { - begin() { - // Re-entry is the same signed-in session: the card and its acknowledgement - // retries stay, and this frame's own read supersedes any read still in flight, - // so a credential swapped in place is never left unnamed. - scope ??= { pending: [] } - void runRead(scope) - }, - end: endLifecycle, - refresh(): Promise { - if (scope === undefined) return Promise.resolve() - startAcks() - return runRead(scope) - }, - shown(orderId) { - setCurrent(current.filter(notice => !expired(notice.expiresAt, Date.now()))) - if (current[0]?.orderId !== orderId) return - report(orderId) - }, - dismiss(orderId) { - setCurrent(current.filter(notice => !expired(notice.expiresAt, Date.now()))) - if (current[0]?.orderId !== orderId) return - // Closing the card is the user seeing it, so queue its acknowledgement before withdrawing. - report(orderId) - setCurrent(current.slice(1).filter(notice => !expired(notice.expiresAt, Date.now()))) - }, - } -} diff --git a/packages/client/ui-settings-account/src/client/index.ts b/packages/client/ui-settings-account/src/client/index.ts index 45f13a1b97..a8ac2c89fa 100644 --- a/packages/client/ui-settings-account/src/client/index.ts +++ b/packages/client/ui-settings-account/src/client/index.ts @@ -10,7 +10,7 @@ import type {} from '@deepseek-ai/dsh-client-ui-chat/client' import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type {} from '@deepseek-ai/dsh-api-remote-access/client' import type {} from '@deepseek-ai/dsh-api-remotes/client' -import type { AccountView, AccountDetails } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountUpdate, AccountDetails } from '@deepseek-ai/dsh-deepseek-account/types' import type { OnboardingChange } from './onboarding-contract.ts' import type { PlatformBridge } from './PlatformOverlay.tsx' import { ContactConfig, CONTACT_CONFIG_GLOBAL } from '../contact-config.ts' @@ -22,7 +22,6 @@ import { AccountPlatformHost, type AccountPlatformHostInjected } from './Account import { AccountMenu } from './AccountMenu.tsx' import { createPlatformPages, type PlatformPages } from './platform-pages.ts' import { AccountSection, type AccountSnapshot, type AccountSectionInjected } from './AccountSection.tsx' -import { createBonusNoticeController } from './bonus-notices.ts' import { accountClientMetadata } from './client-metadata.ts' import { en, ja, es, fr, de, ru, pt, zh, type AccountKey } from './locales.ts' import { AccountQuotaNotice, type AccountQuotaNoticeInjected } from './AccountQuotaNotice.tsx' @@ -36,6 +35,7 @@ export type { AccountSectionInjected, AccountSectionProps } from './AccountSecti export type { AccountMenuProps } from './AccountMenu.tsx' export type { AccountSnapshot } from './AccountSection.tsx' export type { AccountKey } from './locales.ts' +export type { AccountUi, AccountUiState, AccountNotificationsOwnerProps } from './account-ui.ts' declare module '@deepseek-ai/dsh-client-ui-slots' { interface LocaleNamespaceMap { 'settings.account': AccountKey } @@ -60,31 +60,9 @@ export function apply(ctx: Context): void { const publish = (value: AccountSnapshot) => { snapshot = value; for (const listener of listeners) listener() } const avatar = new AccountAvatarLoader((value) => { publish({ ...snapshot, avatar: value }) }) ctx.effect(() => () => { avatar.dispose() }, 'account: profile picture lifetime') - /** @returns the client identity for one account call, read at call time so it carries the language and zone in effect then. */ - const client = () => accountClientMetadata(ctx.locale.getSnapshot().active, process.env.DSH_CLIENT_VERSION) - // The browser half of the notice lifecycle: reads when the account becomes - // active and on an explicit refresh, and acknowledges an order only after its - // card reports a presented frame. The Host owns which bonus is unnotified and - // the server owns the copy. - const notices = createBonusNoticeController({ - ackRetryDelayMs: config.bonusAckRetryDelayMs, - ackRetryMaxDelayMs: config.bonusAckRetryMaxDelayMs, - read: async () => { - const result = await ctx.remote.account.getUnnotifiedBonuses(client()) - if (!result.ok) throw new Error('account bonus read failed') - return result.value - }, - acknowledge: async (accountId, orderId) => { - const result = await ctx.remote.account.ackBonusNotified(accountId, orderId, client()) - if (!result.ok) throw new Error('account bonus acknowledgement failed') - return result.value - }, - publish: (notices) => { - const { notices: _replaced, ...withoutNotices } = snapshot - publish(notices.length === 0 ? withoutNotices : { ...withoutNotices, notices }) - }, - }) - ctx.effect(() => () => { notices.end() }, 'account: bonus notice lifetime') + /** @param locale - requested language. @returns client metadata with the current timezone. */ + const client = (locale: string) => accountClientMetadata(locale, process.env.DSH_CLIENT_VERSION) + ctx.provide('accountUi', { getSnapshot: () => snapshot, clientMetadata: client }) let revision = 0 let refreshing: Promise | undefined const refresh = (): Promise => { @@ -101,13 +79,13 @@ export function apply(ctx: Context): void { } const request = Promise.all([ read('profile', async () => { - const result = await ctx.remote.account.getProfile(client()) + const result = await ctx.remote.account.getProfile(client(ctx.locale.getSnapshot().active)) if (!result.ok) throw new Error('account profile failed') if (generation === revision && result.value?.status === 'ready') avatar.setUrl(result.value.value.avatarUrl) return result.value }), read('balance', async () => { - const result = await ctx.remote.account.getBalance(client()) + const result = await ctx.remote.account.getBalance(client(ctx.locale.getSnapshot().active)) if (!result.ok) throw new Error('account balance failed') return result.value }), @@ -119,17 +97,17 @@ export function apply(ctx: Context): void { ctx.effect(() => () => { revision++ }, 'account: details request lifetime') // The account stream, and the reads it starts, follow access to this host's account state. ctx.remoteAccess.whenAccess('account/watch', function* () { - const stream = ctx.remote.$stream({ + const stream = ctx.remote.$stream({ name: 'account', open: signal => ctx.remote.account.watch(signal), ended: () => new Error('account stream ended'), + carrierFailed: () => { + publish({ ...snapshot, failed: true }) + ctx.emit('account-ui/change', snapshot, true) + }, }) + let accountGeneration = 0 // Read across closures: the disposer ends this grant while the frame loop awaits. const grant = { ended: false } - // Withdrawing access invalidates the reads this grant started, closes the - // pending authorization tab, and clears the account view and the sign-in - // dialog state, synchronously, so the next grant starts from no account - // state. `notices.end()` disposes this generation's notice lifetime, which a - // frame of this stream begins; the notice controller stays outside and - // begins again under the next grant. + // Revocation clears shared account state before another access grant can start. yield () => { grant.ended = true revision++ @@ -138,25 +116,27 @@ export function apply(ctx: Context): void { browser.dispose() const { loginFailed: _loginFailed, ...current } = snapshot publish({ ...current, view: undefined, details: undefined, avatar: undefined, failed: false, loginVisible: false }) - notices.end() + ctx.emit('account-ui/change', snapshot, true) return stream.dispose() } void (async () => { for await (const frame of stream) { // A frame the stream delivered before the revocation is not this grant's to apply. if (grant.ended) return + const credentialsChanged = frame.value.type === 'credentials-changed' + const view = frame.value.state + const generationChanged = frame.generation !== accountGeneration + const reset = credentialsChanged || generationChanged || snapshot.view?.status !== view.status || snapshot.failed + accountGeneration = frame.generation revision++ refreshing = undefined avatar.reset() - const initialize = frame.value.status === 'credential-stored' && frame.value.attempt?.phase === 'succeeded' + const initialize = view.status === 'credential-stored' && view.attempt?.phase === 'succeeded' && snapshot.view?.attempt?.phase !== 'succeeded' - const { notices: previousNotices, ...previous } = snapshot - publish({ ...previous, view: frame.value, details: undefined, avatar: undefined, failed: false, - ...(frame.value.status === 'credential-stored' && previousNotices ? { notices: previousNotices } : {}) }) - browser.update(frame.value) + publish({ ...snapshot, view, details: undefined, avatar: undefined, failed: false }) + browser.update(view) frame.accept() - if (frame.value.status === 'credential-stored') notices.begin() - else notices.end() + ctx.emit('account-ui/change', snapshot, reset) if (initialize) void (async () => { try { const initialized = await ctx.remote.session.initializeDefaultModel() @@ -167,7 +147,12 @@ export function apply(ctx: Context): void { })() void refresh() } - })().catch(() => { if (!grant.ended) publish({ ...snapshot, failed: true }) }) + })().catch(() => { + if (!grant.ended) { + publish({ ...snapshot, failed: true }) + ctx.emit('account-ui/change', snapshot, true) + } + }) }) const nativePlatform = (globalThis as typeof globalThis & { dshPlatform?: PlatformBridge }).dshPlatform // One request channel for the single native Platform view. It always exists @@ -175,12 +160,10 @@ export function apply(ctx: Context): void { // lets an entry request one. const platformPages = createPlatformPages() ctx.effect(() => () => { platformPages.dispose() }, 'account: platform page request') - // One account refresh: the recharge/bonus wallet and the unnotified-bonus read, - // whichever surface asks — a Settings entry, or returning from top-up. Both - // reads are independent, and a concurrent refresh shares the in-flight request. + // Extensions share explicit refreshes; profile and wallet reads remain coalesced. const refreshAccount = async (): Promise => { avatar.retry() - await Promise.all([refresh(), notices.refresh()]) + await Promise.all([refresh(), ctx.parallel('account-ui/refresh')]) } /** * Narrow the shared channel to one surface's post-return read: only a viewer @@ -231,8 +214,6 @@ export function apply(ctx: Context): void { }, showLogin(visible) { publish({ ...snapshot, loginVisible: visible }) }, setOnboarding(active) { publish({ ...snapshot, onboarding: active }) }, - bonusNoticeShown(orderId) { notices.shown(orderId) }, - bonusNoticeDismissed(orderId) { notices.dismiss(orderId) }, hooks: { account: { getSnapshot: () => snapshot, @@ -249,7 +230,7 @@ export function apply(ctx: Context): void { __DSH_TRANSPORT__?: { streamBaseUrl?: string } }).__DSH_TRANSPORT__ const request = async () => { - const result = await ctx.remote.account.startSignIn(client(), + const result = await ctx.remote.account.startSignIn(client(ctx.locale.getSnapshot().active), desktop && transport?.streamBaseUrl !== undefined ? new URL(transport.streamBaseUrl).origin : window.location.origin, desktop ? 'desktop' : 'web') if (!result.ok) throw new Error('account start failed') @@ -270,7 +251,7 @@ export function apply(ctx: Context): void { return result.value }, async signOut() { - const result = await ctx.remote.account.signOut(client()) + const result = await ctx.remote.account.signOut(client(ctx.locale.getSnapshot().active)) if (result.ok) return throw result.error }, @@ -332,6 +313,7 @@ export function apply(ctx: Context): void { } ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.launcher', () => ctx.slots.register({ name: 'settings.launcher', locale: 'settings.account', inject: () => operations, + children: { 'settings.launcher.notifications': { kind: 'single', scope: 'root' } }, }, AccountMenu))) ctx.remoteAccess.whenAccess('account/watch', () => ctx.slots.inject('settings.section', () => { let unregister: (() => void) | undefined diff --git a/packages/client/ui-settings-account/src/client/locales.ts b/packages/client/ui-settings-account/src/client/locales.ts index 43ed4d17c1..1e5efc5bbf 100644 --- a/packages/client/ui-settings-account/src/client/locales.ts +++ b/packages/client/ui-settings-account/src/client/locales.ts @@ -33,7 +33,6 @@ export const en = { quotaTitle: 'No balance available', quotaDescription: 'DeepSeek Harness cannot start a new task with this account when no balance is available. Would you like to top up? You can also top up later in Settings → Account.', quotaTopUp: 'Top up', - bonusNoticeTitle: 'Bonus credited', } as const /** Account locale keys. */ export type AccountKey = keyof typeof en @@ -69,7 +68,6 @@ export const zh: Record = { quotaTitle: '当前无可用余额', quotaDescription: '没有可用额度时,DeepSeek Harness 无法开始新的任务,是否前往充值?或者可以稍后前往 设置 → 账号与余额 进行充值。', quotaTopUp: '去充值', - bonusNoticeTitle: '赠金已到账', } /** Japanese copy, checked against the English keys. */ @@ -129,7 +127,6 @@ export const ja = { 'quotaTitle': '残高がありません', 'quotaDescription': '残高がない場合、DeepSeek Harness はこのアカウントで新しいタスクを開始できません。チャージしますか?後から設定 → アカウントでチャージすることもできます。', 'quotaTopUp': 'チャージ', - 'bonusNoticeTitle': 'ボーナスが付与されました', } satisfies Record /** Spanish dictionary, checked against the English keys. */ @@ -164,7 +161,6 @@ export const es = { quotaTitle: 'No hay saldo disponible', quotaDescription: 'DeepSeek Harness no puede iniciar una nueva tarea con esta cuenta cuando no hay saldo disponible. ¿Quieres recargar? También puedes recargar más tarde en Configuración → Cuenta.', quotaTopUp: 'Recargar', - bonusNoticeTitle: 'Bono acreditado', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -199,7 +195,6 @@ export const fr = { quotaTitle: 'Aucun solde disponible', quotaDescription: "DeepSeek Harness ne peut pas démarrer une nouvelle tâche avec ce compte lorsqu'aucun solde n'est disponible. Souhaitez-vous recharger ? Vous pouvez également recharger plus tard dans Paramètres → Compte.", quotaTopUp: 'Recharger', - bonusNoticeTitle: 'Bonus crédité', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -234,7 +229,6 @@ export const de = { quotaTitle: 'Kein Guthaben verfügbar', quotaDescription: 'DeepSeek Harness kann mit diesem Konto keine neue Aufgabe starten, wenn kein Guthaben verfügbar ist. Möchten Sie aufladen? Sie können das Guthaben auch später unter Einstellungen → Konto aufladen.', quotaTopUp: 'Auffüllen', - bonusNoticeTitle: 'Bonus gutgeschrieben', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -269,7 +263,6 @@ export const ru = { quotaTitle: 'Нет доступного баланса', quotaDescription: 'DeepSeek Harness не может запустить новую задачу с этой учетной записью, если на ней нет баланса. Хотите пополнить счет? Вы также можете пополнить счет позже в «Настройки» → «Аккаунт».', quotaTopUp: 'Пополнить', - bonusNoticeTitle: 'Бонус начислен', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -304,5 +297,4 @@ export const pt = { quotaTitle: 'Nenhum saldo disponível', quotaDescription: 'DeepSeek Harness não pode iniciar uma nova tarefa com esta conta quando não houver saldo disponível. Você gostaria de recarregar? Você também pode recarregar mais tarde em Configurações → Conta.', quotaTopUp: 'Recarregar', - bonusNoticeTitle: 'Bônus creditado', } satisfies Record diff --git a/packages/client/ui-settings-account/src/contact-config.ts b/packages/client/ui-settings-account/src/contact-config.ts index b1afcbf049..234e758b9f 100644 --- a/packages/client/ui-settings-account/src/contact-config.ts +++ b/packages/client/ui-settings-account/src/contact-config.ts @@ -1,23 +1,17 @@ -/** Public contact and bonus notice options shared by Host and Client. */ +/** Public contact options shared by Host and Client. */ import z from '@deepseek-ai/schemastery' -/** Questionnaire destination and bonus notice timings shared by Host and Client. */ +/** Questionnaire destination shared by Host and Client. */ export interface ContactConfig { /** HTTPS questionnaire URL; override for a test form. */ contactFormUrl: string /** Questionnaire source option; empty until Harness is supported by the form. */ contactSource: string - /** First delay before retrying a failed bonus acknowledgement. */ - bonusAckRetryDelayMs: number - /** Ceiling for the acknowledgement retry backoff. */ - bonusAckRetryMaxDelayMs: number } /** Validate public questionnaire options. */ export const ContactConfigFields = { contactFormUrl: z.string().pattern(/^https:\/\/[^/\s]+\//).default('https://trtgsjkv6r.feishu.cn/share/base/form/shrcnlCoGElW7MQznGy9r3YYXcg?hide_uid=1&hide_device_info=1&hide_harness_version=1'), contactSource: z.string().default(''), - bonusAckRetryDelayMs: z.number().min(1).default(1_000), - bonusAckRetryMaxDelayMs: z.number().min(1).default(60_000), } /** Validate public questionnaire options. */ export const ContactConfig: z, ContactConfig> = z.object(ContactConfigFields) diff --git a/packages/client/ui-settings-account/src/index.ts b/packages/client/ui-settings-account/src/index.ts index e37bccc073..326da6d0cc 100644 --- a/packages/client/ui-settings-account/src/index.ts +++ b/packages/client/ui-settings-account/src/index.ts @@ -27,8 +27,6 @@ export interface Config extends ContactConfig { export const Config = z.object({ contactFormUrl: ContactConfigFields.contactFormUrl, contactSource: ContactConfigFields.contactSource, - bonusAckRetryDelayMs: ContactConfigFields.bonusAckRetryDelayMs, - bonusAckRetryMaxDelayMs: ContactConfigFields.bonusAckRetryMaxDelayMs, version: OnboardingSettingsFields.version.volatile(), step: OnboardingSettingsFields.step.volatile(), purpose: OnboardingSettingsFields.purpose.volatile(), @@ -50,7 +48,6 @@ export function apply(ctx: Context, config: Config): void { ctx.on('webserver/index-inject', (table) => { table.push({ kind: 'global', name: CONTACT_CONFIG_GLOBAL, value: { contactFormUrl: config.contactFormUrl, contactSource: config.contactSource, - bonusAckRetryDelayMs: config.bonusAckRetryDelayMs, bonusAckRetryMaxDelayMs: config.bonusAckRetryMaxDelayMs, } satisfies ContactConfig }) }) } diff --git a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts index c969148d1b..3e55d655d9 100644 --- a/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts +++ b/packages/client/ui-settings-account/tests/access-revocation.client.spec.ts @@ -46,6 +46,7 @@ it('withdraws every account surface and the account stream on revocation, and re const streams: { readonly signal: AbortSignal; readonly accepted: Promise }[] = [] const lifetime: (() => void)[] = [] const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -71,7 +72,10 @@ it('withdraws every account surface and the account stream on revocation, and re remote: { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, - account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }) }, + account: { + getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }), + getNotifications: async () => ({ ok: true, value: null }), + }, $stream: () => { const abort = new AbortController() const accepted = Promise.withResolvers() @@ -80,7 +84,7 @@ it('withdraws every account surface and the account stream on revocation, and re signal: abort.signal, dispose: () => { abort.abort() }, async *[Symbol.asyncIterator]() { - yield { value: signedIn, accept: () => { accepted.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { accepted.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -121,6 +125,7 @@ it('drops reads a revoked grant started, and the next grant shows no account sec const firstFrames: { release: () => void; accepted: Promise }[] = [] const lifetime: (() => void)[] = [] const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -147,7 +152,10 @@ it('drops reads a revoked grant started, and the next grant shows no account sec remote: { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, - account: { getProfile: async () => await profile.promise, getBalance: async () => ({ ok: true, value: null }) }, + account: { + getProfile: async () => await profile.promise, getBalance: async () => ({ ok: true, value: null }), + getNotifications: async () => ({ ok: true, value: null }), + }, $stream: () => { const abort = new AbortController() const gate = Promise.withResolvers() @@ -158,7 +166,7 @@ it('drops reads a revoked grant started, and the next grant shows no account sec dispose: () => { abort.abort() }, async *[Symbol.asyncIterator]() { await gate.promise - yield { value: signedIn, accept: () => { accepted.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { accepted.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -207,9 +215,10 @@ function revocationHarness(scripts: StreamScript[]) { const lifetime: (() => void)[] = [] let operations: AccountSectionInjected | undefined const getProfile = vi.fn(async () => ({ ok: true, value: null })) - const getUnnotifiedBonuses = vi.fn(async () => ({ ok: true, value: null })) + const getNotifications = vi.fn(async () => ({ ok: true, value: null })) const startSignIn = vi.fn<() => Promise<{ ok: false }>>() const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) lifetime.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -238,7 +247,7 @@ function revocationHarness(scripts: StreamScript[]) { $on: () => () => {}, session: { initializeDefaultModel: async () => ({ ok: true, value: undefined }) }, account: { - getProfile, getBalance: async () => ({ ok: true, value: null }), getUnnotifiedBonuses, startSignIn, + getProfile, getBalance: async () => ({ ok: true, value: null }), getNotifications, startSignIn, }, $stream: () => { const abort = new AbortController() @@ -251,7 +260,7 @@ function revocationHarness(scripts: StreamScript[]) { async *[Symbol.asyncIterator]() { await Promise.resolve() script(() => {}) - yield { value: signedIn, accept: () => { delivered.resolve(undefined) } } + yield { generation: 1, value: { type: 'snapshot', state: signedIn }, accept: () => { delivered.resolve(undefined) } } await new Promise((resolve) => { abort.signal.addEventListener('abort', resolve) }) }, } @@ -260,7 +269,7 @@ function revocationHarness(scripts: StreamScript[]) { } apply(ctx as never) return { - guards, registered, accepted, getProfile, getUnnotifiedBonuses, startSignIn, + guards, registered, accepted, getProfile, getNotifications, startSignIn, operations: () => operations!, dispose: () => { revoke(guards); for (const dispose of lifetime.reverse()) dispose() }, } @@ -276,7 +285,7 @@ it('ignores a frame the stream delivered just before the revocation', async () = expect(b.operations().hooks.account.getSnapshot().view).toBeUndefined() expect(b.registered.get('settings.section') ?? 0).toBe(0) expect(b.getProfile).not.toHaveBeenCalled() - expect(b.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(b.getNotifications).not.toHaveBeenCalled() } finally { b.dispose() } diff --git a/packages/client/ui-settings-account/tests/account.client.spec.tsx b/packages/client/ui-settings-account/tests/account.client.spec.tsx index 0ff3cb139f..50b2668895 100644 --- a/packages/client/ui-settings-account/tests/account.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/account.client.spec.tsx @@ -9,8 +9,8 @@ import type { PlatformBridge } from '../src/client/PlatformOverlay.tsx' import { createPlatformPages, type PlatformPages } from '../src/client/platform-pages.ts' import { AccountPlatformHost } from '../src/client/AccountPlatformHost.tsx' import { AccountSection, type AccountSectionInjected, type AccountSnapshot } from '../src/client/AccountSection.tsx' -import type { BonusNotice } from '../src/client/bonus-notices.ts' import type { AccountMenuProps } from '../src/client/AccountMenu.tsx' +import type { AccountNotificationsOwnerProps } from '../src/client/account-ui.ts' import type {} from '../src/client/index.ts' import { en, zh, type AccountKey } from '../src/client/locales.ts' import css from '../src/client/AccountSection.module.css' @@ -37,7 +37,6 @@ function operationsOf(state: Omit, details?: Partial false), contactUs: vi.fn(), showLogin: vi.fn(), setOnboarding: vi.fn(), - bonusNoticeShown: vi.fn(), bonusNoticeDismissed: vi.fn(), refreshAccount: vi.fn(() => Promise.resolve()), avatarFailed: vi.fn(), start: vi.fn(() => Promise.resolve()), cancel: vi.fn(() => Promise.resolve()), signOut: vi.fn(() => Promise.resolve()), @@ -93,12 +92,14 @@ function SharedPlatformHost({ Globals, pages, platform, copy, refreshAccount }: * @param settingsOpen - whether the settings panel covers the sidebar. * @returns the sidebar launcher with its framework hooks wired to the test face. */ -async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean) { +async function accountMenu(operations: AccountSectionInjected, snapshot: () => AccountSnapshot, settingsOpen: boolean, + renderSlot: AccountMenuProps['renderSlot'] = () => null, + openSettings: AccountMenuProps['openSettings'] = () => {}, wide = true) { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - return selector(snapshot())} wide + return selector(snapshot())} wide={wide} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} - openOnboarding={() => {}} openSettings={() => {}} t={key => en[key as AccountKey]} /> + openOnboarding={() => {}} openSettings={openSettings} t={key => en[key as AccountKey]} /> } it.each([en, zh])('renders account cards without inventing profile or balance data', async (copy) => { @@ -128,7 +129,7 @@ it.each([en, zh].flatMap(copy => ([false, true, 'unknown'] as const).map(running const operations = mount({ status: 'credential-stored', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} hasRunningAccountTasks={async () => { if (running === 'unknown') throw new Error('offline'); return running }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} @@ -155,7 +156,7 @@ it.each([en, zh])('updates the Settings menu keycaps and accessible combination const operations = mount({ status: 'signed-out', attempt: null }, copy) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const props: AccountMenuProps = { + const props: AccountMenuProps = { renderSlot: () => null, ...({} as GlobalStandardProps), ...operations, wide: true, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -184,7 +185,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco const openSettings = vi.fn() const operations = operationsOf({ status: 'signed-out', attempt: null }) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={openSettings} t={key => key in copy ? copy[key as AccountKey] : key} />) @@ -204,7 +205,7 @@ it.each([en, zh])('offers settings, contact and sign-in from the signed-out acco it.each([true, false])('keeps the account inset local through sign-in changes with wide=%s', async (wide) => { const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let operations = operationsOf({ status: 'signed-out', attempt: null }) - const props: AccountMenuProps = { + const props: AccountMenuProps = { renderSlot: () => null, ...({} as GlobalStandardProps), ...operations, wide, settingsOpen: false, useAccount: selector => selector(operations.hooks.account.getSnapshot()), useTheme: selector => selector(operations.hooks.theme.getSnapshot()), @@ -236,7 +237,8 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( snapshot = { ...snapshot, loginVisible: true, loginFailed: true } return Promise.reject(new Error('account start failed')) }) - const view = render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + start={start} useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} t={key => key in en ? en[key as AccountKey] : key} />) @@ -244,7 +246,8 @@ it('reports a failed start in the login dialog, not as a sidebar alert', async ( await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en.signIn })) }) expect(start).toHaveBeenCalledOnce() expect(screen.queryByRole('alert')).toBeNull() - view.rerender( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} + start={start} useAccount={selector => selector(snapshot)} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} t={key => key in en ? en[key as AccountKey] : key} />) @@ -260,7 +263,7 @@ it('keeps the confirmation dialog open after a failed sign-out', async () => { cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const signOut = vi.fn((): Promise => Promise.reject(new Error('account sign-out failed'))) - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} signOut={signOut} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide @@ -422,7 +425,7 @@ it.each([ }) cleanup() const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -435,7 +438,7 @@ it('shows the same shared picture outcome in settings and the sidebar', async () profile: { status: 'ready', value: { id: null, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' } }, }, undefined, avatar) const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - render( null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openSettings={() => {}} openOnboarding={() => {}} t={key => en[key as AccountKey]} />) @@ -506,7 +509,7 @@ it.each([en, zh])('shows a localized toast when the account credential expires', const { AccountMenu } = await import('../src/client/AccountMenu.tsx') let expire: (() => void) | undefined const unsubscribe = vi.fn() - const element = null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} subscribeSessionExpired={(listener) => { expire = listener; return unsubscribe }} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -605,7 +608,8 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard const { AccountMenu } = await import('../src/client/AccountMenu.tsx') const openOnboarding = vi.fn() let snapshot = operations.hooks.account.getSnapshot() - const props = { ...({} as GlobalStandardProps), ...operations, wide: false, settingsOpen: false, openSettings: vi.fn(), openOnboarding, + const props = { ...({} as GlobalStandardProps), ...operations, renderSlot: () => null, wide: false, settingsOpen: false, + openSettings: vi.fn(), openOnboarding, useAccount: (select: (value: AccountSnapshot) => T) => select(snapshot), useTheme: (select: (value: ThemeSnapshot) => T) => select(operations.hooks.theme.getSnapshot()), t: (key: string) => en[key as AccountKey] } @@ -625,29 +629,6 @@ it('dismisses a collapsed menu and hands its login dialog to the API-key onboard expect(screen.queryByRole('dialog')).toBeNull() }) -it('paints the bonus notice under the open settings panel and reports its display once', async () => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }) - const operations = mount({ status: 'credential-stored', attempt: null }, en, { - profile: { status: 'ready', value: { id: null, name: 'User', contact: null } }, - }) - cleanup() - const notice = { orderId: 'order-1' as BonusNotice['orderId'], message: 'Awarded 5.00', expiresAt: '2099-01-01T00:00:00Z' } - // The launcher mounts first; the entry's refresh then delivers the notice while the panel is open. - let snapshot: AccountSnapshot = operations.hooks.account.getSnapshot() - const view = render(await accountMenu(operations, () => snapshot, true)) - expect(screen.queryByRole('status')).toBeNull() - snapshot = { ...snapshot, notices: [notice] } - view.rerender(await accountMenu(operations, () => snapshot, true)) - // The settings overlay is translucent, so the card paints underneath it instead of waiting for the exit. - await vi.waitFor(() => { expect(screen.getByRole('status').textContent).toBe(`${en.bonusNoticeTitle}${notice.message}`) }) - // A card that passed a presented frame reports once even while the panel is open; that report is the acknowledgement. - await vi.waitFor(() => { expect(operations.bonusNoticeShown).toHaveBeenCalledExactlyOnceWith(notice.orderId) }) - // Leaving the panel keeps the same card without reporting its display a second time. - view.rerender(await accountMenu(operations, () => snapshot, false)) - await vi.waitFor(() => { expect(screen.getByRole('status').textContent).toBe(`${en.bonusNoticeTitle}${notice.message}`) }) - expect(operations.bonusNoticeShown).toHaveBeenCalledOnce() -}) - it('reads once per Settings entry, whatever section the entry opens', async () => { const operations = mount({ status: 'credential-stored', attempt: null }, en) cleanup() @@ -716,7 +697,7 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after const unsubscribe = vi.fn(() => { listener = undefined }) operations.subscribeModelSignInRequired = (next) => { listener = next; return unsubscribe } const { AccountMenu } = await import('../src/client/AccountMenu.tsx') - const element = null} {...({} as GlobalStandardProps)} {...operations} settingsOpen={false} useAccount={selector => selector(operations.hooks.account.getSnapshot())} useTheme={selector => selector(operations.hooks.theme.getSnapshot())} wide openOnboarding={() => {}} openSettings={() => {}} @@ -737,20 +718,39 @@ it.each([en, zh])('shows live model sign-in guidance without replaying it after expect(screen.queryByRole('alert')).toBeNull() }) -it.each(['desktopOnboardingVisible', 'onboarding'] as const)('defers bonus display and acknowledgement until %s ends', async (field) => { - vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} }) +it.each(['desktopOnboardingVisible', 'onboarding'] as const)('hides the notification slot until %s ends', async (field) => { const operations = operationsOf({ status: 'credential-stored', attempt: null }) - const notice = { orderId: 'order-onboarding' as BonusNotice['orderId'], message: 'Awarded 5.00', expiresAt: '2099-01-01T00:00:00Z' } - let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), notices: [notice], [field]: true } - const view = render(await accountMenu(operations, () => snapshot, false)) - expect(screen.queryByText(notice.message)).toBeNull() - expect(operations.bonusNoticeShown).not.toHaveBeenCalled() - view.unmount() - expect(operations.bonusNoticeShown).not.toHaveBeenCalled() - const reopened = render(await accountMenu(operations, () => snapshot, false)) - expect(screen.queryByText(notice.message)).toBeNull() + let snapshot: AccountSnapshot = { ...operations.hooks.account.getSnapshot(), [field]: true } + let active: boolean | undefined + let openAccount: (() => void) | undefined + const openSettings = vi.fn() + const renderSlot: AccountMenuProps['renderSlot'] = (name, owner) => { + expect(name).toBe('settings.launcher.notifications') + const value: object = owner + const props = value as AccountNotificationsOwnerProps + active = props.active + openAccount = props.openAccount + return null + } + const view = render(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + expect(active).toBe(false) snapshot = { ...snapshot, [field]: false } - reopened.rerender(await accountMenu(operations, () => snapshot, false)) - await vi.waitFor(() => { expect(operations.bonusNoticeShown).toHaveBeenCalledExactlyOnceWith(notice.orderId) }) - expect(screen.getByText(notice.message)).toBeTruthy() + view.rerender(await accountMenu(operations, () => snapshot, false, renderSlot, openSettings)) + expect(active).toBe(true) + openAccount?.() + expect(openSettings).toHaveBeenCalledExactlyOnceWith('account') +}) + +it('keeps notification DOM inside the launcher while the collapsed rail hides it', async () => { + const operations = operationsOf({ status: 'credential-stored', attempt: null }) + const snapshot = () => operations.hooks.account.getSnapshot() + const renderSlot: AccountMenuProps['renderSlot'] = () =>
Notification
+ const view = render(await accountMenu(operations, snapshot, false, renderSlot)) + const notice = screen.getByRole('status') + expect(view.container.contains(notice)).toBe(true) + view.rerender(await accountMenu(operations, snapshot, false, renderSlot, undefined, false)) + expect(screen.queryByRole('status')).toBeNull() + expect(notice.isConnected).toBe(true) + view.rerender(await accountMenu(operations, snapshot, false, renderSlot)) + expect(screen.getByRole('status')).toBe(notice) }) diff --git a/packages/client/ui-settings-account/tests/apply.client.spec.ts b/packages/client/ui-settings-account/tests/apply.client.spec.ts index 300641d109..cadea02dfe 100644 --- a/packages/client/ui-settings-account/tests/apply.client.spec.ts +++ b/packages/client/ui-settings-account/tests/apply.client.spec.ts @@ -1,11 +1,11 @@ // @vitest-environment jsdom /** Account operations in the shipped client composition, in Desktop and in a plain browser. */ -import { afterEach, beforeEach, expect, vi } from 'vitest' +import { afterEach, beforeEach, expect, onTestFinished, vi } from 'vitest' import { ok } from '@deepseek-ai/dsh-remote-mock' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { createClientTest, type TestClient, webApp } from '@deepseek-ai/dsh-client-test-runtime/src/assembly/index.ts' import type { - AccountBonusBatch, AccountBonusOrderId, AccountDetails, AccountUserId, AccountView, SignInAttemptId, + AccountDetails, AccountUserId, AccountView, SignInAttemptId, } from '@deepseek-ai/dsh-deepseek-account/types' import type { QuotaNoticeOwnerProps } from '@deepseek-ai/dsh-client-ui-chat/client' import type { ThemeRuntime } from '@deepseek-ai/dsh-client-ui-theme/client' @@ -31,15 +31,6 @@ const view: AccountView = { } const stored: AccountView = { ...view, status: 'credential-stored' } const profile: AccountDetails['profile'] = { status: 'ready', value: { id: 'account-user' as AccountUserId, name: 'User', contact: null } } -/** @param orderId - server order. @param message - server copy. @returns one unnotified bonus for this account. */ -function bonus(orderId: string, message = 'Awarded 5.00'): AccountBonusBatch { - return { - accountId: 'account-user' as AccountUserId, - bonuses: [{ - orderId: orderId as AccountBonusOrderId, expiresAt: '2099-01-01T00:00:00Z', message, - }], - } -} function operations(c: TestClient): AccountSectionInjected { const injected: object = c.ctx.slots.entries('settings.launcher')[0]!.inject!() return injected as AccountSectionInjected @@ -133,7 +124,7 @@ it('shares account actions across seats, publishes dialog ownership, and opens c expect(signedOut.searchParams.has('prefill_uid')).toBe(false) expect(signedOut.searchParams.get('hide_uid')).toBe('1') c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) const entry = c.ctx.slots.entries('settings.section').find(entry => entry.options.id === 'account')! expect(entry.inject!()).toBe(actions) @@ -153,7 +144,7 @@ it('shares account actions across seats, publishes dialog ownership, and opens c expect(support.searchParams.has(`hide_${field}`)).toBe(false) } expect(support.searchParams.has('prefill_app_version')).toBe(false) - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) actions.contactUs() const signedOutAgain = new URL(String(open.mock.calls.at(-1)![0])) @@ -206,10 +197,10 @@ it('reports the account sampled by the click when a native read outlasts a sign- const c = await start() const actions = operations(c) c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) actions.contactUs() - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) device.resolve('platform=darwin; os=15.0; app_arch=arm64; memory_gib=16.0') await vi.waitFor(() => { expect(open).toHaveBeenCalledOnce() }) @@ -229,7 +220,7 @@ it('publishes one avatar load and retries it through the shared Settings refresh status: 'ready', value: { id: 'account-user' as AccountUserId, name: 'User', contact: null, avatarUrl: 'https://example.test/avatar.png' }, } c.mock.remote.account.getProfile.mockResolvedValue(ok(picture)) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(images).toHaveLength(1) }) images[0]!.dispatchEvent(new Event('error')) expect(actions.hooks.account.getSnapshot().avatar?.status).toBe('failed') @@ -252,7 +243,7 @@ it('publishes one avatar load and retries it through the shared Settings refresh const successor = actions.hooks.account.getSnapshot().avatar! actions.avatarFailed(ready) expect(actions.hooks.account.getSnapshot().avatar).toBe(successor) - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) expect(actions.hooks.account.getSnapshot().avatar).toBeUndefined() expect(images[3]!.getAttribute('src')).toBeNull() @@ -268,7 +259,7 @@ it('keeps successful account refreshes silent and reports only failed reads', as await actions.refreshAccount() c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok({ status: 'ready', value: [], bonusWallets: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details?.profile).toEqual(profile) }) await actions.refreshAccount() for (const spy of [output, info, log]) { @@ -299,7 +290,7 @@ it('coalesces refreshes, publishes independent failures, and rejects stale respo const pending = Promise.withResolvers>>() c.mock.remote.account.getProfile.mockReturnValueOnce(pending.promise) c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) // Two concurrent account refreshes share the one in-flight request, so the // second call adds no second read of the profile or the balance. @@ -307,14 +298,14 @@ it('coalesces refreshes, publishes independent failures, and rejects stale respo const concurrently = actions.refreshAccount() expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() expect(c.mock.remote.account.getBalance).toHaveBeenCalledOnce() - c.mock.streams.push('account/watch', view) + c.mock.streams.push('account/watch', { type: 'snapshot', state: view }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) pending.resolve(ok(profile)) await Promise.all([a, concurrently]) expect(actions.hooks.account.getSnapshot().details).toBeUndefined() c.mock.remote.account.getProfile.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) c.mock.remote.account.getBalance.mockRejectedValueOnce(new Error('offline')) - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().details).toEqual({ profile: { status: 'failed' }, balance: { status: 'failed' } }) }) const pendingAgain = Promise.withResolvers>>() c.mock.remote.account.getProfile.mockReturnValueOnce(pendingAgain.promise) @@ -361,7 +352,7 @@ it('navigates the preopened browser tab to the themed authorization page', async const attempt = { id: 'attempt' as SignInAttemptId, phase: 'waiting-browser' as const, authorizeUrl: 'https://platform.deepseek.com/dsh/authorize' } mock.remote.account.startSignIn.mockResolvedValue(ok({ ...view, attempt: { id: attempt.id, phase: 'initializing' } })) await actions.start() - c.mock.streams.push('account/watch', { ...view, attempt }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { ...view, attempt } }) const theme = (c.ctx.get('theme') as ThemeRuntime).getTheme().active.colorScheme await vi.waitFor(() => { expect(replace).toHaveBeenCalledExactlyOnceWith(`${attempt.authorizeUrl}?theme=${theme}`) }) }, 60_000) @@ -410,32 +401,32 @@ it('re-reads the account when the shared host returns from top-up, and not from const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok(null)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok({ accountId: 'account-user' as AccountUserId, bonuses: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.remote.account.getNotifications.mockResolvedValue(ok({ nextPollAfterSeconds: 300, notifications: [] })) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) // The account becoming active already ran one shared refresh; measure only the // reads each return triggers from here. - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() - c.mock.remote.account.getUnnotifiedBonuses.mockClear() + c.mock.remote.account.getNotifications.mockClear() c.mock.remote.account.getProfile.mockClear() // Usage changes nothing the account owns, so returning from it reads nothing. actions.openPlatformPage!('usage', vi.fn()) host.closePage() await c.flush() - expect(mock.remote.account.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(mock.remote.account.getNotifications).not.toHaveBeenCalled() // Closing with no page showing is not a return, so it reads nothing either. host.closePage() await c.flush() - expect(mock.remote.account.getUnnotifiedBonuses).not.toHaveBeenCalled() + expect(mock.remote.account.getNotifications).not.toHaveBeenCalled() // Top up may have changed what the account holds, so its return runs the one // shared refresh: the wallet reads and the unnotified-bonus read. actions.openPlatformPage!('top-up', vi.fn()) host.closePage() - await vi.waitFor(() => { expect(mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() }) + await vi.waitFor(() => { expect(mock.remote.account.getNotifications).toHaveBeenCalledOnce() }) expect(mock.remote.account.getProfile).toHaveBeenCalledOnce() }, 60_000) @@ -455,12 +446,12 @@ it('re-reads profile and balance but no bonus for the onboarding recharge return const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected c.mock.remote.account.getProfile.mockResolvedValue(ok(profile)) c.mock.remote.account.getBalance.mockResolvedValue(ok(null)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok({ accountId: 'account-user' as AccountUserId, bonuses: [] })) - c.mock.streams.push('account/watch', stored) + c.mock.remote.account.getNotifications.mockResolvedValue(ok({ nextPollAfterSeconds: 300, notifications: [] })) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() - const bonusesBefore = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length + const bonusesBefore = c.mock.remote.account.getNotifications.mock.calls.length // The account becoming active already ran the shared refresh; measure only the // reads each later event triggers. c.mock.remote.account.getProfile.mockClear() @@ -485,7 +476,7 @@ it('re-reads profile and balance but no bonus for the onboarding recharge return await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) await vi.waitFor(() => { expect(c.mock.remote.account.getBalance).toHaveBeenCalledOnce() }) await c.flush() - expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBe(bonusesBefore) + expect(c.mock.remote.account.getNotifications.mock.calls.length).toBe(bonusesBefore) }, 60_000) it('waits for an in-flight pre-return read before the post-top-up read', async ({ start }) => { @@ -495,20 +486,20 @@ it('waits for an in-flight pre-return read before the post-top-up read', async ( await c.reload(SELF) const actions = operations(c) const host = injectedOf(platformHostEntry(c)!) as AccountPlatformHostInjected - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalled() }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalled() }) await c.flush() c.mock.remote.account.getProfile.mockClear() c.mock.remote.account.getBalance.mockClear() - c.mock.remote.account.getUnnotifiedBonuses.mockClear() + c.mock.remote.account.getNotifications.mockClear() const pending = Promise.withResolvers>>>() c.mock.remote.account.getBalance.mockReturnValueOnce(pending.promise) try { - c.mock.streams.push('account/watch', stored) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledOnce() }) // The baseline includes the frame's own notice read, which is not the return read. - const bonusesBeforeReturn = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length + const bonusesBeforeReturn = c.mock.remote.account.getNotifications.mock.calls.length actions.openPlatformPage!('top-up', vi.fn()) host.closePage() @@ -520,133 +511,13 @@ it('waits for an in-flight pre-return read before the post-top-up read', async ( pending.resolve(ok(null)) await vi.waitFor(() => { expect(c.mock.remote.account.getProfile).toHaveBeenCalledTimes(2) }) await vi.waitFor(() => { expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(2) }) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBeGreaterThan(bonusesBeforeReturn) }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications.mock.calls.length).toBeGreaterThan(bonusesBeforeReturn) }) } finally { // A failed assertion above must not strand the read the host is awaiting. pending.resolve(ok(null)) } }, 60_000) -it('reads the unnotified bonus in the active locale and acknowledges only after the card renders', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - c.mock.remote.account.ackBonusNotified.mockResolvedValue(ok(true)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId, message: 'Awarded 5.00' }) - }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en' })) - // A successful read is not a display, so nothing may be acknowledged yet. - expect(c.mock.remote.account.ackBonusNotified).not.toHaveBeenCalled() - actions.bonusNoticeShown(orderId as AccountBonusOrderId) - await vi.waitFor(() => { - expect(c.mock.remote.account.ackBonusNotified).toHaveBeenCalledWith('account-user', orderId, expect.objectContaining({ locale: 'en' })) - }) - actions.bonusNoticeDismissed(orderId as AccountBonusOrderId) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() -}, 60_000) - -it('keeps the notice and its acknowledgement retry across repeated signed-in frames', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - vi.stubGlobal(CONTACT_CONFIG_GLOBAL, { bonusAckRetryDelayMs: 1, bonusAckRetryMaxDelayMs: 4 }) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - c.mock.remote.account.ackBonusNotified.mockResolvedValue({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId }) }) - actions.bonusNoticeShown(orderId as AccountBonusOrderId) - await vi.waitFor(() => { expect(c.mock.remote.account.ackBonusNotified.mock.calls.length).toBeGreaterThan(0) }) - // One sign-in commits the credential and then updates the attempt; a reconnected - // stream replays the same signed-in state. None of them is a new account. - c.mock.streams.push('account/watch', stored) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(stored) }) - // The displayed card stays, no second read replaces it, and the failed - // acknowledgement keeps backing off instead of stopping until sign-out. - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() - await vi.waitFor(() => { expect(c.mock.remote.account.ackBonusNotified.mock.calls.length).toBeGreaterThan(1) }, { timeout: 30_000 }) -}, 60_000) - -it('keeps the notice absent when the bonus read is refused, then shows the next read', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const orderId = '4c1b0000-0000-4000-8000-000000000000' - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValueOnce({ - ok: false, error: new RemoteError('gateway/internal', 'offline', {}), - }) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledOnce() }) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() - expect(c.mock.remote.account.ackBonusNotified).not.toHaveBeenCalled() - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus(orderId))) - await actions.refreshAccount() - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]).toMatchObject({ orderId, message: 'Awarded 5.00' }) - }) -}, 60_000) - -it('drops the previous account notice and stops reading after sign-out', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(bonus('4c1b0000-0000-4000-8000-000000000001'))) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { - expect(actions.hooks.account.getSnapshot().notices?.[0]?.message).toBe('Awarded 5.00') - }) - c.mock.streams.push('account/watch', view) - await vi.waitFor(() => { expect(actions.hooks.account.getSnapshot().view).toEqual(view) }) - expect(actions.hooks.account.getSnapshot().notices?.[0]).toBeUndefined() - // Signing out ends the lifecycle, so no further read follows. - const reads = c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length - await new Promise((resolve) => { setTimeout(resolve, 20) }) - expect(c.mock.remote.account.getUnnotifiedBonuses.mock.calls.length).toBe(reads) -}, 60_000) - -it('refreshes balances and the bonus read on one Settings entry, without polling', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - const balance: AccountDetails['balance'] = { - status: 'ready', value: [{ currency: 'CNY', balance: '12.34' }], bonusWallets: [{ currency: 'CNY', balance: '5.00' }], - } - c.mock.remote.account.getBalance.mockResolvedValue(ok(balance)) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - // Signing in reads once; nothing else reads on a timer. - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - await new Promise((resolve) => { setTimeout(resolve, 20) }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) - // Signing in already read the wallet once through the details refresh. - const balances = c.mock.remote.account.getBalance.mock.calls.length - await actions.refreshAccount() - expect(c.mock.remote.account.getBalance).toHaveBeenCalledTimes(balances + 1) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(2) - // The bonus read carries the active UI language. - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith(expect.objectContaining({ locale: 'en' })) -}, 60_000) - -it('publishes a failed balance from a Settings entry without dropping the bonus read', async ({ start }) => { - vi.stubGlobal('dshDesktop', {}) - const c = await start() - const actions = operations(c) - c.mock.remote.account.getBalance.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) }) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - await actions.refreshAccount() - expect(actions.hooks.account.getSnapshot().details?.balance).toEqual({ status: 'failed' }) - // The bonus read still ran: a failed wallet read does not cancel it. - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(2) -}, 60_000) - it('publishes a terminal state-stream failure without mistaking it for plugin disposal', async ({ start }) => { vi.stubGlobal('dshDesktop', {}) const c = await start() @@ -681,16 +552,16 @@ it('samples the build version, language, and UTC offset for every account call', const c = await start() const actions = operations(c) const offset = vi.spyOn(Date.prototype, 'getTimezoneOffset').mockReturnValue(480) - c.mock.remote.account.getUnnotifiedBonuses.mockResolvedValue(ok(null)) - c.mock.streams.push('account/watch', stored) - await vi.waitFor(() => { expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenCalledTimes(1) }) - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith({ + c.mock.remote.account.getNotifications.mockResolvedValue(ok(null)) + c.mock.streams.push('account/watch', { type: 'snapshot', state: stored }) + await vi.waitFor(() => { expect(c.mock.remote.account.getNotifications).toHaveBeenCalledTimes(1) }) + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith({ version: '0.0.0-test', locale: 'en', timezoneOffsetSeconds: -28_800, }) // The next call reads the zone again instead of reusing the first sample. offset.mockReturnValue(-300) await actions.refreshAccount() - expect(c.mock.remote.account.getUnnotifiedBonuses).toHaveBeenLastCalledWith({ + expect(c.mock.remote.account.getNotifications).toHaveBeenLastCalledWith({ version: '0.0.0-test', locale: 'en', timezoneOffsetSeconds: 18_000, }) }, 60_000) @@ -783,3 +654,27 @@ it('applies API-key defaults through the desktop slot and shared configuration o expect(values['ui-settings']).toEqual({ enabled: true }) expect(values['ui-chat']).toMatchObject({ transcriptView: 'standard' }) }, 60_000) + + +it('ignores a delayed iterator rejection after the account plugin has unloaded', async ({ start }) => { + const c = await start() + const entered = Promise.withResolvers() + const failed = Promise.withResolvers() + onTestFinished(() => { failed.resolve(undefined) }) + const original = c.ctx.remote.$stream.bind(c.ctx.remote) + vi.spyOn(c.ctx.remote, '$stream').mockImplementation((options) => { + const stream = original(options) + vi.spyOn(stream, Symbol.asyncIterator).mockImplementation(async function* () { + entered.resolve(undefined) + await failed.promise + }) + return stream + }) + await c.reload(SELF) + await entered.promise + const actions = operations(c) + await c.unload(SELF) + failed.reject(new Error('late stream rejection')) + await c.flush() + expect(actions.hooks.account.getSnapshot()).toMatchObject({ view: undefined, failed: false }) +}) diff --git a/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts b/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts deleted file mode 100644 index 6ab5b50104..0000000000 --- a/packages/client/ui-settings-account/tests/bonus-notices.client.spec.ts +++ /dev/null @@ -1,612 +0,0 @@ -// @vitest-environment jsdom -/** - * Bonus notice lifecycle: reads happen when the account becomes active and on - * an explicit refresh, never on a timer. A notice is acknowledged only after its - * card reports a presented frame, with backoff retry for the rest of the - * signed-in lifecycle; nothing about a notice survives sign-out or unload. - */ -import { afterEach, expect, it, vi } from 'vitest' -import type { AccountBonusBatch, AccountBonusOrderId, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import { createBonusNoticeController, type BonusNotice } from '../src/client/bonus-notices.ts' - -const TIMING = { ackRetryDelayMs: 1_000, ackRetryMaxDelayMs: 60_000 } - -/** - * @param accountId - owning account. - * @param orderId - server order. - * @param expiresAt - server expiration. - * @returns one unnotified bonus as the Host projects it. - */ -function batch(accountId: string, orderId: string, expiresAt = '2099-01-01T00:00:00Z'): AccountBonusBatch { - return { - accountId: accountId as AccountUserId, - bonuses: [{ - orderId: orderId as AccountBonusOrderId, - expiresAt, - message: 'Server copy 5.00', - }], - } -} - -function setup() { - const read = vi.fn(async (): Promise => null) - const acknowledge = vi.fn(async (): Promise => true) - const stacks: (readonly BonusNotice[])[] = [] - const published: (BonusNotice | null)[] = [] - const controller = createBonusNoticeController({ - ...TIMING, read, acknowledge, publish: (notices) => { stacks.push(notices); published.push(notices[0] ?? null) }, - }) - /** @returns the most recently published notice. */ - const latest = (): BonusNotice | null | undefined => published.at(-1) - return { controller, read, acknowledge, published, latest, stacks } -} - -afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() }) - -it('reads once when the account becomes active and never on a timer', async () => { - vi.useFakeTimers() - const { controller, read } = setup() - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(1) - // Nothing else schedules a read: only an explicit refresh does. - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - expect(read).toHaveBeenCalledTimes(1) - await controller.refresh() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(2) - controller.end() -}) - -it('publishes the server copy for the first unnotified order', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', message: 'Server copy 5.00' }) }) - controller.end() -}) - -it('acknowledges only after the card reports a presented frame, then keeps the card until it is closed', async () => { - const { controller, read, acknowledge, published, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - expect(acknowledge).not.toHaveBeenCalled() - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - // A refresh still offering the order must not republish the open card. - const publishedBefore = published.length - await controller.refresh() - await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(2) }) - expect(published.length).toBe(publishedBefore) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.dismiss('order-1' as AccountBonusOrderId) - expect(latest()).toBeNull() - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('retries a failed acknowledgement with a growing backoff starting at the configured delay', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs - 1) - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(acknowledge).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 2) - expect(acknowledge).toHaveBeenCalledTimes(3) - controller.end() -}) - -it('keeps the card and its pending acknowledgement when the signed-in session re-enters', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // The second commit update of one sign-in and a reconnected stream's replayed - // state both re-enter here. Each frame reads again, and neither may drop the - // card or stop the failed acknowledgement from backing off. - controller.begin() - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(3) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - controller.end() -}) - -it.each(['aborted', 'null'] as const)("does not adopt the replaced credential's in-flight read when it answers %s", async (answer) => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // Account A's next signed-in frame starts a read the Host abandons when the - // credential is replaced by B. B's frame must not inherit it: A's answer names - // the replaced account, so adopting it would leave B with no read of its own. - const abandoned = Promise.withResolvers() - read.mockReturnValueOnce(abandoned.promise) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - read.mockResolvedValueOnce(batch('account-b', 'order-2')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(read).toHaveBeenCalledTimes(3) - expect(latest()).toMatchObject({ orderId: 'order-2' }) - if (answer === 'aborted') abandoned.reject(new Error('aborted')) - else abandoned.resolve(null) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - // The abandoned answer neither restores A's card nor resumes A's retry. - expect(latest()).toMatchObject({ orderId: 'order-2' }) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('refreshes the copy of the order already on screen when a read offers it again', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', message: 'Server copy 5.00' }) }) - // The same order arrives with new copy: its card updates in place instead of being replaced. - read.mockResolvedValue({ ...batch('account-a', 'order-1'), bonuses: [{ ...batch('account-a', 'order-1').bonuses[0]!, title: 'Updated title', message: 'Updated copy' }] }) - await controller.refresh() - expect(latest()).toMatchObject({ orderId: 'order-1', title: 'Updated title', message: 'Updated copy' }) - controller.end() -}) - -it('withdraws a card the user never saw when a read offers no bonus', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // The card never reported a presented frame, so an empty read withdraws it. - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [] }) - await controller.refresh() - expect(latest()).toBeNull() - controller.end() -}) - -it('queues the next shown order behind a settling acknowledgement', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((resolve) => { settle = resolve })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // A later order replaces the card while the first acknowledgement is still settling. - read.mockResolvedValue(batch('account-a', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.shown('order-2' as AccountBonusOrderId) - settle?.(true) - // The settled order clears and the next one follows without a further display. - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'order-2') }) - controller.end() -}) - -it('ignores an acknowledgement pump that fires while one is already in flight', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementation(() => new Promise((resolve) => { settle = resolve })) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // A Settings entry schedules another pump while the first call is unresolved. - read.mockResolvedValue(batch('account-a', 'order-1')) - void controller.refresh() - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - settle?.(true) - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.end() -}) - -it('stops retrying when the account changes while an acknowledgement is failing', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let fail: ((reason: Error) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // Another account answers before account-a's call fails: its failure must not - // schedule a retry into the new account's queue. - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - fail?.(new Error('offline')) - await new Promise((resolve) => { setTimeout(resolve, 10) }) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('ignores a dismissal that names an order the card does not show', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.dismiss('order-2' as AccountBonusOrderId) - // The other order's dismissal neither withdraws this card nor queues its acknowledgement. - expect(latest()).toMatchObject({ orderId: 'order-1' }) - expect(acknowledge).not.toHaveBeenCalled() - controller.end() -}) - -it('keeps one queued acknowledgement when a reported order returns after another card', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - read.mockResolvedValue(batch('account-a', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - read.mockResolvedValue(batch('account-a', 'order-1')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // Its acknowledgement was already queued and is still retrying, so no second entry joins it. - controller.shown('order-1' as AccountBonusOrderId) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.end() -}) - -it('displays an order the server offers again after an earlier sign-in acknowledged it', async () => { - const first = setup() - first.read.mockResolvedValue(batch('account-a', 'order-1')) - first.controller.begin() - await vi.waitFor(() => { expect(first.latest()).toMatchObject({ orderId: 'order-1' }) }) - first.controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(first.acknowledge).toHaveBeenCalledTimes(1) }) - first.controller.end() - // Nothing is remembered, so the same order the server still offers displays again. - const second = setup() - second.read.mockResolvedValue(batch('account-a', 'order-1')) - second.controller.begin() - await vi.waitFor(() => { expect(second.latest()).toMatchObject({ orderId: 'order-1' }) }) - second.controller.end() -}) - -it('discards the previous account card and retries when a credential is replaced without a signed-out frame', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockResolvedValue(false) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledOnce() }) - // The credential is replaced in place: another signed-in frame arrives, the read - // names the other account, and no signed-out frame ever describes the switch. - read.mockResolvedValue(batch('account-b', 'order-2')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.end() -}) - -it('keeps the retry going when the re-entry read fails', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledTimes(1) - // The replayed state re-enters and its read fails; a failed read must leave the - // pending acknowledgement retrying rather than strand it. - read.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - controller.end() -}) - -it('acknowledges a re-offered order once per displayed card', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - // Closing the card withdraws it; the next read of the same order is a new card. - controller.dismiss('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(2) }) - controller.end() -}) - -it('keeps the visible card when a read offers no bonus', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - // A card the user has already seen keeps its place. - controller.shown('order-1' as AccountBonusOrderId) - // A Settings entry whose read returns nothing must not pull the card out from under the user. - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [] }) - await controller.refresh() - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.dismiss('order-1' as AccountBonusOrderId) - await controller.refresh() - expect(latest()).toBeNull() - controller.end() -}) - -it('keeps a pending acknowledgement for the signed-in lifecycle and drops it at sign-out', async () => { - // Advance the backoff clock explicitly so retry observation has no competing deadline. - vi.useFakeTimers() - const { controller, read, acknowledge, latest } = setup() - acknowledge.mockRejectedValue(new Error('offline')) - read.mockResolvedValue(batch('account-a', 'order-1')) - const again = setup() - try { - controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(latest()).toMatchObject({ orderId: 'order-1' }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') - expect(acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs) - expect(acknowledge).toHaveBeenCalledTimes(2) - - // Signing out ends the retry with the lifecycle; the next sign-in starts clean. - controller.end() - const callsAtEnd = acknowledge.mock.calls.length - again.read.mockResolvedValue(batch('account-a', 'order-1')) - again.controller.begin() - await vi.advanceTimersByTimeAsync(0) - expect(again.latest()).toMatchObject({ orderId: 'order-1' }) - // The next sign-in must not inherit the earlier pending acknowledgement. - expect(again.acknowledge).not.toHaveBeenCalled() - expect(acknowledge.mock.calls.length).toBe(callsAtEnd) - // Past the next retry delay: the ended lifecycle scheduled nothing. - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 3) - expect(acknowledge.mock.calls.length).toBe(callsAtEnd) - } finally { - controller.end() - again.controller.end() - } -}) - -it('ignores an acknowledgement that settles after the lifecycle it belonged to', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settle: ((value: boolean) => void) | undefined - acknowledge.mockImplementation(() => new Promise((resolve) => { settle = resolve })) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - controller.end() - // The new sign-in has its own pending queue; the old call settling later must not touch it. - const next = setup() - next.read.mockResolvedValue(batch('account-a', 'order-2')) - next.controller.begin() - await vi.waitFor(() => { expect(next.latest()).toMatchObject({ orderId: 'order-2' }) }) - next.controller.shown('order-2' as AccountBonusOrderId) - await vi.waitFor(() => { expect(next.acknowledge).toHaveBeenCalledTimes(1) }) - settle?.(true) - await new Promise((resolve) => { setTimeout(resolve, 5) }) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - expect(next.latest()).toMatchObject({ orderId: 'order-2' }) - next.controller.end() -}) - -it('does not let an in-flight acknowledgement of one account clear another account\'s queue', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - let settleA: ((value: boolean) => void) | undefined - acknowledge.mockImplementationOnce(() => new Promise((resolve) => { settleA = resolve })) - acknowledge.mockResolvedValue(true) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - // Another account answers the same lifecycle before account-a's call settles. - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - settleA?.(true) - await new Promise((resolve) => { setTimeout(resolve, 5) }) - // The stale answer settled account-a's order, not account-b's retry. - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.shown('order-2' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-b', 'order-2') }) - controller.end() -}) - -it('restarts the retry delay after a lifecycle ends', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - acknowledge.mockRejectedValue(new Error('offline')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs * 3) - expect(acknowledge.mock.calls.length).toBeGreaterThan(2) - controller.end() - // The next lifecycle starts from the configured delay, not the previous backoff. - const next = setup() - next.read.mockResolvedValue(batch('account-a', 'order-2')) - next.acknowledge.mockRejectedValue(new Error('offline')) - next.controller.begin() - await vi.advanceTimersByTimeAsync(0) - next.controller.shown('order-2' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(0) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryDelayMs - 1) - expect(next.acknowledge).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(1) - expect(next.acknowledge).toHaveBeenCalledTimes(2) - next.controller.end() -}) - -it('withdraws the displayed card when the signed-in account changes', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - read.mockResolvedValue(batch('account-b', 'order-2')) - await controller.refresh() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-2' }) }) - controller.end() -}) - -it('never acknowledges after the plugin unloads', async () => { - vi.useFakeTimers() - const { controller, read, acknowledge } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.advanceTimersByTimeAsync(0) - controller.end() - controller.shown('order-1' as AccountBonusOrderId) - await vi.advanceTimersByTimeAsync(TIMING.ackRetryMaxDelayMs) - expect(acknowledge).not.toHaveBeenCalled() -}) - -it('suppresses a bonus that expired before its first presented frame', async () => { - const { controller, read, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1', '2000-01-01T00:00:00Z')) - controller.begin() - await vi.waitFor(() => { expect(read).toHaveBeenCalledTimes(1) }) - expect(latest()).toBeUndefined() - controller.end() -}) - -it('does not record a display when the award expired before the card could render', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1' }) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - // The card refuses to render an expired award, so no display is reported. - controller.shown('order-1' as AccountBonusOrderId) - expect(acknowledge).not.toHaveBeenCalled() - controller.end() -}) - -it('displays and acknowledges a notice without expiration', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'order-1', '')) - controller.begin() - await vi.waitFor(() => { expect(latest()).toMatchObject({ orderId: 'order-1', expiresAt: '' }) }) - controller.shown('order-1' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledWith('account-a', 'order-1') }) - controller.end() -}) - -it('publishes every live notice and only acknowledges the foreground as dismissals advance the stack', async () => { - const { controller, read, acknowledge, stacks } = setup() - const bonuses = ['first', 'second', 'third'].flatMap(id => batch('account-a', id, '').bonuses) - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toEqual(bonuses) }) - controller.shown('second' as AccountBonusOrderId) - controller.dismiss('third' as AccountBonusOrderId) - expect(acknowledge).not.toHaveBeenCalled() - expect(stacks.at(-1)).toEqual(bonuses) - controller.shown('first' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'first') }) - controller.dismiss('first' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual(bonuses.slice(1)) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.shown('second' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'second') }) - controller.dismiss('second' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual(bonuses.slice(2)) - controller.dismiss('third' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual([]) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenLastCalledWith('account-a', 'third') }) - controller.end() -}) - -it('drops queued notices that expire before promotion without acknowledging them', async () => { - const { controller, read, acknowledge, stacks } = setup() - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [ - ...batch('account-a', 'first', '').bonuses, - ...batch('account-a', 'expired', '2099-01-01T00:00:00Z').bonuses, - ...batch('account-a', 'last', '').bonuses, - ] }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(3) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - controller.dismiss('first' as AccountBonusOrderId) - expect(stacks.at(-1)?.map(notice => notice.orderId)).toEqual(['last']) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'first') }) - controller.end() -}) - -it('publishes a title-only refresh without acknowledging the same card twice', async () => { - const { controller, read, acknowledge, latest } = setup() - read.mockResolvedValue(batch('account-a', 'first', '')) - controller.begin() - await vi.waitFor(() => { expect(latest()?.orderId).toBe('first') }) - controller.shown('first' as AccountBonusOrderId) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledTimes(1) }) - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, - bonuses: batch('account-a', 'first', '').bonuses.map(notice => ({ ...notice, title: 'Updated title' })) }) - await controller.refresh() - expect(latest()?.title).toBe('Updated title') - controller.shown('first' as AccountBonusOrderId) - expect(acknowledge).toHaveBeenCalledTimes(1) - controller.end() -}) - -it('does not read or acknowledge when refreshed outside an active account lifecycle', async () => { - const { controller, read, acknowledge } = setup() - await controller.refresh() - expect(read).not.toHaveBeenCalled() - expect(acknowledge).not.toHaveBeenCalled() -}) - -it('closes the visible notice when the preceding card expires before its display callback', async () => { - const { controller, read, acknowledge, stacks } = setup() - read.mockResolvedValue({ accountId: 'account-a' as AccountUserId, bonuses: [ - ...batch('account-a', 'first', '2099-01-01T00:00:00Z').bonuses, - ...batch('account-a', 'second', '').bonuses, - ] }) - controller.begin() - await vi.waitFor(() => { expect(stacks.at(-1)).toHaveLength(2) }) - vi.spyOn(Date, 'now').mockReturnValue(Date.parse('2100-01-01T00:00:00Z')) - controller.dismiss('second' as AccountBonusOrderId) - expect(stacks.at(-1)).toEqual([]) - await vi.waitFor(() => { expect(acknowledge).toHaveBeenCalledExactlyOnceWith('account-a', 'second') }) - controller.end() -}) diff --git a/packages/client/ui-settings-account/tests/config.client.spec.ts b/packages/client/ui-settings-account/tests/config.client.spec.ts index 850cf78660..1129937481 100644 --- a/packages/client/ui-settings-account/tests/config.client.spec.ts +++ b/packages/client/ui-settings-account/tests/config.client.spec.ts @@ -11,13 +11,12 @@ const PAGE_PEER = { principal: { kind: 'owner' } } as Parameters { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) - const config: Config = Config({ contactSource: 'harness', bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100 }) - await ctx.plugin({ Config, apply }, { contactSource: 'harness', bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100 }) + const config: Config = Config({ contactSource: 'harness' }) + await ctx.plugin({ Config, apply }, { contactSource: 'harness' }) const table: IndexInjection[] = [] ctx.emit('webserver/index-inject', table, PAGE_PEER) expect(table).toEqual([{ kind: 'global', name: CONTACT_CONFIG_GLOBAL, value: { contactFormUrl: config.contactFormUrl, contactSource: config.contactSource, - bonusAckRetryDelayMs: 25, bonusAckRetryMaxDelayMs: 100, } }]) await ctx.fiber.dispose() table.length = 0 diff --git a/packages/client/ui-settings-account/tests/initialization.client.spec.ts b/packages/client/ui-settings-account/tests/initialization.client.spec.ts index a17217f0d2..a6f1d82767 100644 --- a/packages/client/ui-settings-account/tests/initialization.client.spec.ts +++ b/packages/client/ui-settings-account/tests/initialization.client.spec.ts @@ -24,10 +24,12 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize const signedIn: AccountView = { status: 'credential-stored', links, attempt: { id: 'login' as SignInAttemptId, phase: 'succeeded' }, } - const frames: AccountView[] = [signedIn, signedIn, { status: 'signed-out', links, attempt: null }] + const frames: AccountView[] = [signedIn, signedIn, signedIn, { status: 'signed-out', links, attempt: null }] + const getNotifications = vi.fn(async () => ({ ok: true, value: null })) const disposers: (() => void)[] = [] let operations: AccountSectionInjected | undefined const ctx = { + on: () => () => {}, provide: () => {}, emit: () => {}, parallel: async () => [], effect: (install: () => (() => void) | undefined) => { const dispose = install(); if (dispose) disposers.push(dispose) }, locale: { register: () => () => {}, bind: () => (key: string) => key, getSnapshot: () => ({ active: 'en' }) }, configForms: { @@ -55,11 +57,12 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize remote: { $on: () => () => {}, session: { initializeDefaultModel }, - account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }) }, + account: { getProfile: async () => ({ ok: true, value: null }), getBalance: async () => ({ ok: true, value: null }), + getNotifications }, $stream: () => ({ signal: abort.signal, dispose: () => { abort.abort(); release.resolve(undefined) }, async *[Symbol.asyncIterator]() { - for (const value of frames) yield { value, accept: () => { + for (const [index, value] of frames.entries()) yield { generation: index < 2 ? 1 : 2, value: { type: 'snapshot', state: value }, accept: () => { const snapshot = operations?.hooks.account.getSnapshot() observed.push({ status: snapshot?.view?.status, failed: snapshot?.failed }) if (value.status === 'signed-out') done.resolve(undefined) @@ -73,7 +76,9 @@ it.each(['accepted', 'refused', 'disconnected', 'pending'] as const)('initialize apply(ctx as never) await done.promise expect(initializeDefaultModel).toHaveBeenCalledExactlyOnceWith() + expect(getNotifications).not.toHaveBeenCalled() expect(observed).toEqual([ + { status: 'credential-stored', failed: false }, { status: 'credential-stored', failed: false }, { status: 'credential-stored', failed: false }, { status: 'signed-out', failed: false }, diff --git a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx index 04b3a65747..21523784dc 100644 --- a/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/onboarding.client.spec.tsx @@ -34,7 +34,7 @@ it('claims onboarding while loading, offers API key fallback, and completes afte useTheme: (select: (snapshot: ThemeSnapshot) => T) => select(theme), start: vi.fn(async () => {}), cancel: vi.fn(async () => {}), signOut: vi.fn(async () => {}), contactUs: vi.fn(), t: makeTranslate(en), - refreshAccount: vi.fn(async () => {}), bonusNoticeShown: vi.fn(), bonusNoticeDismissed: vi.fn(), + refreshAccount: vi.fn(async () => {}), avatarFailed: vi.fn(), } const view = render() diff --git a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx index 89fe09d0fe..7393ce1d5a 100644 --- a/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx +++ b/packages/client/ui-settings-account/tests/quota-notice-hold.client.spec.tsx @@ -66,7 +66,7 @@ function sectionOperations(account: AccountSnapshot, pages: PlatformPages): Acco openPlatformPage: pages.open, refreshAccount: async () => {}, avatarFailed: () => {}, - bonusNoticeShown: () => {}, bonusNoticeDismissed: () => {}, + hasRunningAccountTasks: async () => false, contactUs: () => {}, showLogin: () => {}, setOnboarding: () => {}, start: async () => {}, cancel: async () => {}, signOut: async () => {}, diff --git a/packages/client/ui-settings-general/README.i18n.yaml b/packages/client/ui-settings-general/README.i18n.yaml index fc1c4c4111..a3e6d06c2b 100644 --- a/packages/client/ui-settings-general/README.i18n.yaml +++ b/packages/client/ui-settings-general/README.i18n.yaml @@ -27,8 +27,8 @@ en: 7600861d064dbc99 zh: a52ba446016e3a21 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation: - en: 9c8c35ae0e672b14 - zh: 503c8e9d24a93d88 + en: 4d25df8fe0e60b20 + zh: cecd02d3b6e47b24 /deepseek-ai-dsh-client-ui-settings-general/understand-the-implementation/ledger-projections: en: fd99444278ab8530 zh: 2efc5831c7e19be1 diff --git a/packages/client/ui-settings-general/README.md b/packages/client/ui-settings-general/README.md index cb8873ba9b..a7782b0518 100644 --- a/packages/client/ui-settings-general/README.md +++ b/packages/client/ui-settings-general/README.md @@ -68,7 +68,7 @@ Desktop also contributes an **Update channel** row to General when the preload e ## Understand the implementation -The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. +The shell declares settings.launcher for an account-owned sidebar menu and retains the Settings button as its fallback. The launcher receives settingsOpen, whose false-to-true edge marks one Settings entry, so a registrant acts once per entry instead of on every re-render inside one open. Closing the dialog returns focus to the active launcher. In the expanded sidebar, the fallback uses the navigation rows' compact icon-label alignment and inset hover fill. Contributed launchers own their insets; the shell keeps its row full-width and its status indicator's trailing edge independent of account state. The collapsed rail retains its centered 36 × 36 px control. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section.
Implementation internals — click to expand diff --git a/packages/client/ui-settings-general/README.zh.md b/packages/client/ui-settings-general/README.zh.md index 9cf20eea0e..a9e949c08e 100644 --- a/packages/client/ui-settings-general/README.zh.md +++ b/packages/client/ui-settings-general/README.zh.md @@ -68,7 +68,7 @@ Web 与桌面端的通用设置底部显示当前发布版本,使用构建注 ## 理解实现 -外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 +外壳声明 settings.launcher,供账号功能提供侧边栏菜单,并以设置按钮作为回退。入口接收 settingsOpen,其 false→true 边沿代表一次进入设置页,因此注册方在每次进入时执行一次,而不是在同一次打开中的每次重渲染执行。关闭对话框后,焦点返回当前入口。侧栏展开时,回退按钮采用导航行的紧凑图文对齐及内缩悬停底色。贡献入口自行拥有内缩;外壳保持行宽占满可用空间,状态指示器的尾侧边缘不随账号状态移动。折叠轨道保留居中的 36 × 36 px 控件。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。
实现细节——点击展开 diff --git a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx index 980e59a06d..95e74201b7 100644 --- a/packages/client/ui-settings-general/src/client/SettingsRoot.tsx +++ b/packages/client/ui-settings-general/src/client/SettingsRoot.tsx @@ -224,7 +224,10 @@ export function SettingsRoot(props: SettingsRootComponentProps) { <>
{renderSlot('settings.launcher', { - wide, settingsOpen: open, openSettings: actions.open, + wide, settingsOpen: open, openSettings: (sectionId) => { + if (sectionId === undefined) actions.open() + else actions.openSection(sectionId) + }, ...(shortcut?.keys.length ? { settingsShortcut: { keys: shortcut.keys, aria: shortcut.aria } } : {}), openOnboarding: (id) => { close(); setRequestedOnboarding(id) }, }, { fallback: diff --git a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx index 094ef4787a..7a3e6ba80f 100644 --- a/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx +++ b/packages/client/ui-settings-general/tests/settings-root.client.spec.tsx @@ -524,6 +524,14 @@ it('opens Account from the contributed sidebar launcher', () => { expect(renderSlot.mock.calls.filter(call => call[0] === 'settings.launcher').at(-1)?.[1]).toMatchObject({ settingsOpen: false }) }) +it('opens the section requested by the contributed sidebar launcher', () => { + const { renderSlot } = mount({ rows: [{ id: 'general', order: 0, label: 'General' }, { id: 'account', order: 1, label: 'Account' }] }) + const launcher = renderSlot.mock.calls.find(call => call[0] === 'settings.launcher')! + act(() => { (launcher[1] as { openSettings: (sectionId?: string) => void }).openSettings('account') }) + expect(screen.getByTestId('section-account')).toBeTruthy() + expect(screen.queryByTestId('section-general')).toBeNull() +}) + it('shows the effective settings binding on focus and exposes it to assistive technology', () => { mount({ shortcuts: [{ id: 'settings.open' as ShortcutCommandId, label: 'Open settings', aliases: [], keys: ['⌘', ','], aria: 'Meta+,', binding: { code: 'Comma', modifiers: ['meta'] }, modified: false, conflicts: [], issue: null }] }) const trigger = screen.getByRole('button', { name: 'Settings' }) diff --git a/packages/client/ui-settings-general/tests/shell.client.spec.ts b/packages/client/ui-settings-general/tests/shell.client.spec.ts index 4b5776de36..75af01b079 100644 --- a/packages/client/ui-settings-general/tests/shell.client.spec.ts +++ b/packages/client/ui-settings-general/tests/shell.client.spec.ts @@ -121,13 +121,13 @@ describe('ui-settings-general shell', () => { const { sections } = injectedOf(c).hooks await c.mock.streams.opened('account/watch', 1) expect(sections.getSnapshot().map(row => row.id)).toEqual(PRODUCT_SECTIONS) - c.mock.streams.push('account/watch', { status: 'credential-stored', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'credential-stored', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().map(row => row.id)).toEqual(['account', ...PRODUCT_SECTIONS]) }) - c.mock.streams.push('account/watch', { status: 'credential-stored', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'credential-stored', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().filter(row => row.id === 'account')).toHaveLength(1) }) - c.mock.streams.push('account/watch', { status: 'signed-out', attempt: null }) + c.mock.streams.push('account/watch', { type: 'snapshot', state: { status: 'signed-out', attempt: null } }) await vi.waitFor(() => { expect(sections.getSnapshot().map(row => row.id)).toEqual(PRODUCT_SECTIONS) }) }) diff --git a/packages/client/ui-settings/README.i18n.yaml b/packages/client/ui-settings/README.i18n.yaml index 936371be65..c830f51312 100644 --- a/packages/client/ui-settings/README.i18n.yaml +++ b/packages/client/ui-settings/README.i18n.yaml @@ -30,8 +30,8 @@ en: 9767f17ca0f02ae3 zh: 8e475d6d3d670702 /deepseek-ai-dsh-client-ui-settings/understand-the-implementation: - en: d756fe51d9456fb4 - zh: 41de582aace7332f + en: 84b6449030ffabe7 + zh: 958382ead3ab0407 /deepseek-ai-dsh-client-ui-settings/understand-the-implementation/the-describe-mirror: en: 0cd270ddcac46776 zh: 4e03bf1d153b3f04 diff --git a/packages/client/ui-settings/README.md b/packages/client/ui-settings/README.md index 8fd5dc1f00..51ef808ec7 100644 --- a/packages/client/ui-settings/README.md +++ b/packages/client/ui-settings/README.md @@ -55,7 +55,7 @@ A committed write folds its answer into the shared mirror. Refused writes refres ## Understand the implementation -The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. +The optional `settings.launcher` contribution receives sidebar geometry, whether the open Settings panel covers the sidebar, the settings navigation callbacks, and the effective Settings key labels and accessible combination. The shell omits shortcut presentation for an unbound command and retains its plain Settings trigger when no launcher is registered. The launcher can pass a section ID to openSettings to open that section directly; an absent ID uses the default section.
Implementation internals — click to expand diff --git a/packages/client/ui-settings/README.zh.md b/packages/client/ui-settings/README.zh.md index d0aadf47cc..fff25c57ec 100644 --- a/packages/client/ui-settings/README.zh.md +++ b/packages/client/ui-settings/README.zh.md @@ -55,7 +55,7 @@ kind: "package-reference" ## 理解实现 -可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 +可选的 `settings.launcher` 贡献接收侧栏布局、设置面板是否覆盖侧栏、设置导航回调,以及有效的设置键位标签和无障碍组合。命令未绑定时,外壳不传快捷键展示信息;未注册入口时,外壳保留普通设置按钮。 入口可以向 openSettings 传入分区 ID,直接打开对应分区;未传 ID 时使用默认分区。
实现细节——点击展开 diff --git a/packages/client/ui-settings/src/client/contract/slots.ts b/packages/client/ui-settings/src/client/contract/slots.ts index 0f1dc07d70..dbab0c7df1 100644 --- a/packages/client/ui-settings/src/client/contract/slots.ts +++ b/packages/client/ui-settings/src/client/contract/slots.ts @@ -164,8 +164,8 @@ export interface SettingsLauncherOwnerProps { settingsOpen: boolean /** Effective Settings key labels and accessible combination; omitted when unbound. */ settingsShortcut?: { readonly keys: readonly string[]; readonly aria?: string | undefined } - /** Open the settings panel. */ - openSettings: () => void + /** @param sectionId - section to open; absent uses the shell's default section. */ + openSettings: (sectionId?: string) => void /** @param id - registered onboarding editor to open explicitly. */ openOnboarding: (id: string) => void } diff --git a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json index 6a08bf158f..f2f0c5559d 100644 --- a/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json +++ b/packages/client/ui-theme/tests/expected/radius-exceptions.expected.json @@ -43,7 +43,7 @@ ".instruction: border-radius: 16px", ".delivery: border-radius: 8px" ], - "ui-settings-account/src/client/AccountNotice.module.css": [ + "ui-account-notifications/src/client/AccountNotifications.module.css": [ ".card: border-radius: 16px" ], "ui-settings-account/src/client/DesktopOnboarding.module.css": [ diff --git a/packages/credentials/deepseek-account-platform/README.i18n.yaml b/packages/credentials/deepseek-account-platform/README.i18n.yaml deleted file mode 100644 index 9e6ffe9905..0000000000 --- a/packages/credentials/deepseek-account-platform/README.i18n.yaml +++ /dev/null @@ -1,37 +0,0 @@ -# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write packages/credentials/deepseek-account-platform/README.md -/: - en: 9dbb9bc3960a11fe - zh: ed58987926489d3e -/deepseek-ai-dsh-deepseek-account-platform: - en: 7be860d52e1202db - zh: a2612757253d67a6 -/deepseek-ai-dsh-deepseek-account-platform/summary: - en: 28bcca957bf6abf4 - zh: 4a3fc8a59f2925bc -/deepseek-ai-dsh-deepseek-account-platform/table-of-contents: - en: af856ba79fe31b8e - zh: 15b7d1a5d1856de2 -/deepseek-ai-dsh-deepseek-account-platform/use-this-package: - en: 56bee240f50c293a - zh: 6c4c5de6088c9d79 -/deepseek-ai-dsh-deepseek-account-platform/understand-the-implementation: - en: 76d2da2dab100ac3 - zh: 2c9404f27915daab -/deepseek-ai-dsh-deepseek-account-platform/further-exploration: - en: c8b43a641360ec9e - zh: a545f6a0b6a5066b -/deepseek-ai-dsh-deepseek-account-platform/model-experience: - en: ee1df7ca3467ee3f - zh: 84904a5148da3862 -/deepseek-ai-dsh-deepseek-account-platform/model-experience/kv-cache-effect: - en: ca3015e252db0114 - zh: ebca9253cf15e8e9 -/deepseek-ai-dsh-deepseek-account-platform/known-limitations-and-deferred-work: - en: 1b26fcb10e139c27 - zh: 8babfccddabdabc4 -/deepseek-ai-dsh-deepseek-account-platform/known-limitations-and-deferred-work/dev-note: - en: c5d41d3333c20c2b - zh: 41442ff16d92b37a diff --git a/packages/credentials/deepseek-account-platform/README.md b/packages/credentials/deepseek-account-platform/README.md deleted file mode 100644 index 104b597c9a..0000000000 --- a/packages/credentials/deepseek-account-platform/README.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -description: "Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in." -kind: "package-reference" ---- - -# @deepseek-ai/dsh-deepseek-account-platform - -English | [中文](README.zh.md) - -Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The provider derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. - -getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. - -`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The provider owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. - -Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. - -## Summary - -Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in. - -Platform requests report `no-response` when fetch rejects before returning a Response, including request timeouts. HTTP errors and response-body failures do not use this code; authorization-attempt expiry retains `expired`. - -Device identity reads validate the existing login device record and expose only its ID, the current account ID, and the shared login OS version string. - -## Table of Contents - -- [Use this package](#use-this-package) -- [Model Experience](#model-experience) -- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) - - -## Use this package - -The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. - -Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. - -getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. - -getUnnotifiedBonuses reads GET /api/v0/users/get_unnotified_bonuses and ackBonusNotified posts POST /api/v0/users/ack_bonus_notified with a JSON body naming the order on the same origin, each sending the five client headers built from the caller's metadata. Both resolve the account identity for the captured grant first, so a signed-out or switched account yields null or false instead of acknowledging another account's bonus, and a read publishes only after the whole query settled under one credential lifetime. The Host forwards the bonus list in Platform order, retains the string fields order_id, expires_at and msg, and maps them to orderId, expiresAt and message. An optional string title is forwarded unchanged; null or absent titles use the client default. An empty, null or absent expires_at becomes an empty expiresAt and means the notice never expires. Order IDs need not be UUIDs; campaign, amount, currency and granted_at are optional, unvalidated metadata forwarded as campaign, amount, currency and grantedAt; malformed payloads, other HTTP failures and other business failures throw, while a credential rejection (HTTP 401 or response code `40003`) invalidates the current grant and yields null or false. - -Balance requests use balanceTimeoutMs (30,000ms by default); timeout returns a failed outcome without clearing the account or manufacturing a zero balance. Configure platformOrigin, allowLoopbackHttp, requestTimeoutMs, balanceTimeoutMs, and attemptTimeoutMs in the plugin row. HTTP is accepted only for explicitly enabled loopback development. The provider registers /oauth/callback on the existing Host webServer before auth_init, validates state, exchanges an S256 PKCE code once, and commits a grant before redirecting to auth_exchange.biz_data.authorized_url. Browser destinations default to the configured platform origin and always require the fixed /dsh/authorize or /dsh/authorized path. The completion URL sets `login_source` to the initiating client (`web` or `desktop`) and preserves other Platform-supplied query parameters. Device identity is a separate random UUID record shared by processes using the same credential store; device_model reports OS and architecture. - -Platform URLs have one configuration owner: `platformOrigin`. Authorization requests, browser validation, completion redirects, usage, and top-up destinations all use that origin. Set it in a private `$DSH_HOME/cordis.patch.yml`; deployment addresses do not belong in source control. HTTPS is required except for loopback HTTP with `allowLoopbackHttp: true`. Model and file token destinations use the separate `inferenceOrigin` configuration. - -`requestHeaders` adds Host-only headers to authorization, profile, balance, and logout requests on `platformOrigin`. Header values are secret configuration; they are excluded from account UI state. Authorization, X-DSH-Auth-Token, Host, Content-Type and connection/framing headers are reserved. Client identity headers override same-named deployment headers. Redirects fail without forwarding headers. Store deployment cookies in private configuration or environment variables; browser cookies are not collected automatically. - -A private patch can read environment variables through Cordis expressions: - -```yaml -- id: deepseek-account - config: - platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN - allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' - requestHeaders: !!js | - process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} -``` - -The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The provider fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. Callback requests use state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt route. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. - -Host diagnostics use `console.error` with the `[deepseek-account]` prefix on standard error and in the Host inspector Console, only for request, response-validation, or sign-in failures. Successful requests, caller cancellation, and normal account state changes are silent; request timeouts remain failures. Failure diagnostics include endpoint paths, HTTP status, numeric response codes, failure stages, invalid field paths, received types and validation codes, and browser URL rejection rules; headers, request and response bodies, authorization URLs, and raw exceptions are excluded. - -`rewriteBrowserOrigin` defaults to `false`, requiring same-origin browser URLs. A private development patch may set it to `true` to map authorization and completion URLs to `platformOrigin`, preserving their fixed paths and query strings. Source URLs must use HTTPS or already match the configured origin; user information, fragments and unexpected paths remain rejected. Shipped profiles retain strict same-origin validation. - -inferenceOrigin defaults to `https://api.deepseek.com`. A private deployment patch may replace it with one exact HTTP(S) origin, including its port, for inference and file authentication through x-dsh-auth-token. Paths, URL credentials, queries and fragments are invalid configuration. Alternate origins require a grant issued by the configured platformOrigin; mock tokens remain excluded. Loopback grants cannot authenticate the official production API. Deployment addresses belong in private patches, not shipped configuration. - -At provider initialization, a valid stored grant whose issuer differs from platformOrigin is deleted locally before consumers read account state. Startup continues signed out without a remote logout request; API keys and device identity remain stored. Storage failures remain explicit, and account HTTP or response-validation failures do not delete a matching grant. - - -## Understand the implementation - -Account presence reads the credential store, and attempt state projects private state directly. Behavior tests verify asynchronous cancellation and commit ordering. - - -## Further Exploration - -The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. - -The attemptTimeoutMs limit includes initialization, browser waiting, and exchange. Initialization does not extend its absolute deadline; the server TTL may only shorten the remaining time. Credential persistence admitted before expiry completes without cancellation. - - -## Model Experience - -None, as account credentials affect HTTP authentication and never enter model prompts, Session logs, or tool results. - -#### KV Cache effect - -No model request prefix changes. - -## Known Limitations and Deferred Work - - - -- Browser sign-in requires the Host webServer. Only local access and SSH local forwarding through HTTP localhost, 127.0.0.1, or [::1] with an explicit port are supported; non-loopback reverse proxies are unsupported. Account tokens have no expiry or refresh flow; explicit DSH sign-out removes the local grant before calling POST /auth-api/v0/users/logout in the background. Remote failures never restore local login. The captured old token receives at most five additional attempts with exponential delays of 1, 2, 4, 8, and 16 seconds by default; logoutMaxRetries (0–5) and logoutRetryDelayMs configure that policy. Each request uses requestTimeoutMs. Provider shutdown aborts requests and waits, and pending revocations are not persisted. Local credential deletion failures remain visible to the caller. Authorization-attempt deadlines still apply before a token is issued. Cancellation or timeout after initialization sends one background POST /auth-api/v0/dsh/auth_cancel with the authorize_id from auth_init.biz_data and the original code_verifier, without account authorization. Local cancellation never waits for this request or reverses on failure; requestTimeoutMs bounds it, and provider shutdown aborts it. TODO(product-error-ui): Product must define localized copy and UI behavior for the supplied biz_code values. Until then, business failures use the existing generic retry message; other codes and HTTP errors use the same fallback. Development grants never authenticate production requests. - - -### Dev Note - -The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. - -The first profile read after sign-in uses the sanitized user returned by auth_exchange. A null or malformed user falls back to current; subsequent refreshes and Host restarts also query current. Failed current requests retain the latest successful profile for the same credential in Host memory; credential changes and disposal clear it. A ready current response whose stable account ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, so identity consumers re-read getPlatformSession; refreshes that repeat the same ID stay silent. Exchange registers the submitted device information. - -accountRequestHeaders overlays requestHeaders for current, balance and embedded Platform page/API requests. Cookie pairs merge by name so routing overrides retain other deployment cookies. Authorization initialization, exchange, cancellation and logout keep requestHeaders. Both maps remain private to Host and Electron main; the session's userId stays Host-only too, and renderer bootstrap receives only origin and token. - -The account provider’s `embeddedPageDist` configuration adds a `dist` query parameter to embedded Usage and Top-up URLs. Its default is empty; private frontend branch selectors belong in the local profile patch. It does not change API URLs or credential delivery. - -Platform wallet balances accept decimal strings with optional scientific notation (including `0E-16`); the provider preserves the original string for consumers. diff --git a/packages/credentials/deepseek-account-platform/README.zh.md b/packages/credentials/deepseek-account-platform/README.zh.md deleted file mode 100644 index 7e9b181868..0000000000 --- a/packages/credentials/deepseek-account-platform/README.zh.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -description: "通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。" -kind: "package-reference" ---- - -# @deepseek-ai/dsh-deepseek-account-platform - -[English](README.md) | 中文 - -每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。提供者据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 - -getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 - -`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 - -资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 - -## 概述 - -通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。 - -当 fetch 在返回 Response 前拒绝(包括单次请求超时)时,Platform 请求报告 `no-response`。HTTP 错误和响应体失败不使用此代码;授权尝试到期仍使用 `expired`。 - -设备身份读取会校验已有登录设备记录,仅提供设备 ID、当前账户 ID 和与登录共用的操作系统版本字符串。 - -## 目录 - -- [使用此包](#use-this-package) -- [模型体验](#model-experience) -- [已知限制与后续工作](#known-limitations-and-deferred-work) - - -## 使用此包 - -本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 - -账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 - -getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 - -getUnnotifiedBonuses 读取同一来源上的 GET /api/v0/users/get_unnotified_bonuses,ackBonusNotified 向 POST /api/v0/users/ack_bonus_notified 发送仅含订单号的 JSON 正文,两者都按调用方元数据组装这五个客户端请求头。二者都先为捕获到的授权解析账号身份,因此退登或切号时返回 null 或 false,而不会确认另一个账号的赠金;一次读取只有在同一凭证生命周期内全部结算后才发布。Host 按 Platform 返回顺序转发赠金列表,保留字符串字段 order_id、expires_at 和 msg,并映射为 orderId、expiresAt 和 message。可选的字符串 title 原样转发;null 或缺省表示使用客户端默认标题。expires_at 为空字符串、null 或缺省时,统一转为空字符串 expiresAt,表示通知永不过期。订单号不要求 UUID 格式;campaign、amount、currency 和 granted_at 均为可选元数据,不做校验,分别原样转发为 campaign、amount、currency 和 grantedAt;格式错误、其他 HTTP 失败和其他业务失败都会抛出,而凭据被拒绝(HTTP 401 或响应码 `40003`)会使当前授权失效并返回 null 或 false。 - -余额请求使用 balanceTimeoutMs(默认 30,000ms);超时返回失败结果,不清除账号,也不制造零余额。在插件行配置 platformOrigin、allowLoopbackHttp、requestTimeoutMs、balanceTimeoutMs 和 attemptTimeoutMs。HTTP 仅用于显式启用的本机开发。提供者先在现有 Host webServer 注册 /oauth/callback,再调用 auth_init;校验 state、使用 S256 PKCE 授权码兑换一次,并在跳转 auth_exchange.biz_data.authorized_url 前提交授权记录。浏览器地址默认要求匹配配置的平台来源,并始终要求固定的 /dsh/authorize 或 /dsh/authorized 路径。完成页地址将 `login_source` 设为发起登录的客户端类型(`web` 或 `desktop`),并保留平台返回的其他查询参数。设备标识是独立的随机 UUID 记录,由使用同一凭证存储的进程共享;device_model 报告操作系统和架构。 - -开放平台 URL 统一由 `platformOrigin` 配置管理。授权请求、浏览器地址校验、完成跳转、用量和充值入口都使用该来源。将配置放在私有的 `$DSH_HOME/cordis.patch.yml`,部署地址不进入源码仓库。默认要求 HTTPS;只有本机 HTTP 可通过 `allowLoopbackHttp: true` 显式启用。模型及文件 token 的目标由独立的 `inferenceOrigin` 配置管理。 - -`requestHeaders` 为 `platformOrigin` 上的授权、资料、余额和退登请求添加仅 Host 使用的请求头。请求头值属于敏感配置,不包含在账号 UI 状态中。Authorization、X-DSH-Auth-Token、Host、Content-Type 及连接和消息分帧请求头由提供者保留。客户端身份请求头覆盖部署配置中的同名请求头。重定向会失败,不会转发请求头。开发环境 Cookie 应保存在私有配置或环境变量中;不会自动收集浏览器 Cookie。 - -私有 patch 也可通过 Cordis 表达式读取环境变量: - -```yaml -- id: deepseek-account - config: - platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN - allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' - requestHeaders: !!js | - process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} -``` - -已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。提供者固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。回调请求使用 state 和 PKCE 校验,不要求 RPC 鉴权。完成、取消和卸载仅移除本次尝试的路由。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 - -Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error` 写入标准错误及 Host 调试器 Console,前缀为 `[deepseek-account]`。成功请求、调用方主动取消和正常账号状态变化不输出日志;请求超时仍记录为失败。失败诊断包含接口路径、HTTP 状态、数值响应码、失败阶段、校验失败的字段路径、实际类型和校验码,以及浏览器 URL 拒绝规则,不包含请求头、请求和响应正文、授权 URL 或原始异常。 - -`rewriteBrowserOrigin` 默认为 `false`,要求浏览器地址同源。私有开发 patch 可设为 `true`,将授权页和完成页地址映射到 `platformOrigin`,保留固定路径和查询字符串。原地址必须使用 HTTPS 或已匹配配置来源;仍拒绝用户名密码、片段和非预期路径。发布的 profile 保持严格同源校验。 - -inferenceOrigin 默认为 `https://api.deepseek.com`。私有部署 patch 可将其替换为一个精确的 HTTP(S) 来源(含端口),让推理及文件请求通过 x-dsh-auth-token 认证。配置不得包含路径、URL 凭证、查询或片段。其他来源要求授权由配置的 platformOrigin 签发;仍拒绝 Mock token。本机授权不能认证官方生产 API。部署地址保存在私有 patch 中,不随默认配置发布。 - -提供者初始化时,若有效的已存授权 issuer 与 platformOrigin 不同,会在使用方读取账号状态前删除该本地授权,以未登录态继续启动,不发送远端退登请求;API Key 和设备标识保留。存储错误仍明确报错,账号 HTTP 或响应校验失败不会删除来源匹配的授权。 - - -## 理解实现 - -账号是否存在直接读取凭证存储,尝试状态直接投影私有状态。异步取消和提交由行为测试验证。 - - -## 深入探索 - -[凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 - -attemptTimeoutMs 包含初始化、等待浏览器和兑换的耗时。初始化不会延长绝对截止时间;服务端 TTL 只能缩短剩余时间。在到期前已获准的凭证持久化不再取消。 - - -## 模型体验 - -无,因为账号凭证只影响 HTTP 认证,不进入模型提示、Session 日志或工具结果。 - -#### KV Cache effect - -不改变模型请求前缀。 - -## 已知限制与后续工作 - - - -- 浏览器登录需要 Host webServer,仅支持通过带显式端口的 HTTP localhost、127.0.0.1 或 [::1] 本机访问及 SSH 本地转发,不支持非本机域名的反向代理。账号 token 没有过期或刷新流程;用户主动在 DSH 退出登录时,先删除本地授权,再在后台调用 POST /auth-api/v0/users/logout。远程失败不会恢复本地登录态。默认仅针对捕获的旧 token 最多额外重试五次,指数退避间隔为 1、2、4、8、16 秒;logoutMaxRetries(0–5)和 logoutRetryDelayMs 可配置该策略。每次请求使用 requestTimeoutMs。提供者关闭时取消请求和等待,不持久化待撤销任务。本地凭证删除失败仍向调用者报错。签发 token 前的授权尝试仍有有效期。初始化后的取消或超时会在后台发送一次 POST /auth-api/v0/dsh/auth_cancel,携带 auth_init.biz_data 中的 authorize_id 和原始 code_verifier,不附带账号授权。本地取消不等待该请求,也不会因失败而恢复;requestTimeoutMs 限制请求时间,提供者关闭时中止请求。TODO(product-error-ui):产品需定义已给定 biz code 的本地化文案和交互表现。在此之前,业务失败沿用现有“操作失败,请重试”兜底;其他 code 和 HTTP 错误也使用该兜底。开发授权不能认证生产请求。 - - -### 开发备注 - -[桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 - -登录后首次读取资料使用 auth_exchange 返回并经筛选的 user。user 为 null 或格式无效时回退到 current;后续刷新及 Host 重启也查询 current。current 请求失败时保留 Host 内存中同一凭证最近一次成功的资料;凭证变更或提供者销毁时清空。current 成功返回的稳定账号 ID 首次可用或变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取 getPlatformSession;重复相同 ID 的刷新不通知。exchange 负责登记提交的设备信息。 - -accountRequestHeaders 覆盖 requestHeaders,供 current、余额以及内嵌 Platform 页面/API 请求使用。Cookie 按名称合并,路由覆盖保留其他部署 Cookie。授权初始化、兑换、取消和退登保持使用 requestHeaders。两组请求头仅供 Host 和 Electron 主进程使用;快照的 userId 同样仅限 Host,渲染层 bootstrap 仅接收 origin 和 token。 - -账号提供者的 `embeddedPageDist` 配置为内嵌用量和充值页面 URL 添加 `dist` 查询参数。默认值为空;私有前端分支选择值应写在本地 profile patch 中。此配置不改变 API 地址或凭证传递方式。 - -Platform 钱包余额接受带可选科学计数法的十进制字符串(包括 `0E-16`),提供方保留原始字符串供调用方使用。 diff --git a/packages/credentials/deepseek-account-platform/locale/en.json b/packages/credentials/deepseek-account-platform/locale/en.json deleted file mode 100644 index 542b6b880f..0000000000 --- a/packages/credentials/deepseek-account-platform/locale/en.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "meta": { - "title": "deepseek-account-platform" - } -} diff --git a/packages/credentials/deepseek-account-platform/package.json b/packages/credentials/deepseek-account-platform/package.json deleted file mode 100644 index 9c4f09ff16..0000000000 --- a/packages/credentials/deepseek-account-platform/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@deepseek-ai/dsh-deepseek-account-platform", - "description": "Authorize DeepSeek accounts through browser PKCE", - "version": "0.2.2-rc.1", - "publishConfig": { - "access": "public" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", - "directory": "packages/credentials/deepseek-account-platform" - }, - "type": "module", - "main": "lib/index.js", - "types": "lib/types/index.d.ts", - "exports": { - ".": { - "types": "./lib/types/index.d.ts", - "default": "./lib/index.js" - }, - "./types": { - "types": "./lib/types/types.d.ts", - "default": "./lib/types/types.js" - }, - "./src/*": "./src/*", - "./package.json": "./package.json", - "./locale/*.json": "./locale/*.json" - }, - "files": [ - "locale/*.json", - "lib/index.js", - "lib/types/**/*.js", - "lib/types/**/*.d.ts", - "lib/types/**/*.d.ts.map", - "lib/**/*.js.map", - "src" - ], - "license": "MIT", - "peerDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-authorization": "workspace:*", - "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-host-webserver": "workspace:*" - }, - "devDependencies": { - "@deepseek-ai/cordis": "workspace:~", - "@deepseek-ai/dsh-deepseek-account": "workspace:*", - "@deepseek-ai/dsh-authorization": "workspace:*", - "@deepseek-ai/dsh-credentials": "workspace:*", - "@deepseek-ai/dsh-host-webserver": "workspace:*" - }, - "dependencies": { - "@deepseek-ai/schemastery": "workspace:~", - "zod": "4.6.6" - } -} diff --git a/packages/credentials/deepseek-account-platform/src/index.ts b/packages/credentials/deepseek-account-platform/src/index.ts deleted file mode 100644 index 0319a553c3..0000000000 --- a/packages/credentials/deepseek-account-platform/src/index.ts +++ /dev/null @@ -1,660 +0,0 @@ -/** Platform PKCE account provider; browser approval never bypasses local cancellation. */ -import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto' -import type { ServerResponse } from 'node:http' -import type {} from '@deepseek-ai/dsh-host-webserver' -import { arch, platform, release } from 'node:os' -import { promises as streamPromises } from 'node:stream' -import { Context, Service } from '@deepseek-ai/cordis' -import Schema from '@deepseek-ai/schemastery' -import { z } from 'zod' -import { DeepSeekAccount, installAccountTaskCancellation, mergePlatformCookies, platformClientHeaders, platformWireLocale, type AccountBonusBatch, type AccountBonusOrderId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from '@deepseek-ai/dsh-deepseek-account' -import { credentialKey } from '@deepseek-ai/dsh-credentials' -import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' -import { profile, readAccountDetail, readUnnotifiedBonuses, sendBonusNotified } from './details.ts' -import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' -import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' - -const KEY = credentialKey('deepseek-account-platform', 'default') -const DEVICE = credentialKey('deepseek-account-platform', 'device') -const grant = z.object({ version: z.literal(1), token: z.string().min(1), issuer: z.url() }) -const device = z.object({ id: z.uuid() }) - -/** Deployment-specific platform and request deadlines. */ -export interface Config { - /** Platform origin serving auth-api and browser pages. */ - platformOrigin?: string - /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ - desktopPlatform?: 'darwin' | 'win32' | null - /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ - embeddedPageDist?: string - /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ - inferenceOrigin?: string - /** Allow HTTP only on loopback for the development Mock. */ - allowLoopbackHttp?: boolean - /** Map authorization and completion pages to platformOrigin for private development proxies. */ - rewriteBrowserOrigin?: boolean - /** Host-only headers sent exclusively to platformOrigin; account authorization cannot be overridden. */ - requestHeaders?: Record - /** Overrides for profile, balance and embedded Platform requests; Cookie pairs merge by name. Logout retains requestHeaders. */ - accountRequestHeaders?: Record - /** Deadline for each platform HTTP request. */ - requestTimeoutMs?: number - /** Deadline for recharge-wallet queries; timeout returns a failed balance outcome. */ - balanceTimeoutMs?: number - /** Additional logout attempts after the first request fails, at most five. */ - logoutMaxRetries?: number - /** Delay before the first logout retry; each later delay doubles. */ - logoutRetryDelayMs?: number - /** Upper bound for the entire local attempt, even if the server advertises a longer TTL. */ - attemptTimeoutMs?: number -} -/** Validated deployment choices. */ -export const Config = Schema.object({ - platformOrigin: Schema.string().default('https://platform.deepseek.com'), - desktopPlatform: Schema.union([Schema.const('darwin'), Schema.const('win32'), Schema.const(null)]).default(null), - embeddedPageDist: Schema.string().default(''), - inferenceOrigin: Schema.string().default('https://api.deepseek.com'), - allowLoopbackHttp: Schema.boolean().default(false), - rewriteBrowserOrigin: Schema.boolean().default(false), - requestHeaders: Schema.dict(Schema.string().role('secret')).default({}), - accountRequestHeaders: Schema.dict(Schema.string().role('secret')).default({}), - requestTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), - balanceTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), - logoutMaxRetries: Schema.number().min(0).max(5).step(1).default(5), - logoutRetryDelayMs: Schema.number().min(1).max(60_000).default(1_000), - attemptTimeoutMs: Schema.number().min(1).max(3_600_000).default(600_000), -}) - -interface Attempt { - locale: 'en_US' | 'zh_CN' - clientHeaders: Record - view: SignInAttemptView - controller: AbortController - done: Promise - running: Promise - origin: string - loginSource: 'web' | 'desktop' - disposeCallback?: () => Promise - callback?: ServerResponse - initialProfile?: { token: string; value: AccountDetails['profile'] } - completionUrl?: string -} - -/** The platform implementation owns login state and its opaque stored grant. */ -export class PlatformAccount extends DeepSeekAccount { - static inject = ['credentials', 'authorization'] - static Config = Config - private readonly origin: string - private readonly embeddedPageDist: string - private readonly inferenceOrigin: string - private readonly rewriteBrowserOrigin: boolean - private readonly platform: 'darwin' | 'win32' | null - private readonly requestHeaders: Record - private readonly accountRequestHeaders: Record - private readonly requestTimeout: number - private readonly balanceTimeout: number - private readonly attemptTimeout: number - private readonly logoutPolicy: LogoutRetryPolicy - private readonly logoutLifetime = new AbortController() - private readonly revocations = new Set>() - private attempt: Attempt | undefined - private readonly listeners = new Set<(identityOnly: boolean) => void>() - /** - * Latest ready profile read and the grant token it was read with. Binding the token keeps a - * cached identity from answering for a credential that has since changed. - */ - private lastProfile: { readonly token: string; readonly profile: Extract } | undefined - private detailsLifetime = new AbortController() - private closed = false - private removing: Promise | undefined - - /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ - constructor(ctx: Context, config: Config = {}) { - super(ctx) - installAccountTaskCancellation(ctx) - const resolved = Config(config) - this.embeddedPageDist = resolved.embeddedPageDist - this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp) - const inference = new URL(resolved.inferenceOrigin) - if (!['http:', 'https:'].includes(inference.protocol) || inference.username || inference.password - || inference.pathname !== '/' || inference.search || inference.hash) { - throw new Error('account: inferenceOrigin must be an HTTP(S) origin without credentials, path, query or fragment') - } - this.inferenceOrigin = inference.origin - this.rewriteBrowserOrigin = resolved.rewriteBrowserOrigin - this.platform = resolved.desktopPlatform - this.requestHeaders = platformHeaders(resolved.requestHeaders) - const accountHeaders = platformHeaders(resolved.accountRequestHeaders) - this.accountRequestHeaders = { ...this.requestHeaders, ...accountHeaders } - if (accountHeaders.cookie !== undefined) { - this.accountRequestHeaders.cookie = mergePlatformCookies(this.requestHeaders.cookie ?? '', accountHeaders.cookie) - } - this.requestTimeout = resolved.requestTimeoutMs - this.balanceTimeout = resolved.balanceTimeoutMs - this.attemptTimeout = resolved.attemptTimeoutMs - this.logoutPolicy = { - maxRetries: resolved.logoutMaxRetries, delayMs: resolved.logoutRetryDelayMs, requestTimeoutMs: this.requestTimeout, - } - ctx.authorization.registerFlow({ - key: KEY, label: 'DeepSeek', methods: [{ id: 'browser', label: 'DeepSeek' }], - run: (session) => { - const attempt = this.attempt - if (attempt === undefined) return Promise.reject(new PlatformAuthError('protocol')) - attempt.running = this.run(session, attempt) - return attempt.running - }, - }) - ctx.on('credentials/record-updated', (key) => { - if (key !== KEY) return - this.invalidateDetails() - this.changed() - }) - ctx.effect(() => async () => { - this.closed = true - this.logoutLifetime.abort() - this.invalidateDetails() - const active = this.attempt - if (active !== undefined) { - if (active.view.phase !== 'committing') active.controller.abort() - await active.done - } - await this.removing - await Promise.all(this.revocations) - this.changed() - }, 'account: active attempt lifetime') - } - - async [Service.init](): Promise { - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined) return - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - if (parsed.data.issuer === this.origin) return - await this.ctx.credentials.deleteRecord(KEY) - } - - override async getState(): Promise { - const record = await this.ctx.credentials.readRecord(KEY) - if (record !== undefined && (record.kind !== 'grant' || !grant.safeParse(record.payload).success)) { - throw new PlatformAuthError('storage') - } - const attempt = this.attempt?.view ?? null - return { - status: record === undefined ? 'signed-out' : 'credential-stored', - // Credential removal can notify watchers before sign-out finishes clearing the attempt. - attempt: record === undefined && attempt?.phase === 'succeeded' ? null : attempt, - links: { usageUrl: new URL('/usage', this.origin).href, topUpUrl: new URL('/top_up', this.origin).href }, - } - } - - override async getProfile(client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - const result = await this.getDetail('profile', this.detailHeaders(client), { lifetime, stored }) - if (this.detailsLifetime !== lifetime) return null - if (result !== null) this.cacheProfile(stored.token, result) - if (result?.status !== 'failed') return result - // Only this same grant's last ready read may stand in for a failed refresh. - const cached = this.lastProfile?.token === stored.token ? this.lastProfile.profile : undefined - return cached ?? result - } - - override getBalance(client: AccountClientMetadata): Promise { - return this.getDetail('balance', this.detailHeaders(client)) - } - - override async getUnnotifiedBonuses(client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const headers = this.detailHeaders(client) - const stored = await this.readCurrentGrant(lifetime) - if (stored === null) return null - const accountId = await this.currentAccountId(lifetime, stored, headers) - if (accountId === null) return null - try { - const bonuses = await readUnnotifiedBonuses(this.origin, stored.token, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) - return { accountId, bonuses } - } catch (error) { - if (error instanceof AccountUnauthorizedError) { - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return null - } - throw error - } - } - - override async ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise { - const lifetime = this.detailsLifetime - const headers = this.detailHeaders(client) - const stored = await this.readCurrentGrant(lifetime) - if (stored === null) return false - const current = await this.currentAccountId(lifetime, stored, headers) - if (current === null || current !== accountId) return false - try { - await sendBonusNotified(this.origin, stored.token, orderId, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) - return true - } catch (error) { - if (error instanceof AccountUnauthorizedError) { - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return false - } - throw error - } - } - - /** - * Resolve the profile identity bound to one captured grant, within that grant's credential lifetime. - * @param lifetime - credential lifetime the grant was captured under; a change discards the result. - * @param stored - captured grant; the identity query never re-reads a newer credential. - * @param headers - client identity headers of the calling operation. - * @returns the account identity, or null while signed out or after the credential changed. - */ - private async currentAccountId(lifetime: AbortController, stored: z.infer, - headers: Record): Promise { - // A profile already read for this same captured grant names the account, so a bonus read or - // acknowledgement reuses it instead of issuing another current query. - if (this.lastProfile?.token === stored.token) return this.identityOf(this.lastProfile.profile) - const details = await this.getDetail('profile', headers, { lifetime, stored }) - if (details === null) return null - if (details.status === 'failed') { - // The query named no identity, and the cache is empty or belongs to another grant. - throw new PlatformAuthError('network') - } - this.cacheProfile(stored.token, details) - return this.identityOf(details) - } - - /** - * Cache one ready profile against the grant token it was read with, so identity reuse cannot cross - * a credential change. A stable ID that first appears or changes notifies identity-enabled watch consumers, so - * identity consumers re-read getPlatformSession; repeated IDs stay silent. - * @param token - grant the profile was read with. - * @param profile - profile outcome to record when it carries account data. - */ - private cacheProfile(token: string, profile: AccountDetails['profile']): void { - if (profile.status !== 'ready') return - // Identity publishers re-read the session snapshot; wake them only when the stable ID changes. - const previous = this.lastProfile?.profile.value.id || null - this.lastProfile = { token, profile } - if (previous !== (profile.value.id || null)) this.changed(true) - } - - /** - * @param profile - ready profile projected for the UI. - * @returns the account identity it names. - * @throws PlatformAuthError when the profile carries no stable Platform id, which cannot isolate notices. - */ - private identityOf(profile: Extract): AccountUserId { - if (profile.value.id === null) throw new PlatformAuthError('protocol') - return profile.value.id - } - - private async getDetail(field: K, headers: Record, - captured?: { lifetime: AbortController; stored: z.infer }): Promise { - const lifetime = captured?.lifetime ?? this.detailsLifetime - const stored = captured?.stored ?? await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - if (field === 'profile' && this.attempt?.initialProfile?.token === stored.token) { - const initial = this.attempt.initialProfile.value - delete this.attempt.initialProfile - return initial as AccountDetails[K] - } - try { - const details = await readAccountDetail(field, this.origin, stored.token, - AbortSignal.any([lifetime.signal, AbortSignal.timeout(field === 'balance' ? this.balanceTimeout : this.requestTimeout)]), headers) - return this.detailsLifetime !== lifetime ? null : details - } catch (_unauthorized) { - // readAccountDetail exposes only authenticated credential rejection failures. - if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) - return null - } - } - - /** Deployment account headers plus the client identity headers derived from one call's metadata. */ - private detailHeaders(client: AccountClientMetadata): Record { - return { ...this.accountRequestHeaders, ...platformClientHeaders(this.platform, client) } - } - - override async rejectToken(token: string): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored?.token !== token || this.detailsLifetime !== lifetime) return - await this.expireCredential(token, lifetime) - } - - private async expireCredential(token: string, lifetime: AbortController): Promise { - this.removing ??= (async () => { - if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) - const record = await this.ctx.credentials.readRecord(KEY) - if (this.closed || this.detailsLifetime !== lifetime || record?.kind !== 'grant') return this.getState() - const current = grant.parse(record.payload) - if (current.token !== token || current.issuer !== this.origin) return this.getState() - await this.ctx.credentials.deleteRecord(KEY) - this.ctx.emit('deepseek-account/session-expired') - this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') - this.changed() - return this.getState() - })().finally(() => { this.removing = undefined }) - await this.removing - } - - override async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> { - const [record, session] = await Promise.all([ - this.ctx.credentials.readRecord(DEVICE), - this.getPlatformSession(), - ]) - const parsed = record?.kind === 'grant' ? device.safeParse(record.payload) : undefined - return { - ...parsed?.success ? { deviceId: parsed.data.id } : {}, - ...session?.userId == null ? {} : { userId: session.userId }, - osVersion: deviceOsVersion(), - } - } - - override async getPlatformSession(): Promise { - const lifetime = this.detailsLifetime - const stored = await this.readCurrentGrant(lifetime) - if (stored === null || lifetime.signal.aborted) return null - // Deployment headers only; the consuming client adds the identity of its own UI. - const requestHeaders = { ...this.accountRequestHeaders } - // Identity comes from the profile read for this same grant; an unknown ID requires disposable - // browser storage. A replaced credential never publishes the account its predecessor named. - return { origin: this.origin, token: stored.token, - userId: this.lastProfile?.token === stored.token ? this.lastProfile.profile.value.id || null : null, - ...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}), - requestHeaders } - } - - private async readCurrentGrant(lifetime: AbortController): Promise | null> { - if (this.closed) return null - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined || lifetime.signal.aborted) return null - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - // A private origin override must never forward a grant issued by another environment. - if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') - return parsed.data - } - - override async resolveToken(url: string): Promise { - if (this.closed || this.removing !== undefined) return undefined - const destination = new URL(url) - if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined - const record = await this.ctx.credentials.readRecord(KEY) - if (record === undefined) return undefined - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const result = grant.safeParse(record.payload) - if (!result.success) throw new PlatformAuthError('storage') - // Development grants cannot authenticate production model or file requests. - const issuer = new URL(result.data.issuer) - if (result.data.token.startsWith('dsh_mock_')) return undefined - if (this.inferenceOrigin === 'https://api.deepseek.com') { - if (['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname)) return undefined - } else if (issuer.origin !== this.origin) return undefined - return result.data.token - } - - override async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { - if (this.removing !== undefined) await this.removing - const origin = loginOrigin(callbackOrigin) - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== undefined && ['initializing', 'waiting-browser', 'exchanging', 'committing'].includes(this.attempt.view.phase)) { - return this.getState() - } - const previous = this.attempt - if (previous !== undefined) { - await previous.done - // Disposal can close the provider while the previous attempt settles. - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== previous) return this.getState() - } - const attempt: Attempt = { - origin, loginSource, - locale: platformWireLocale(client.locale), - clientHeaders: platformClientHeaders(this.platform, client), - view: { id: randomUUID() as SignInAttemptId, phase: 'initializing' }, - controller: new AbortController(), done: Promise.resolve(), running: Promise.resolve(), - } - this.attempt = attempt - attempt.done = this.ctx.authorization.begin({ - key: KEY, signal: attempt.controller.signal, - interaction: { notify: () => undefined, prompt: () => Promise.reject(new PlatformAuthError('protocol')) }, - }).then((outcome) => { - this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' }) - if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) { - attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end() - } else attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() - }).catch((error: unknown) => { - const code = error instanceof PlatformAuthError ? error.code : 'protocol' - console.error('[deepseek-account] sign-in failed', { errorCode: code }) - this.update(attempt, { phase: code === 'expired' ? 'expired' : 'failed', errorCode: code }) - this.finishFailedCallback(attempt) - }).then(async () => { - // begin() may report cancellation before the HTTP work observes its signal. - await attempt.running.catch(() => undefined) - if (attempt.callback !== undefined) { - await streamPromises.finished(attempt.callback, { cleanup: true }).catch(() => undefined) - } - await attempt.disposeCallback?.() - }) - this.changed() - return this.getState() - } - - override async cancelSignIn(id: SignInAttemptId): Promise { - const attempt = this.attempt - if (attempt?.view.id === id) { - if (attempt.view.phase !== 'committing') { - attempt.controller.abort() - this.ctx.authorization.cancel(KEY) - } - await attempt.done - } - return this.getState() - } - - override signOut(client: AccountClientMetadata): Promise { - this.removing ??= (async () => { - if (this.closed) throw new PlatformAuthError('protocol') - if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) - const record = await this.ctx.credentials.readRecord(KEY) - if (record !== undefined) { - if (record.kind !== 'grant') throw new PlatformAuthError('storage') - const parsed = grant.safeParse(record.payload) - if (!parsed.success) throw new PlatformAuthError('storage') - if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') - await this.ctx.credentials.deleteRecord(KEY) - this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) - } - this.attempt = undefined - this.ctx.emit('deepseek-account/signed-out') - this.changed() - return this.getState() - })().finally(() => { this.removing = undefined }) - return this.removing - } - - override async *watch(signal: AbortSignal, includeIdentityChanges = false): AsyncIterable { - let dirty = true - let wake: (() => void) | undefined - const wakeUp = (): void => { dirty = true; wake?.() } - const changed = (identityOnly: boolean): void => { if (!identityOnly || includeIdentityChanges) wakeUp() } - this.listeners.add(changed) - signal.addEventListener('abort', wakeUp, { once: true }) - try { - while (!this.closed && !signal.aborted) { - if (dirty) { dirty = false; yield await this.getState(); continue } - await new Promise((resolve) => { wake = resolve }) - } - } finally { - this.listeners.delete(changed) - signal.removeEventListener('abort', wakeUp) - } - } - - private revoke(token: string, headers: Record): void { - if (this.closed) return - const revocation = revokeAccount(this.origin, token, this.logoutPolicy, - this.logoutLifetime.signal, { ...this.requestHeaders, ...headers }).finally(() => { this.revocations.delete(revocation) }) - this.revocations.add(revocation) - } - - private invalidateDetails(): void { - this.lastProfile = undefined - this.detailsLifetime.abort() - this.detailsLifetime = new AbortController() - } - - private changed(identityOnly = false): void { for (const listener of this.listeners) listener(identityOnly) } - - private update(attempt: Attempt, value: Partial): void { - const { authorizeUrl: _url, ...rest } = attempt.view - attempt.view = { ...rest, ...value } - this.changed() - } - - private async run(session: AuthorizationSession, attempt: Attempt): Promise { - const webServer = this.ctx.get('webServer') - if (webServer === undefined) throw new PlatformAuthError('protocol') - const verifier = randomBytes(32).toString('base64url') - const state = randomBytes(32).toString('base64url') - const challenge = createHash('sha256').update(verifier).digest('base64url') - let authorizeId: string | undefined - const code = Promise.withResolvers() - // Callback requests may precede initialization settlement; the rejection is observed immediately. - void code.promise.catch(() => undefined) - const deadline = new AbortController() - let expiresAt = Date.now() + this.attemptTimeout - const signal = AbortSignal.any([session.signal, deadline.signal]) - let timer = setTimeout(() =>{ deadline.abort() }, this.attemptTimeout) - const abort = (): void => { code.reject(new PlatformAuthError('expired')) } - signal.addEventListener('abort', abort, { once: true }) - try { - attempt.disposeCallback = this.ctx.effect(() => webServer.register({ - kind: 'exact', path: '/oauth/callback', handler: (req, res) => { - let url: URL - try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } - catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } - const receivedCode = url.searchParams.get('code') - const receivedState = url.searchParams.get('state') ?? '' - const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) - && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) - if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || !validState || !receivedCode - || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { - res.writeHead(400, { 'cache-control': 'no-store' }).end(); return - } - if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { - res.writeHead(410, { 'cache-control': 'no-store' }).end(); return - } - attempt.callback = res - code.resolve(receivedCode) - }, - }), 'account: browser callback') - signal.throwIfAborted() - const redirectUri = `${attempt.origin}/oauth/callback` - const init = initialization.safeParse(await this.request('auth_init', { - code_challenge: challenge, code_challenge_method: 'S256', state, redirect_uri: redirectUri, locale: attempt.locale, - login_source: attempt.loginSource, - }, signal, attempt.clientHeaders), { reportInput: true }) - if (!init.success) this.rejectPayload('auth_init', init.error) - const authorizeUrl = browserUrl(init.data.authorize_url, this.origin, '/dsh/authorize', this.rewriteBrowserOrigin) - authorizeId = init.data.authorize_id - signal.throwIfAborted() - const now = Date.now() - expiresAt = Math.min(expiresAt, now + init.data.expires_in * 1000) - const remaining = expiresAt - now - if (remaining <= 0) { deadline.abort(); signal.throwIfAborted() } - clearTimeout(timer) - timer = setTimeout(() =>{ deadline.abort() }, remaining) - this.update(attempt, { phase: 'waiting-browser', authorizeUrl, expiresAt }) - const receivedCode = await code.promise - signal.throwIfAborted() - this.update(attempt, { phase: 'exchanging' }) - const deviceRecord = await this.ctx.credentials.modifyRecord(DEVICE, current => Promise.resolve(current === undefined - ? { kind: 'grant', payload: { id: randomUUID() } } : undefined)) - if (deviceRecord?.kind !== 'grant') throw new PlatformAuthError('storage') - const identity = device.parse(deviceRecord.payload) - const result = exchange.safeParse(await this.request('auth_exchange', { - code: receivedCode, code_verifier: verifier, redirect_uri: redirectUri, - device_id: identity.id, device_model: `${platform()}-${arch()}`, os_version: deviceOsVersion(), - }, signal, attempt.clientHeaders), { reportInput: true }) - if (!result.success) this.rejectPayload('auth_exchange', result.error) - const completionUrl = new URL(browserUrl(result.data.authorized_url, this.origin, '/dsh/authorized', this.rewriteBrowserOrigin)) - completionUrl.searchParams.set('login_source', attempt.loginSource) - attempt.completionUrl = completionUrl.href - if (Date.now() >= expiresAt) deadline.abort() - signal.throwIfAborted() - if (result.data.user != null) { - try { attempt.initialProfile = { token: result.data.token, value: { status: 'ready', value: profile(result.data.user) } } } - catch { - // Invalid optional user data falls back to current without discarding a valid authorization. - } - } - this.update(attempt, { phase: 'committing' }) - clearTimeout(timer) - try { await session.commit({ kind: 'grant', payload: { version: 1, token: result.data.token, issuer: this.origin } }) } - catch { throw new PlatformAuthError('storage') } - } catch (error) { - if (deadline.signal.aborted) throw new PlatformAuthError('expired') - throw error - } finally { - if (signal.aborted && authorizeId !== undefined) this.cancelRequest(authorizeId, verifier, attempt.clientHeaders) - clearTimeout(timer) - signal.removeEventListener('abort', abort) - // begin() settles the browser response and removes only this attempt’s route. - } - } - - private rejectPayload(stage: string, error: z.ZodError): never { - console.error('[deepseek-account] payload rejected', { - stage, issues: error.issues.map(issue => ({ - path: issue.path, code: issue.code, - receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input, - })), - }) - throw new PlatformAuthError('protocol') - } - - private cancelRequest(authorizeId: string, verifier: string, headers: Record): void { - if (this.closed) return - const cancellation = this.request('auth_cancel', { authorize_id: authorizeId, code_verifier: verifier }, - this.logoutLifetime.signal, headers).then(() => undefined, () => { - // Remote cancellation failures never reverse local cancellation or expose verifier diagnostics. - }).finally(() => { this.revocations.delete(cancellation) }) - this.revocations.add(cancellation) - } - - private request(method: string, body: unknown, signal: AbortSignal, headers: Record): Promise { - return requestPlatform(this.origin, method, body, - AbortSignal.any([signal, AbortSignal.timeout(this.requestTimeout)]), { ...this.requestHeaders, ...headers }) - } - - private finishFailedCallback(attempt: Attempt): void { - if (attempt.loginSource === 'web') { - const nonce = randomBytes(16).toString('base64url') - const message = attempt.locale === 'zh_CN' ? '登录失败,请关闭此标签页并在原页面重试。' - : 'Sign-in failed. Close this tab and try again in the original tab.' - attempt.callback?.writeHead(200, { - 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', - 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'`, - 'referrer-policy': 'no-referrer', - }).end(`${message}` - + `

${message}

`) - } else { - // Native account subscribers focus the login window; retain the browser’s Platform document. - attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() - } - } -} -export default PlatformAccount - -/** OS identification shared by login and credential-free identity reads. */ -function deviceOsVersion(): string { - return `${platform()} ${release()}` -} diff --git a/packages/credentials/deepseek-account-platform/src/types.ts b/packages/credentials/deepseek-account-platform/src/types.ts deleted file mode 100644 index ed3d43d0f8..0000000000 --- a/packages/credentials/deepseek-account-platform/src/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** Platform provider reuses the account service's client-safe state. */ -export type { AccountView, SignInAttemptView } from '@deepseek-ai/dsh-deepseek-account/types' diff --git a/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts b/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts deleted file mode 100644 index 959af7bc3f..0000000000 --- a/packages/credentials/deepseek-account-platform/tests/bonus.spec.ts +++ /dev/null @@ -1,419 +0,0 @@ -/** Bonus notification reads and acknowledgements over the real Host HTTP path. */ -import { afterEach, expect, it, vi } from 'vitest' -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' -import { Context } from '@deepseek-ai/cordis' -import AuthorizationService from '@deepseek-ai/dsh-authorization' -import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' -import { credentialKey } from '@deepseek-ai/dsh-credentials' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountUserId, AccountView } from '@deepseek-ai/dsh-deepseek-account' -import { PlatformAccount } from '../src/index.ts' - -const cleanups: Array<() => Promise> = [] -afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) - -const ORDER = '4c1b0000-0000-4000-8000-000000000000' -const SECOND_ORDER = '5d2c0000-0000-4000-8000-000000000000' -const USER = 'test-user' - -/** Client identity supplied with each account operation; only the locale's primary subtag selects the wire locale. */ -const clientMetadata = (locale = 'en-US'): AccountClientMetadata => ({ version: '1.2.3', locale, timezoneOffsetSeconds: 28_800 }) - -interface Recorded { - readonly method: string | undefined - readonly url: string | undefined - readonly token: string | undefined - readonly locale: string | undefined - readonly bundleId: string | undefined - readonly platform: string | undefined - readonly version: string | undefined - readonly timezoneOffset: string | undefined - readonly contentType: string | undefined - readonly body: string | undefined -} - -/** Read one request body; the acknowledgement carries its order id in JSON, so the fixture keeps the exact bytes. */ -function requestBody(req: IncomingMessage): Promise { - return new Promise((resolve, reject) => { - let body = '' - req.setEncoding('utf8') - req.on('data', (chunk: string) => { body += chunk }) - req.on('error', reject) - req.on('end', () => { resolve(body) }) - }) -} - -async function fixture() { - const home = await mkdtemp(join(tmpdir(), 'dsh-bonus-')) - cleanups.push(() => rm(home, { recursive: true, force: true })) - const requests: Recorded[] = [] - let profileId: string | null = USER - let profileBizCode = 0 - let profileStatus = 200 - let bonusBizCode = 0 - let bonusStatus = 200 - let bonuses: unknown = [ - { order_id: ORDER, campaign: 'dsh_login_bonus', amount: '5.00', currency: 'CNY', - granted_at: '2026-09-21T12:00:00Z', expires_at: '2026-10-21T12:00:00Z', msg: '已赠送您 5.00 元 DSH 体验赠金。' }, - { order_id: SECOND_ORDER, campaign: 'dsh_login_bonus', amount: '1.50', currency: 'CNY', - granted_at: '2026-09-20T12:00:00Z', expires_at: '2026-10-20T12:00:00Z', msg: '已赠送您 1.50 元 DSH 体验赠金。' }, - ] - let ackBizCode = 0 - let ackStatus = 200 - let beforeProfileResponse: (() => Promise) | undefined - let origin = '' - const handle = async (req: IncomingMessage, res: ServerResponse): Promise => { - expect(req.headers.authorization).toBeUndefined() - const body = await requestBody(req) - requests.push({ method: req.method, url: req.url, token: req.headers['x-dsh-auth-token'] as string | undefined, - locale: req.headers['x-client-locale'] as string | undefined, - bundleId: req.headers['x-client-bundle-id'] as string | undefined, - platform: req.headers['x-client-platform'] as string | undefined, - version: req.headers['x-client-version'] as string | undefined, - timezoneOffset: req.headers['x-client-timezone-offset'] as string | undefined, - contentType: req.headers['content-type'], body: body === '' ? undefined : body }) - res.setHeader('content-type', 'application/json') - if (req.url === '/auth-api/v0/users/current') { - await beforeProfileResponse?.() - res.writeHead(profileStatus).end(JSON.stringify({ code: profileStatus === 200 ? 0 : 1, data: { biz_code: profileBizCode, - biz_data: { id: profileId, email: 't***@example.invalid', id_profile: { name: 'Test', picture: null } } } })) - return - } - if (req.url === '/api/v0/users/get_unnotified_bonuses') { - res.writeHead(bonusStatus).end(JSON.stringify({ code: bonusStatus === 200 ? 0 : 1, - data: { biz_code: bonusBizCode, biz_data: bonuses } })) - return - } - // The exact path is the assertion: a query parameter would fall through to the 404 below. - if (req.url === '/api/v0/users/ack_bonus_notified') { - res.writeHead(ackStatus).end(JSON.stringify(ackStatus === 200 - ? { code: 0, msg: '', data: { biz_code: ackBizCode, biz_msg: ackBizCode === 0 ? '' : 'BONUS_ORDER_NOT_FOUND', biz_data: null } } - : { code: 1, msg: 'INTERNAL', data: null })) - return - } - res.writeHead(404).end('{}') - } - const server = createServer((req, res) => { void handle(req, res).catch(() => { res.writeHead(500).end('{}') }) }) - await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') throw new Error('missing listener') - origin = `http://127.0.0.1:${address.port}` - cleanups.push(async () => { - await new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }) - }) - const ctx = new Context() - const credentials = ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) - await credentials - const authorization = ctx.plugin(AuthorizationService) - await authorization - // The composed client identity is this fixture's choice; `null` is the web profile's documented setting. - const provider = ctx.plugin(PlatformAccount, { - platformOrigin: origin, allowLoopbackHttp: true, requestTimeoutMs: 5_000, desktopPlatform: null, - }) - await provider - cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose() }) - const key = credentialKey('deepseek-account-platform', 'default') - return { - account: ctx.deepseekAccount, ctx, requests, key, - grant: (token: string) => ctx.credentials.modifyRecord(key, () => Promise.resolve({ - kind: 'grant', payload: { version: 1, token, issuer: origin }, - })), - signOut: () => ctx.credentials.deleteRecord(key), - profileId: (value: string | null) => { profileId = value }, - failProfile: (bizCode = 17, status = 200) => { profileBizCode = bizCode; profileStatus = status }, - bonuses: (value: unknown) => { bonuses = value }, - failBonuses: (bizCode = 17, status = 200) => { bonusBizCode = bizCode; bonusStatus = status }, - failAck: (bizCode = 0, status = 200) => { ackBizCode = bizCode; ackStatus = status }, - onProfile: (hook: () => Promise) => { beforeProfileResponse = hook }, - } -} - -it('reads the identity once, then sends one call\'s client identity headers on both bonus requests', async () => { - const f = await fixture() - await f.grant('test-account-token') - const client = { version: '3.0.0', locale: 'zh-TW', timezoneOffsetSeconds: -18_000 } - await f.account.getUnnotifiedBonuses(client) - await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, client) - expect(f.requests.map(request => [ - request.url, request.bundleId, request.platform, request.version, request.locale, request.timezoneOffset, - ])).toEqual([ - ['/auth-api/v0/users/current', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ['/api/v0/users/get_unnotified_bonuses', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ['/api/v0/users/ack_bonus_notified', '', 'web', '3.0.0', 'zh_CN', '-18000'], - ]) -}) - -it('queries the account identity once even across repeated reads and acknowledgements', async () => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')) - expect(f.requests.filter(request => request.url === '/auth-api/v0/users/current')).toHaveLength(1) -}) - -it('does not reuse a cached identity from another grant', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - await f.grant('rotated-token') - await f.account.getUnnotifiedBonuses(clientMetadata('en')) - expect(f.requests.map(request => [request.url, request.token])).toEqual([ - ['/auth-api/v0/users/current', 'test-account-token'], - ['/auth-api/v0/users/current', 'rotated-token'], - ['/api/v0/users/get_unnotified_bonuses', 'rotated-token'], - ]) -}) - -it('publishes the identity a bonus read resolved, so the session can scope account storage', async () => { - const f = await fixture() - await f.grant('test-account-token') - const lifetime = new AbortController() - const states: AccountView[] = [] - const watching = (async () => { for await (const state of f.account.watch(lifetime.signal, true)) states.push(state) })() - try { - await expect.poll(() => states.length).toBe(1) - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toMatchObject({ accountId: USER }) - // The bonus read names the account, so identity consumers re-read the session snapshot. - await expect.poll(() => states.length).toBe(2) - expect(await f.account.getPlatformSession()).toMatchObject({ userId: USER, token: 'test-account-token' }) - } finally { - lifetime.abort() - await watching - } -}) - -it('reads unnotified bonuses with the platform origin, grant header, and locale header', async () => { - const f = await fixture() - await f.grant('test-account-token') - const batch = await f.account.getUnnotifiedBonuses(clientMetadata('zh-CN')) - expect(batch).toEqual({ - accountId: USER as AccountUserId, - bonuses: [ - { orderId: ORDER as AccountBonusOrderId, campaign: 'dsh_login_bonus', amount: '5.00', currency: 'CNY', - grantedAt: '2026-09-21T12:00:00Z', expiresAt: '2026-10-21T12:00:00Z', message: '已赠送您 5.00 元 DSH 体验赠金。' }, - { orderId: SECOND_ORDER as AccountBonusOrderId, campaign: 'dsh_login_bonus', amount: '1.50', currency: 'CNY', - grantedAt: '2026-09-20T12:00:00Z', expiresAt: '2026-10-20T12:00:00Z', message: '已赠送您 1.50 元 DSH 体验赠金。' }, - ], - }) - expect(f.requests).toEqual([ - { method: 'GET', url: '/auth-api/v0/users/current', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - { method: 'GET', url: '/api/v0/users/get_unnotified_bonuses', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - ]) -}) - -it.each([ - ['absent', {}, {}], - ['unvalidated', { campaign: null, amount: 'not-a-number', currency: 'EUR', granted_at: 42 }, - { campaign: null, amount: 'not-a-number', currency: 'EUR', grantedAt: 42 }], -])('accepts opaque order IDs with %s unused fields and acknowledges the same ID', async (_name, extra, expected) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([{ order_id: 'model-update-1', expires_at: '2099-01-01T00:00:00Z', title: 'Model news', msg: 'Model updated', ...extra }]) - const batch = await f.account.getUnnotifiedBonuses(clientMetadata('en')) - expect(batch?.bonuses).toEqual([ - { orderId: 'model-update-1', expiresAt: '2099-01-01T00:00:00Z', title: 'Model news', message: 'Model updated', ...expected }, - ]) - const notice = batch!.bonuses[0]! - expect(await f.account.ackBonusNotified(batch!.accountId, notice.orderId, clientMetadata('en'))).toBe(true) - expect(f.requests.at(-1)?.body).toBe(JSON.stringify({ order_id: 'model-update-1' })) -}) - -it.each([ - ['empty', { expires_at: '' }], - ['null', { expires_at: null }], - ['absent', {}], -])('accepts %s expiry as a notice that never expires', async (_name, expiry) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([{ order_id: 'notice', msg: 'News', ...expiry }]) - expect((await f.account.getUnnotifiedBonuses(clientMetadata('en')))?.bonuses).toEqual([ - { orderId: 'notice', expiresAt: '', message: 'News' }, - ]) -}) - -it.each([ - ['zh-CN', 'zh_CN'], - ['en-US', 'en_US'], -])('selects %s copy through the locale header and never a language query', async (locale, wireLocale) => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getUnnotifiedBonuses(clientMetadata(locale)) - expect(f.requests.map(request => request.locale)).toEqual([wireLocale, wireLocale]) - expect(f.requests.map(request => request.url)).toEqual([ - '/auth-api/v0/users/current', - '/api/v0/users/get_unnotified_bonuses', - ]) -}) - -it.each([ - ['a non-string title', [{ order_id: 'order', title: 42, expires_at: 'b', msg: 'm' }]], - ['a non-string order id', [{ order_id: 42, expires_at: 'b', msg: 'm' }]], - ['a non-string expiry', [{ order_id: 'order', expires_at: 42, msg: 'm' }]], - ['a missing message', [{ order_id: ORDER, campaign: 'c', amount: '5.00', currency: 'CNY', granted_at: 'a', expires_at: 'b' }]], - ['a payload that is not a list', { bonuses: [] }], -])('rejects a malformed unnotified payload: %s', async (_name, payload) => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses(payload) - await expect(f.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('acknowledges a displayed bonus with the grant, locale, and a JSON body', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('zh-CN'))).toBe(true) - expect(f.requests).toEqual([ - { method: 'GET', url: '/auth-api/v0/users/current', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, - { method: 'POST', url: '/api/v0/users/ack_bonus_notified', token: 'test-account-token', locale: 'zh_CN', - bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800', - contentType: 'application/json', body: `{"order_id":"${ORDER}"}` }, - ]) -}) - -it.each([ - ['the unnotified read', (f: Awaited>) => { - f.failBonuses(0, 401) - return f.account.getUnnotifiedBonuses(clientMetadata('en')) - }, null], - ['the acknowledgement', (f: Awaited>) => { - f.failAck(0, 401) - return f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')) - }, false], -])('expires the rejected grant when %s returns HTTP 401', async (_name, run, signedOutOutcome) => { - const f = await fixture() - await f.grant('test-account-token') - const expired = vi.fn() - f.ctx.on('deepseek-account/session-expired', expired) - // A rejected authenticated request names an invalid credential, so the provider drops it locally - // exactly as the profile and balance reads do; the caller sees its signed-out outcome. - expect(await run(f)).toBe(signedOutOutcome) - expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) - expect(expired).toHaveBeenCalledOnce() -}) - -it.each([ - ['read', (f: Awaited>) => f.account.getUnnotifiedBonuses(clientMetadata('en')), null], - ['acknowledgement', (f: Awaited>) => - f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en')), false], -])('ignores a bonus %s rejection whose response cleanup overlaps a credential replacement', async (_name, run, outcome) => { - const f = await fixture() - await f.grant('test-account-token') - await f.account.getProfile(clientMetadata()) - const response = new Response('', { status: 401 }) - const cancel = response.body!.cancel.bind(response.body) - // Credential changes can arrive while the response reader releases a rejected response body. - const cleanup = vi.spyOn(response.body!, 'cancel').mockImplementation(async () => { - await f.grant('replacement-token') - await cancel() - }) - const fetchResponse = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) - const expired = vi.fn() - f.ctx.on('deepseek-account/session-expired', expired) - try { - expect(await run(f)).toBe(outcome) - expect(cleanup).toHaveBeenCalledOnce() - expect(expired).not.toHaveBeenCalled() - expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) - expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) - } finally { cleanup.mockRestore(); fetchResponse.mockRestore() } -}) - -it('retains the grant when an acknowledgement returns HTTP 500', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(0, 500) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))) - .rejects.toThrow('account: network') - expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) -}) - -it('rejects the supplied BONUS_ORDER_NOT_FOUND envelope as a business failure', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(1) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))) - .rejects.toThrow('account: protocol') - expect(f.requests[1]).toMatchObject({ - method: 'POST', url: '/api/v0/users/ack_bonus_notified', locale: 'en_US', - contentType: 'application/json', body: `{"order_id":"${ORDER}"}`, - }) -}) - -it.each([ - ['a business failure', 1, 200, 'account: protocol'], - ['an HTTP failure', 0, 500, 'account: network'], -])('surfaces %s as a retryable acknowledgement failure', async (_name, bizCode, status, message) => { - const f = await fixture() - await f.grant('test-account-token') - f.failAck(bizCode, status) - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).rejects.toThrow(message) -}) - -it('does not acknowledge a notification from another account', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.ackBonusNotified('other-user' as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).toBe(false) - expect(f.requests.map(request => request.url)).toEqual(['/auth-api/v0/users/current']) -}) - -it('returns signed-out outcomes without any request', async () => { - const f = await fixture() - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toBeNull() - expect(await f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).toBe(false) - expect(f.requests).toEqual([]) -}) - -it('discards a read that a credential change invalidated before it published', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.onProfile(async () => { await f.grant('rotated-token') }) - expect(await f.account.getUnnotifiedBonuses(clientMetadata('en'))).toBeNull() - expect(f.requests.map(request => request.url)).toEqual(['/auth-api/v0/users/current']) -}) - -it('reports an unknown identity as retryable and an absent id as a protocol failure', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.failProfile() - await expect(f.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: network') - const absent = await fixture() - await absent.grant('test-account-token') - absent.profileId(null) - await expect(absent.account.getUnnotifiedBonuses(clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('reuses a cached identity for the same credential after a failed query', async () => { - const f = await fixture() - await f.grant('test-account-token') - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - f.failProfile() - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).resolves.toBe(true) -}) - -it('refuses a cached identity that carries no Platform id', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.profileId(null) - expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) - f.failProfile() - await expect(f.account.ackBonusNotified(USER as AccountUserId, ORDER as AccountBonusOrderId, clientMetadata('en'))).rejects.toThrow('account: protocol') -}) - -it('treats a null title as absent without rejecting other notifications', async () => { - const f = await fixture() - await f.grant('test-account-token') - f.bonuses([ - { order_id: 'untitled', title: null, msg: 'News' }, - { order_id: 'titled', title: 'Update', msg: 'Details' }, - ]) - expect((await f.account.getUnnotifiedBonuses(clientMetadata('en')))?.bonuses).toEqual([ - { orderId: 'untitled', expiresAt: '', message: 'News' }, - { orderId: 'titled', title: 'Update', expiresAt: '', message: 'Details' }, - ]) -}) diff --git a/packages/credentials/deepseek-account-platform/tsconfig.json b/packages/credentials/deepseek-account-platform/tsconfig.json deleted file mode 100644 index 63c81daaea..0000000000 --- a/packages/credentials/deepseek-account-platform/tsconfig.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "compilerOptions": { - "rootDir": "src", - "outDir": "lib/types" - }, - "include": [ - "src" - ], - "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, - { - "path": "../deepseek-account" - }, - { - "path": "../authorization" - }, - { - "path": "../credentials" - }, - { - "path": "../../../vendor/schemastery" - }, - { - "path": "../../host/webserver" - } - ] -} diff --git a/packages/credentials/deepseek-account/README.i18n.yaml b/packages/credentials/deepseek-account/README.i18n.yaml index 7ac8b46fac..7c8e7b9d6f 100644 --- a/packages/credentials/deepseek-account/README.i18n.yaml +++ b/packages/credentials/deepseek-account/README.i18n.yaml @@ -3,26 +3,26 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/credentials/deepseek-account/README.md /: - en: 30a2d1a634d60f4a - zh: 9fbf972d342f8ba2 + en: 9dbb9bc3960a11fe + zh: ed58987926489d3e /deepseek-ai-dsh-deepseek-account: - en: 4333ad7e5c2d257f - zh: 1f1acbb68131d328 + en: 78e86576b7f38038 + zh: 7ec9f58f21ce00bf /deepseek-ai-dsh-deepseek-account/summary: - en: 26e77d24d904dd48 - zh: abc2d141826091f9 + en: 28bcca957bf6abf4 + zh: 4a3fc8a59f2925bc /deepseek-ai-dsh-deepseek-account/table-of-contents: en: af856ba79fe31b8e zh: 15b7d1a5d1856de2 /deepseek-ai-dsh-deepseek-account/use-this-package: - en: d7825ac71d3acb22 - zh: 337bb5048aaade09 + en: a334962d65816a50 + zh: 28f66b089476123a /deepseek-ai-dsh-deepseek-account/understand-the-implementation: - en: ca361e6eb61faf02 - zh: d14923826e86293a + en: 76d2da2dab100ac3 + zh: 2c9404f27915daab /deepseek-ai-dsh-deepseek-account/further-exploration: - en: 5a57b4b331031f41 - zh: 8b72ac64ed244f58 + en: adda341390cbdb9b + zh: e564f30150373228 /deepseek-ai-dsh-deepseek-account/model-experience: en: ee1df7ca3467ee3f zh: 84904a5148da3862 @@ -30,8 +30,8 @@ en: ca3015e252db0114 zh: ebca9253cf15e8e9 /deepseek-ai-dsh-deepseek-account/known-limitations-and-deferred-work: - en: 0960f4968520bf50 - zh: 6a45253b706eceb0 + en: 1b26fcb10e139c27 + zh: c419d805bf62d62d /deepseek-ai-dsh-deepseek-account/known-limitations-and-deferred-work/dev-note: - en: 01eda6d8c3a86813 - zh: 9a4fd8c0571c33f4 + en: c6980daf81e68974 + zh: 58d58e6ad468f749 diff --git a/packages/credentials/deepseek-account/README.md b/packages/credentials/deepseek-account/README.md index 16cdf91af5..28e3b20afe 100644 --- a/packages/credentials/deepseek-account/README.md +++ b/packages/credentials/deepseek-account/README.md @@ -1,5 +1,5 @@ --- -description: "Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin." +description: "Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in." kind: "package-reference" --- @@ -7,23 +7,21 @@ kind: "package-reference" English | [中文](README.zh.md) -getPlatformSession returns a Host-only origin/token snapshot for native Platform embedding, or null when signed out. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile holds no ID. The snapshot reuses that ID without issuing a profile request, so an unknown ID leaves userId null instead of delaying the caller; a profile read whose stable ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, which lets identity consumers re-read the snapshot. Consumers key persistent browser preference storage by origin and userId and use temporary storage while userId is null. It is absent from account-controller RPC and Client state. Consumers destroy documents holding a snapshot when the account changes. The snapshot carries deployment request headers only; the embedding client composes the Platform client identity of its own UI. +Every operation that reaches Platform takes the caller's `AccountClientMetadata`: the client version, the active UI language, and the UTC offset in seconds. The service derives the five Platform client headers from that metadata and the composition's platform, so each request reports the UI that made it instead of the last caller the Host saw. A new sign-in attempt captures the metadata for its initialization, exchange, and cancellation, and a joining caller never replaces it; sign-out captures the metadata for the revocation retries that outlive the request. -`platformClientHeaders` builds the five Platform client headers for one call from its `AccountClientMetadata` and the composition's desktop platform: `x-client-bundle-id` is intentionally empty, `x-client-platform` is `web` unless the Desktop profile supplies `darwin` or `win32`, `x-client-version` is the calling build's version, `x-client-locale` reduces the active UI language to `zh_CN` or `en_US` through the exported `platformWireLocale`, and `x-client-timezone-offset` is whole seconds east of UTC. A consumer whose request body carries that same wire locale reuses `platformWireLocale` so the header and body cannot disagree. +getPlatformSession exports the stored grant only when its issuer matches platformOrigin. This Host-only operation supports native Platform embedding without widening the model/file origin configured for resolveToken. Its userId repeats the stable account ID from the most recent successful getProfile, and is null until one succeeds or when that profile carries no ID; the snapshot issues no profile request of its own, so a slow or failed profile request never delays it, and an unknown ID leaves userId null, which consumers treat as temporary-storage mode. A credential change during the grant read discards the snapshot. -getUnnotifiedBonuses returns the granted bonuses Platform has not yet recorded as displayed, together with the account they belong to; ackBonusNotified records one bonus the user actually saw. The acknowledgement names that account, so a notification read under one account is never confirmed for another. +`desktopPlatform` defaults to `null`, which sends `x-client-platform: web`; the Desktop profile supplies `darwin` or `win32`, becoming `desktop-mac` or `desktop-win`. The service owns all five headers, so deployment configuration cannot override them; `x-client-bundle-id` is intentionally empty, and `x-client-locale` reduces the caller's language to `zh_CN` or `en_US`. PlatformSession carries deployment headers only, and the embedding client composes the same five headers for the Platform documents and API requests it opens, only at the configured origin. -`rejectToken` accepts a Host inference request’s rejected token and removes only the matching current login; a late rejection cannot clear a replacement credential. - -`deepseek-account/session-expired` notifies current subscribers once after a rejected credential is removed. Account snapshots carry no expiry notice, so reconnecting does not repeat the toast. +Profile and balance HTTP 401 responses or top-level response code `40003` (invalid authorization) clear the rejected local grant and emit the live `deepseek-account/session-expired` notification. Concurrent responses share one removal; responses from an invalidated credential generation cannot clear its replacement. Other HTTP failures retain the grant. Host inference consumers can report a rejected request token through `rejectToken`; removal requires that it still matches the stored login. ## Summary -Account consumers read stored login state, start or cancel a browser login, and sign out without editing API keys. Host model consumers resolve account credentials only for the provider-configured inference origin. +Sign in through the system browser and keep the account credential in the existing local credential store. Local cancellation prevents late callbacks and exchange responses from signing the user in. -`SignInErrorCode` distinguishes `no-response` (fetch returned no Response) from HTTP and response-validation failures so clients can offer network troubleshooting. +Platform requests report `no-response` when fetch rejects before returning a Response, including request timeouts. HTTP errors and response-body failures do not use this code; authorization-attempt expiry retains `expired`. -`getDeviceIdentity()` returns existing device and account IDs plus the login OS version string, without credentials or device creation. +Device identity reads validate the existing login device record and expose only its ID, the current account ID, and the shared login OS version string. ## Table of Contents @@ -34,25 +32,62 @@ Account consumers read stored login state, start or cancel a browser login, and ## Use this package -`AccountProfile.avatarUrl` is an optional profile image URL; null or absence means no avatar. +The service exposes its client-safe operations through the `account` Remote namespace. The application loads its generated `./remote` contribution; no separate controller is needed. Login, profile, balance, notification, sign-out-impact, and expiry operations remain available through `ctx.remote.account`. Remote `watch` omits the Host-only identity subscription option. `resolveToken`, `rejectToken`, `getPlatformSession`, and `getDeviceIdentity` remain Host-only. -Successful local sign-out emits `deepseek-account/signed-out`. The platform provider installs the account-owned cancellation listener, which checks running Agents against `session.requestContext().provider` and cancels account tasks while retaining inboxes. The account controller uses the same predicate for its confirmation dialog. No additional Agent state is maintained. Before a new turn binds its first request, this predicate still sees the previous turn’s provider. +`DeepSeekAccount` is the concrete service owning login, credentials, and Remote operations. The `/types` entry exposes types without loading the service implementation. `watch` returns complete state tagged as `snapshot` or `credentials-changed`; Host-only `watch(signal, true)` also receives profile-identity changes, while Remote subscriptions omit that option. -The service defines account operations and reconnectable state snapshots. The platform provider owns the protocol and stored grant. Credentials are Host-only; the API controller exports state and commands without resolveToken. +The `/client-metadata` entry provides pure Platform header and cookie helpers for Host consumers. The configuration schema is `DeepSeekAccount.Config`; the plugin entry exports no helper functions. Mounting the service installs account-task cancellation. -Account model failures with `ACCOUNT_SIGN_IN_REQUIRED` emit `deepseek-account/model-sign-in-required`; the Client receives this live event for sign-in guidance. Other request errors do not emit it. +The `agents` service is optional. `hasRunningAccountTasks()` returns false when it is absent; when present, it checks running tasks for the account provider. + +The profile projection maps `id_profile.picture` to `avatarUrl`, using null when no picture is configured. + +Token resolution refuses requests while local sign-out is in progress. Successful local removal publishes `deepseek-account/signed-out` before returning the signed-out snapshot; remote revocation remains independent. + +getProfile / getBalance sends the stored grant in the x-dsh-auth-token header to GET /auth-api/v0/users/current and GET /api/v0/users/get_user_summary on platformOrigin. The grant issuer must match that origin. Host projects only the account UID, profile name, avatar URL, phone or email exactly as masked by Platform, and normal_wallets / bonus_wallets currency/balance strings; response tokens and other fields are discarded. A balance or bonus-amount string is accepted when it matches the numeric grammar Platform's Web client already passes to big.js, which allows an omitted integer or fraction part and a decimal exponent, so values such as 0E-16 and 5.0000000000000000 stay valid; the original string is retained and NaN, Infinity and malformed text are rejected. Bonus wallets remain separate from recharge balances. Credential changes and disposal invalidate in-flight queries. + +getNotifications reads `GET /api/v0/users/notifications/list`; getNotificationContent reads `GET /api/v0/users/notifications/content?id=`, including consumed notifications. The list also validates the required positive `next_poll_after` against browser timer limits and projects it as `nextPollAfterSeconds`. Both use x-client-locale. The list envelope requires a valid polling delay and notification array. Each notification is decoded separately; malformed fields or unsupported actions skip that notification with a diagnostic, preserving valid neighbors and server order. Skipped notifications are not shown or reported. A malformed single-content response still rejects, allowing the client to retain the current content. reportNotificationEvent posts `POST /api/v0/users/notifications/events` with notification_id and type displayed, cta_clicked, or dismissed. A valid acked response records the server decision without closing the local card. Each operation captures the current grant and its cancellation lifetime without a current-user preflight. Credential changes cancel the old lifetime and discard its late replies; token values remain Host-only. Other HTTP, business, and response-validation failures reject; HTTP 401 or response code 40003 invalidate only the current grant and return a signed-out result. + +Balance requests use balanceTimeoutMs (30,000ms by default); timeout returns a failed outcome without clearing the account or manufacturing a zero balance. Configure platformOrigin, allowLoopbackHttp, requestTimeoutMs, balanceTimeoutMs, and attemptTimeoutMs in the plugin row. HTTP is accepted only for explicitly enabled loopback development. The service registers /oauth/callback on the existing Host webServer before auth_init, validates state, exchanges an S256 PKCE code once, and commits a grant before redirecting to auth_exchange.biz_data.authorized_url. Browser destinations default to the configured platform origin and always require the fixed /dsh/authorize or /dsh/authorized path. The completion URL sets `login_source` to the initiating client (`web` or `desktop`) and preserves other Platform-supplied query parameters. Device identity is a separate random UUID record shared by processes using the same credential store; device_model reports OS and architecture. + +platformOrigin defaults to `https://platform.deepseek.com` for login, profile, balance, logout, external navigation, and native embedded pages. harnessOrigin defaults to `https://harness.deepseek.com` for notification list, content, and events only. Private deployments set harnessOrigin explicitly. Both accept HTTPS, or loopback HTTP when allowLoopbackHttp is enabled. Model and file token destinations use inferenceOrigin. + +`requestHeaders` adds Host-only headers to Platform and notification API requests. `accountRequestHeaders` overrides them for profile, balance, notifications, and native embedded pages; Cookie pairs merge by name. Header values are secret configuration and are excluded from account UI state. Authorization, X-DSH-Auth-Token, Host, Content-Type and connection/framing headers are reserved. Client identity headers override same-named deployment headers. Redirects fail without forwarding headers. Store deployment cookies in private configuration or environment variables; browser cookies are not collected automatically. + +A private patch can read environment variables through Cordis expressions: + +```yaml +- id: deepseek-account + config: + platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN + allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' + requestHeaders: !!js | + process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} +``` + +The authenticated client supplies its browser-accessible callback origin, including the local SSH forwarding port, and its UI kind. The service fixes the callback path and binds the resulting redirect_uri to both initialization and exchange. Callback requests use state and PKCE validation rather than RPC authentication. Completion, cancellation and disposal remove only the attempt route. Exchange failures publish failed state without retrying: Web closes its authorization tab and keeps the failure dialog in the original tab; the callback page attempts to close itself and offers a manual-close message. Desktop receives HTTP 204 and focuses its existing login UI through the account stream. + +Host diagnostics use `console.error` with the `[deepseek-account]` prefix on standard error and in the Host inspector Console, only for request, response-validation, or sign-in failures. Successful requests, caller cancellation, and normal account state changes are silent; request timeouts remain failures. Failure diagnostics include endpoint paths, HTTP status, numeric response codes, failure stages, invalid field paths, received types and validation codes, and browser URL rejection rules; headers, request and response bodies, authorization URLs, and raw exceptions are excluded. + +`rewriteBrowserOrigin` defaults to `false`, requiring same-origin browser URLs. A private development patch may set it to `true` to map authorization and completion URLs to `platformOrigin`, preserving their fixed paths and query strings. Source URLs must use HTTPS or already match the configured origin; user information, fragments and unexpected paths remain rejected. Shipped profiles retain strict same-origin validation. + +inferenceOrigin defaults to `https://api.deepseek.com`. A private deployment patch may replace it with one exact HTTP(S) origin, including its port, for inference and file authentication through x-dsh-auth-token. Paths, URL credentials, queries and fragments are invalid configuration. Alternate origins require a grant issued by the configured platformOrigin; mock tokens remain excluded. Loopback grants cannot authenticate the official production API. Deployment addresses belong in private patches, not shipped configuration. + +At service initialization, a valid stored grant whose issuer differs from platformOrigin is deleted locally before consumers read account state. Startup continues signed out without a remote logout request; API keys and device identity remain stored. Storage failures remain explicit, and account HTTP or response-validation failures do not delete a matching grant. ## Understand the implementation -The service defines account operations without maintaining a second credential index. The provider owns persistence and login lifecycle checks. +Account presence reads the credential store, and attempt state projects private state directly. Behavior tests verify asynchronous cancellation and commit ordering. ## Further Exploration The [credentials subsystem](../../../docs/subsystems/credentials.md) owns storage APIs; the [architecture](../../../docs/architecture.md) explains application composition. -A ready AccountDetails.balance keeps recharge wallets in value and bonus wallets in bonusWallets; both arrays preserve decimal strings and currency. Query failure supplies neither amount. +The attemptTimeoutMs limit includes initialization, browser waiting, and exchange. Initialization does not extend its absolute deadline; the server TTL may only shorten the remaining time. Credential persistence admitted before expiry completes without cancellation. + +Account updates share one ordered stream. A credential write takes priority over pending progress snapshots; a state read interrupted by a newer credential lifetime is discarded. ## Model Experience @@ -67,11 +102,17 @@ No model request prefix changes. -- Account tokens have no expiry or refresh flow. Sign-out removes the local grant before background provider revocation; remote logout failures never restore local login. Profile and balance query failures retain the stored grant. getProfile / getBalance reports profile and balance query outcomes independently. +- Browser sign-in requires the Host webServer. Only local access and SSH local forwarding through HTTP localhost, 127.0.0.1, or [::1] with an explicit port are supported; non-loopback reverse proxies are unsupported. Account tokens have no expiry or refresh flow; explicit DSH sign-out removes the local grant before calling POST /auth-api/v0/users/logout in the background. Remote failures never restore local login. The captured old token receives at most five additional attempts with exponential delays of 1, 2, 4, 8, and 16 seconds by default; logoutMaxRetries (0–5) and logoutRetryDelayMs configure that policy. Each request uses requestTimeoutMs. Provider shutdown aborts requests and waits, and pending revocations are not persisted. Local credential deletion failures remain visible to the caller. Authorization-attempt deadlines still apply before a token is issued. Cancellation or timeout after initialization sends one background POST /auth-api/v0/dsh/auth_cancel with the authorize_id from auth_init.biz_data and the original code_verifier, without account authorization. Local cancellation never waits for this request or reverses on failure; requestTimeoutMs bounds it, and provider shutdown aborts it. TODO(product-error-ui): Product must define localized copy and UI behavior for the supplied biz_code values. Until then, business failures use the existing generic retry message; other codes and HTTP errors use the same fallback. Development grants never authenticate production requests. ### Dev Note The [desktop login decision](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.md) records cancellation and storage ownership. -PlatformSession may carry Host-only requestHeaders from Host to Electron main: deployment headers only, because the embedded document's client identity is composed where its locale, timezone and version are known. Consumers must exclude those headers from renderer bootstrap and restrict them to the configured origin. userId is Host-only on the same terms and never enters renderer bootstrap. mergePlatformCookies preserves unrelated cookie pairs while replacing matching names. +The first profile read after sign-in uses the sanitized user returned by auth_exchange. A null or malformed user falls back to current; subsequent refreshes and Host restarts also query current. Failed current requests retain the latest successful profile for the same credential in Host memory; credential changes and disposal clear it. A ready current response whose stable account ID first becomes available or changes notifies only Host subscribers using `watch(signal, true)`, so identity consumers re-read getPlatformSession; refreshes that repeat the same ID stay silent. Exchange registers the submitted device information. + +accountRequestHeaders overlays requestHeaders for current, balance and embedded Platform page/API requests. Cookie pairs merge by name so routing overrides retain other deployment cookies. Authorization initialization, exchange, cancellation and logout keep requestHeaders. Both maps remain private to Host and Electron main; the session's userId stays Host-only too, and renderer bootstrap receives only origin and token. + +The account provider’s `embeddedPageDist` configuration adds a `dist` query parameter to embedded Usage and Top-up URLs. Its default is empty; private frontend branch selectors belong in the local profile patch. It does not change API URLs or credential delivery. + +Platform wallet balances accept decimal strings with optional scientific notation (including `0E-16`); the service preserves the original string for consumers. diff --git a/packages/credentials/deepseek-account/README.zh.md b/packages/credentials/deepseek-account/README.zh.md index 2ef0d01d89..628fd2ed61 100644 --- a/packages/credentials/deepseek-account/README.zh.md +++ b/packages/credentials/deepseek-account/README.zh.md @@ -1,5 +1,5 @@ --- -description: "账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。" +description: "通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。" kind: "package-reference" --- @@ -7,23 +7,21 @@ kind: "package-reference" [English](README.md) | 中文 -getPlatformSession 为原生 Platform 内嵌提供仅限 Host 的 origin/token 快照,退登时返回 null。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照复用该 ID,不自行发起资料请求,因此 ID 未知时只会让 userId 为 null,而不会延迟调用方;资料读取首次取得稳定 ID 或该 ID 变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取快照。使用方以 origin 和 userId 作为持久化浏览器偏好存储的键,userId 为 null 时改用临时存储。账号控制器 RPC 和 Client 状态不包含此方法及快照。账号变化时,使用方销毁持有旧快照的文档。快照只携带部署请求头;Platform 客户端身份由发起请求的内嵌客户端自行组装。 +每个到达 Platform 的操作都接收调用方的 `AccountClientMetadata`:客户端版本、当前界面语言和以秒为单位的 UTC 偏移。服务据此与组合出的平台推导五个 Platform 客户端请求头,因此每个请求报告的是发起它的界面,而不是 Host 上一次见到的调用方。新的登录申请会为该申请的初始化、兑换和取消捕获这份元数据,中途加入的调用方不会替换它;退登则为在请求之后继续进行的撤销重试捕获这份元数据。 -`platformClientHeaders` 依据单次调用的 `AccountClientMetadata` 与组合出的桌面平台生成五个 Platform 客户端请求头:`x-client-bundle-id` 有意保持为空字符串,`x-client-platform` 在没有 Desktop profile 提供 `darwin` 或 `win32` 时为 `web`,`x-client-version` 为调用方构建的版本,`x-client-locale` 通过导出的 `platformWireLocale` 将当前界面语言归约为 `zh_CN` 或 `en_US`,`x-client-timezone-offset` 为东为正的整秒偏移。请求正文需要同一个线上语言值时,消费方复用 `platformWireLocale`,使请求头与正文不会不一致。 +getPlatformSession 仅在已存授权的 issuer 与 platformOrigin 一致时导出该授权。这个仅限 Host 的操作支持原生 Platform 内嵌,不扩大 resolveToken 配置的模型及文件请求来源。其 userId 复制最近一次成功 getProfile 得到的稳定账号 ID;尚无一次成功读取或资料不含 ID 时为 null。快照不自行发起资料请求,因此资料请求缓慢或失败都不会延迟它;ID 未知时 userId 为 null,使用方将其视为临时存储模式。读取授权期间凭证变化时丢弃快照。 -getUnnotifiedBonuses 返回平台尚未记录为已展示的赠金及其所属账号;ackBonusNotified 记录用户实际看到的那一笔赠金。确认请求携带该账号,因此在一个账号下读取的通知绝不会被确认到另一个账号。 +`desktopPlatform` 默认为 `null`,此时携带 `x-client-platform: web`;Desktop profile 提供 `darwin` 或 `win32`,改为 `desktop-mac` 或 `desktop-win`。五个请求头均由 provider 拥有,部署配置无法覆盖;`x-client-bundle-id` 有意保持为空,`x-client-locale` 将调用方语言归约为 `zh_CN` 或 `en_US`。PlatformSession 只携带部署请求头,内嵌客户端为自行打开的 Platform 文档和 API 请求组装同样的五个请求头,且仅在配置来源发送。 -`rejectToken` 接收 Host 推理请求被拒绝的 token,仅删除与它匹配的当前登录凭据;延迟返回的拒绝不能清除替换后的凭据。 - -`deepseek-account/session-expired` 在移除被拒绝的凭据后,向当前订阅方通知一次。账号快照不携带失效提示,因此重新连接不会重复弹出 toast。 +资料和余额接口返回 HTTP 401 或顶层响应码 `40003`(鉴权失效)时清除被拒绝的本地凭据,并发送实时 `deepseek-account/session-expired` 通知。并发响应共用一次清除操作;已失效凭据代次的响应不能清除替换后的凭据。其他 HTTP 错误保留凭据。Host 推理调用方可以通过 `rejectToken` 报告被拒绝的请求 token;仅当它仍匹配当前登录凭据时才执行清除。 ## 概述 -账号使用方可读取本地登录状态、发起或取消浏览器登录,并在保留 API Key 的情况下退出。Host 模型使用方仅能为提供者配置的推理来源解析账号凭证。 +通过系统浏览器登录,并将账号凭证保存在现有本地凭证存储中。本地取消会阻止迟到的回调和兑换响应使用户登录。 -`SignInErrorCode` 将 `no-response`(fetch 未返回 Response)与 HTTP 和响应校验失败区分开,使客户端可以提示检查网络。 +当 fetch 在返回 Response 前拒绝(包括单次请求超时)时,Platform 请求报告 `no-response`。HTTP 错误和响应体失败不使用此代码;授权尝试到期仍使用 `expired`。 -`getDeviceIdentity()` 返回已有设备和账户 ID 以及登录使用的操作系统版本字符串,不返回凭据,也不创建设备标识。 +设备身份读取会校验已有登录设备记录,仅提供设备 ID、当前账户 ID 和与登录共用的操作系统版本字符串。 ## 目录 @@ -34,25 +32,62 @@ getUnnotifiedBonuses 返回平台尚未记录为已展示的赠金及其所属 ## 使用此包 -本地成功退出登录后发出 `deepseek-account/signed-out`。Platform 提供方安装账号模块的取消监听器,根据运行中 Agent 的 `session.requestContext().provider` 判断账号任务,取消时保留收件箱。账号控制器的确认弹窗复用同一判断,不维护额外 Agent 状态。新轮次绑定首请求前,该判断仍读取上一轮的提供方。 +服务通过 `account` Remote 命名空间暴露可供客户端使用的操作。应用加载其生成的 `./remote` 贡献,无需单独的 controller。登录、资料、余额、通知、退出影响检查和凭据过期操作均通过 `ctx.remote.account` 调用。Remote `watch` 不接受仅供 Host 使用的身份订阅选项。`resolveToken`、`rejectToken`、`getPlatformSession` 和 `getDeviceIdentity` 仍仅供 Host 使用。 -`AccountProfile.avatarUrl` 是可选的账号头像 URL;为空或缺失时表示没有头像。 +`DeepSeekAccount` 是具体服务,拥有登录、凭证和 Remote 操作。`/types` 提供不加载服务实现的类型出口。`watch` 返回完整状态与 `snapshot` 或 `credentials-changed` 类型;仅 Host 的 `watch(signal, true)` 还接收资料身份变化,Remote 订阅不启用该选项。 -该服务定义账号操作和可重连的状态快照。平台提供者负责协议和授权记录。凭证仅限 Host;API 控制器只导出状态与操作,不导出 resolveToken。 +`/client-metadata` 为 Host 使用方提供纯函数形式的 Platform 请求头和 Cookie 辅助函数。配置 schema 为 `DeepSeekAccount.Config`;插件入口不导出辅助函数。挂载服务时会安装账号任务取消逻辑。 -账号模型请求以 `ACCOUNT_SIGN_IN_REQUIRED` 失败时,发出 `deepseek-account/model-sign-in-required`,Client 接收该实时事件以提示登录。其他请求错误不触发此事件。 +`agents` 服务为可选依赖。未提供时,`hasRunningAccountTasks()` 返回 false;提供时,检查使用账号服务的运行中任务。 + +账号资料投影将 `id_profile.picture` 映射为 `avatarUrl`,没有配置头像时返回 null。 + +本地退出登录期间拒绝解析 token。本地授权成功删除后,先发布 `deepseek-account/signed-out`,再返回已退出的状态快照;远程撤销独立执行。 + +getProfile / getBalance 将保存的授权 token 通过 x-dsh-auth-token 请求头,向 platformOrigin 上的 GET /auth-api/v0/users/current 和 GET /api/v0/users/get_user_summary 发起请求。授权签发来源必须与该来源一致。Host 只投影账号 UID、资料名称、头像 URL、由 Platform 脱敏的手机号或邮箱(原样保留),以及 normal_wallets / bonus_wallets 的币种和余额字符串,丢弃响应 token 与其他字段。余额和赠金金额字符串只要符合 Platform Web 客户端交给 big.js 的数字文法即可通过,该文法和 big.js 一致,允许省略整数或小数部分以及十进制指数,因此 0E-16、5.0000000000000000 这类值仍然有效;原始字符串会保留,NaN、Infinity 和非法文本仍被拒绝。赠送钱包不计入充值余额。凭证变化和销毁会使进行中的查询失效。 + +getNotifications 读取 `GET /api/v0/users/notifications/list`;getNotificationContent 读取 `GET /api/v0/users/notifications/content?id=`,支持已消费通知。列表还会校验必填的正数 `next_poll_after` 不超出浏览器计时范围,并投影为 `nextPollAfterSeconds`。二者都通过 x-client-locale 指定语言。列表外层要求有效的轮询间隔和通知数组。每条通知单独解码;字段格式错误或操作不受支持时,记录诊断并跳过该条,保留其他有效通知及服务端顺序。被跳过的通知不会展示或上报。单条内容响应格式错误时仍拒绝请求,让客户端保留当前内容。reportNotificationEvent 向 `POST /api/v0/users/notifications/events` 发送 notification_id 和 type displayed、cta_clicked 或 dismissed。有效的 acked 响应表示服务端消费决策,不会关闭本地卡片。每项操作都捕获当前授权和取消生命周期,不前置查询当前用户;凭据变化会取消旧生命周期并丢弃迟到的响应,token 始终只留在 Host。其他 HTTP、业务和响应校验失败均拒绝;HTTP 401 或响应码 40003 仅使当前授权失效,并返回未登录结果。 + +余额请求使用 balanceTimeoutMs(默认 30,000ms);超时返回失败结果,不清除账号,也不制造零余额。在插件行配置 platformOrigin、allowLoopbackHttp、requestTimeoutMs、balanceTimeoutMs 和 attemptTimeoutMs。HTTP 仅用于显式启用的本机开发。服务先在现有 Host webServer 注册 /oauth/callback,再调用 auth_init;校验 state、使用 S256 PKCE 授权码兑换一次,并在跳转 auth_exchange.biz_data.authorized_url 前提交授权记录。浏览器地址默认要求匹配配置的平台来源,并始终要求固定的 /dsh/authorize 或 /dsh/authorized 路径。完成页地址将 `login_source` 设为发起登录的客户端类型(`web` 或 `desktop`),并保留平台返回的其他查询参数。设备标识是独立的随机 UUID 记录,由使用同一凭证存储的进程共享;device_model 报告操作系统和架构。 + +platformOrigin 默认为 `https://platform.deepseek.com`,用于登录、资料、余额、退出登录、外部导航和原生内嵌页面。harnessOrigin 默认为 `https://harness.deepseek.com`,仅用于通知 list、content 和 events 接口。私有部署需显式设置 harnessOrigin。二者均接受 HTTPS;启用 allowLoopbackHttp 后也接受回环 HTTP。模型和文件 token 目标使用 inferenceOrigin。 + +`requestHeaders` 为 Platform 和通知 API 请求添加仅 Host 使用的请求头。`accountRequestHeaders` 为资料、余额、通知和原生内嵌页面覆盖这些请求头;Cookie 按名称合并。请求头值属于敏感配置,不包含在账号 UI 状态中。Authorization、X-DSH-Auth-Token、Host、Content-Type 及连接和消息分帧请求头由服务保留。客户端身份请求头覆盖部署配置中的同名请求头。重定向会失败,不会转发请求头。开发环境 Cookie 应保存在私有配置或环境变量中;不会自动收集浏览器 Cookie。 + +私有 patch 也可通过 Cordis 表达式读取环境变量: + +```yaml +- id: deepseek-account + config: + platformOrigin: !!js process.env.DSH_PLATFORM_ORIGIN + allowLoopbackHttp: !!js process.env.DSH_PLATFORM_ALLOW_LOOPBACK_HTTP === '1' + requestHeaders: !!js | + process.env.DSH_PLATFORM_COOKIE ? { Cookie: process.env.DSH_PLATFORM_COOKIE } : {} +``` + +已鉴权客户端提供浏览器可访问的回调来源(含 SSH 本地转发端口)和 UI 类型。服务固定回调路径,并在初始化与兑换时使用同一个 redirect_uri。回调请求使用 state 和 PKCE 校验,不要求 RPC 鉴权。完成、取消和卸载仅移除本次尝试的路由。兑换失败发布 failed 状态,不自动重试:Web 关闭授权标签页,原标签页显示失败弹窗;回调页尝试自行关闭,并提供手动关闭提示。Desktop 收到 HTTP 204,并通过账号状态流聚焦现有登录界面。 + +Host 诊断仅在请求、响应校验或登录失败时,通过 `console.error` 写入标准错误及 Host 调试器 Console,前缀为 `[deepseek-account]`。成功请求、调用方主动取消和正常账号状态变化不输出日志;请求超时仍记录为失败。失败诊断包含接口路径、HTTP 状态、数值响应码、失败阶段、校验失败的字段路径、实际类型和校验码,以及浏览器 URL 拒绝规则,不包含请求头、请求和响应正文、授权 URL 或原始异常。 + +`rewriteBrowserOrigin` 默认为 `false`,要求浏览器地址同源。私有开发 patch 可设为 `true`,将授权页和完成页地址映射到 `platformOrigin`,保留固定路径和查询字符串。原地址必须使用 HTTPS 或已匹配配置来源;仍拒绝用户名密码、片段和非预期路径。发布的 profile 保持严格同源校验。 + +inferenceOrigin 默认为 `https://api.deepseek.com`。私有部署 patch 可将其替换为一个精确的 HTTP(S) 来源(含端口),让推理及文件请求通过 x-dsh-auth-token 认证。配置不得包含路径、URL 凭证、查询或片段。其他来源要求授权由配置的 platformOrigin 签发;仍拒绝 Mock token。本机授权不能认证官方生产 API。部署地址保存在私有 patch 中,不随默认配置发布。 + +服务初始化时,若有效的已存授权 issuer 与 platformOrigin 不同,会在使用方读取账号状态前删除该本地授权,以未登录态继续启动,不发送远端退登请求;API Key 和设备标识保留。存储错误仍明确报错,账号 HTTP 或响应校验失败不会删除来源匹配的授权。 ## 理解实现 -服务只定义账号操作,不维护第二份凭证索引。提供者负责持久化和登录生命周期检查。 +账号是否存在直接读取凭证存储,尝试状态直接投影私有状态。异步取消和提交由行为测试验证。 ## 深入探索 [凭证子系统](../../../docs/subsystems/credentials.zh.md)定义存储接口;[架构](../../../docs/architecture.zh.md)说明应用组合。 -AccountDetails.balance 就绪时,value 保存充值钱包,bonusWallets 保存赠送钱包;两个数组均保留十进制金额字符串和币种。查询失败不提供金额。 +attemptTimeoutMs 包含初始化、等待浏览器和兑换的耗时。初始化不会延长绝对截止时间;服务端 TTL 只能缩短剩余时间。在到期前已获准的凭证持久化不再取消。 + +账号更新共用一条有序流。凭据写入优先于待发送的进度快照;状态读取期间若凭据生命周期被替换,则丢弃该次读取。 ## 模型体验 @@ -67,11 +102,17 @@ AccountDetails.balance 就绪时,value 保存充值钱包,bonusWallets 保 -- 账号 token 没有过期或刷新流程。退出时先移除本地授权,再由提供者在后台撤销;远程退登失败不会恢复本地登录态。资料和余额查询失败保留已存储授权。getProfile / getBalance 分别报告资料和余额的查询结果。 +- 浏览器登录需要 Host webServer,仅支持通过带显式端口的 HTTP localhost、127.0.0.1 或 [::1] 本机访问及 SSH 本地转发,不支持非本机域名的反向代理。账号 token 没有过期或刷新流程;用户主动在 DSH 退出登录时,先删除本地授权,再在后台调用 POST /auth-api/v0/users/logout。远程失败不会恢复本地登录态。默认仅针对捕获的旧 token 最多额外重试五次,指数退避间隔为 1、2、4、8、16 秒;logoutMaxRetries(0–5)和 logoutRetryDelayMs 可配置该策略。每次请求使用 requestTimeoutMs。服务关闭时取消请求和等待,不持久化待撤销任务。本地凭证删除失败仍向调用者报错。签发 token 前的授权尝试仍有有效期。初始化后的取消或超时会在后台发送一次 POST /auth-api/v0/dsh/auth_cancel,携带 auth_init.biz_data 中的 authorize_id 和原始 code_verifier,不附带账号授权。本地取消不等待该请求,也不会因失败而恢复;requestTimeoutMs 限制请求时间,服务关闭时中止请求。TODO(product-error-ui):产品需定义已给定 biz code 的本地化文案和交互表现。在此之前,业务失败沿用现有“操作失败,请重试”兜底;其他 code 和 HTTP 错误也使用该兜底。开发授权不能认证生产请求。 ### 开发备注 [桌面登录决策](../../../.agents/notes/implemented/architecture/2026-09-14-deepseek-account-login.zh.md)记录取消和存储的职责。 -PlatformSession 可将仅限 Host 的 requestHeaders 从 Host 传至 Electron 主进程,其中只有部署请求头,因为内嵌文档的客户端身份在其语言、时区和版本可知处组装。消费者必须从渲染层 bootstrap 排除这些请求头,并将其限定于配置来源。userId 同样仅限 Host,绝不进入渲染层 bootstrap。mergePlatformCookies 替换同名 Cookie,同时保留其他 Cookie。 +登录后首次读取资料使用 auth_exchange 返回并经筛选的 user。user 为 null 或格式无效时回退到 current;后续刷新及 Host 重启也查询 current。current 请求失败时保留 Host 内存中同一凭证最近一次成功的资料;凭证变更或服务销毁时清空。current 成功返回的稳定账号 ID 首次可用或变化时仅通知使用 `watch(signal, true)` 的 Host 订阅者,供标识使用方重新读取 getPlatformSession;重复相同 ID 的刷新不通知。exchange 负责登记提交的设备信息。 + +accountRequestHeaders 覆盖 requestHeaders,供 current、余额以及内嵌 Platform 页面/API 请求使用。Cookie 按名称合并,路由覆盖保留其他部署 Cookie。授权初始化、兑换、取消和退登保持使用 requestHeaders。两组请求头仅供 Host 和 Electron 主进程使用;快照的 userId 同样仅限 Host,渲染层 bootstrap 仅接收 origin 和 token。 + +账号服务的 `embeddedPageDist` 配置为内嵌用量和充值页面 URL 添加 `dist` 查询参数。默认值为空;私有前端分支选择值应写在本地 profile patch 中。此配置不改变 API 地址或凭证传递方式。 + +Platform 钱包余额接受带可选科学计数法的十进制字符串(包括 `0E-16`),提供方保留原始字符串供调用方使用。 diff --git a/packages/credentials/deepseek-account-platform/locale/de.json b/packages/credentials/deepseek-account/locale/de.json similarity index 76% rename from packages/credentials/deepseek-account-platform/locale/de.json rename to packages/credentials/deepseek-account/locale/de.json index edd924d206..4fc42a20db 100644 --- a/packages/credentials/deepseek-account-platform/locale/de.json +++ b/packages/credentials/deepseek-account/locale/de.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek Kontoanmeldung", + "title": "DeepSeek-Konto", "description": "Schließen Sie die Anmeldeautorisierung für das DeepSeek-Konto über den Browser ab." } } diff --git a/packages/credentials/deepseek-account/locale/en.json b/packages/credentials/deepseek-account/locale/en.json new file mode 100644 index 0000000000..6a40638c62 --- /dev/null +++ b/packages/credentials/deepseek-account/locale/en.json @@ -0,0 +1,5 @@ +{ + "meta": { + "title": "DeepSeek account" + } +} diff --git a/packages/credentials/deepseek-account-platform/locale/es.json b/packages/credentials/deepseek-account/locale/es.json similarity index 71% rename from packages/credentials/deepseek-account-platform/locale/es.json rename to packages/credentials/deepseek-account/locale/es.json index e5ce28e7cd..18de04f7a0 100644 --- a/packages/credentials/deepseek-account-platform/locale/es.json +++ b/packages/credentials/deepseek-account/locale/es.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek inicio de sesión de cuenta", + "title": "Cuenta de DeepSeek", "description": "Complete la autorización de inicio de sesión de la cuenta DeepSeek a través del navegador." } } diff --git a/packages/credentials/deepseek-account-platform/locale/fr.json b/packages/credentials/deepseek-account/locale/fr.json similarity index 72% rename from packages/credentials/deepseek-account-platform/locale/fr.json rename to packages/credentials/deepseek-account/locale/fr.json index e472dc67ec..e443d00434 100644 --- a/packages/credentials/deepseek-account-platform/locale/fr.json +++ b/packages/credentials/deepseek-account/locale/fr.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek connexion au compte", + "title": "Compte DeepSeek", "description": "Complétez l'autorisation de connexion au compte DeepSeek via le navigateur." } } diff --git a/packages/credentials/deepseek-account-platform/locale/ja.json b/packages/credentials/deepseek-account/locale/ja.json similarity index 70% rename from packages/credentials/deepseek-account-platform/locale/ja.json rename to packages/credentials/deepseek-account/locale/ja.json index 1409b20137..e9ef24eaad 100644 --- a/packages/credentials/deepseek-account-platform/locale/ja.json +++ b/packages/credentials/deepseek-account/locale/ja.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek アカウントログイン", + "title": "DeepSeek アカウント", "description": "ブラウザで DeepSeek アカウントへのログイン認可を行います。" } } diff --git a/packages/credentials/deepseek-account-platform/locale/pt.json b/packages/credentials/deepseek-account/locale/pt.json similarity index 74% rename from packages/credentials/deepseek-account-platform/locale/pt.json rename to packages/credentials/deepseek-account/locale/pt.json index 2653ad2013..ed8f92bdd7 100644 --- a/packages/credentials/deepseek-account-platform/locale/pt.json +++ b/packages/credentials/deepseek-account/locale/pt.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek login da conta", + "title": "Conta DeepSeek", "description": "Conclua a autorização de login da conta DeepSeek através do navegador." } } diff --git a/packages/credentials/deepseek-account-platform/locale/ru.json b/packages/credentials/deepseek-account/locale/ru.json similarity index 75% rename from packages/credentials/deepseek-account-platform/locale/ru.json rename to packages/credentials/deepseek-account/locale/ru.json index 3d5fff9ff8..defd4481c6 100644 --- a/packages/credentials/deepseek-account-platform/locale/ru.json +++ b/packages/credentials/deepseek-account/locale/ru.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek вход в аккаунт", + "title": "Аккаунт DeepSeek", "description": "Завершите авторизацию входа в учетную запись DeepSeek через браузер." } } diff --git a/packages/credentials/deepseek-account-platform/locale/zh.json b/packages/credentials/deepseek-account/locale/zh.json similarity index 71% rename from packages/credentials/deepseek-account-platform/locale/zh.json rename to packages/credentials/deepseek-account/locale/zh.json index 86bbe95c12..65d9b31b58 100644 --- a/packages/credentials/deepseek-account-platform/locale/zh.json +++ b/packages/credentials/deepseek-account/locale/zh.json @@ -1,6 +1,6 @@ { "meta": { - "title": "DeepSeek 账号登录", + "title": "DeepSeek 账号", "description": "通过浏览器完成 DeepSeek 账号登录授权。" } } diff --git a/packages/credentials/deepseek-account/package.json b/packages/credentials/deepseek-account/package.json index 2a4d649a9f..088b4e8106 100644 --- a/packages/credentials/deepseek-account/package.json +++ b/packages/credentials/deepseek-account/package.json @@ -1,6 +1,6 @@ { "name": "@deepseek-ai/dsh-deepseek-account", - "description": "Read account state and resolve official API credentials", + "description": "Sign in to DeepSeek and manage account credentials and notifications", "version": "0.2.2-rc.1", "publishConfig": { "access": "public" @@ -22,15 +22,34 @@ "types": "./lib/types/types.d.ts", "default": "./lib/types/types.js" }, + "./client-metadata": { + "types": "./lib/types/client-metadata.d.ts", + "default": "./lib/types/client-metadata.js" + }, "./src/*": "./src/*", - "./package.json": "./package.json" + "./package.json": "./package.json", + "./locale/*.json": "./locale/*.json", + "./typert": { + "types": "./lib/typert.host.d.ts", + "default": "./lib/typert.host.js" + }, + "./remote": { + "types": "./lib/typert.remote-client.d.ts", + "default": "./lib/typert.remote-client.js" + } }, "files": [ + "locale/*.json", "lib/index.js", "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "lib/**/*.js.map", + "lib/typert.host.js", + "lib/typert.host.d.ts", + "lib/typert.remote-client.js", + "lib/typert.remote-client.d.ts", + "lib/typert.remote-client.d.ts.map", "src" ], "license": "MIT", @@ -39,18 +58,30 @@ "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-util-values": "workspace:*" + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", - "@deepseek-ai/dsh-util-values": "workspace:*" + "@deepseek-ai/dsh-util-values": "workspace:*", + "@deepseek-ai/dsh-authorization": "workspace:*", + "@deepseek-ai/dsh-credentials": "workspace:*", + "@deepseek-ai/dsh-host-webserver": "workspace:*", + "@deepseek-ai/dsh-typert-protocol": "workspace:*" }, "peerDependenciesMeta": { "@deepseek-ai/dsh-agent": { "optional": true } + }, + "dependencies": { + "@deepseek-ai/schemastery": "workspace:~", + "zod": "4.6.6" } } diff --git a/packages/credentials/deepseek-account/src/client-metadata.ts b/packages/credentials/deepseek-account/src/client-metadata.ts new file mode 100644 index 0000000000..76583ca318 --- /dev/null +++ b/packages/credentials/deepseek-account/src/client-metadata.ts @@ -0,0 +1,56 @@ +/** Platform client identity headers and deployment cookies. */ +import type { AccountClientMetadata } from './types.ts' + +/** Merge Cookie header pairs by case-sensitive name, retaining unrelated cookies. + * @param base - existing request cookies. + * @param override - deployment cookies whose values take precedence. + * @returns one Cookie header with at most one pair per name. + */ +export function mergePlatformCookies(base: string, override: string): string { + const cookies = new Map() + for (const header of [base, override]) { + for (const pair of header.split(';')) { + const separator = pair.indexOf('=') + if (separator < 1) continue + cookies.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()) + } + } + return [...cookies].map(([name, value]) => `${name}=${value}`).join('; ') +} + +/** + * Identify native desktop API requests; null leaves non-desktop requests unchanged. + * @param platform - Operating system supplied by the desktop composition. + * @returns Platform request headers shared by account and update-policy clients. + */ +export function desktopClientHeaders(platform: 'darwin' | 'win32' | null): Record { + if (platform === null) return {} + return { 'x-client-platform': platform === 'win32' ? 'desktop-win' : 'desktop-mac' } +} + +/** + * Build the Platform client identity headers for one call. + * @param platform - Operating system supplied by the desktop composition; null identifies the client as web. + * @param client - identity of the requesting UI for this call. + * @returns the five client headers; the bundle ID is intentionally empty. + */ +export function platformClientHeaders(platform: 'darwin' | 'win32' | null, client: AccountClientMetadata): Record { + return { + 'x-client-bundle-id': '', + 'x-client-platform': 'web', + ...desktopClientHeaders(platform), + 'x-client-version': client.version, + 'x-client-locale': platformWireLocale(client.locale), + 'x-client-timezone-offset': String(client.timezoneOffsetSeconds), + } +} + +/** + * Reduce a caller's UI language to the region-tagged Platform locale. + * Shares one normalization with the header and with request body locale fields. + * @param locale - active UI language such as `zh-CN`, `zh_TW`, or `en-US`. + * @returns the region-tagged Platform locale for that language, `zh_CN` or `en_US`. + */ +export function platformWireLocale(locale: string): 'zh_CN' | 'en_US' { + return locale.toLowerCase().split(/[-_]/)[0] === 'zh' ? 'zh_CN' : 'en_US' +} diff --git a/packages/credentials/deepseek-account-platform/src/details.ts b/packages/credentials/deepseek-account/src/details.ts similarity index 53% rename from packages/credentials/deepseek-account-platform/src/details.ts rename to packages/credentials/deepseek-account/src/details.ts index d7c90b9ac3..e1dc0dec3f 100644 --- a/packages/credentials/deepseek-account-platform/src/details.ts +++ b/packages/credentials/deepseek-account/src/details.ts @@ -1,7 +1,7 @@ /** Platform Web profile and wallet queries projected for account UI consumers. */ import { z } from 'zod' -import type { AccountBonusNotification, AccountBonusOrderId, AccountDetails, AccountProfile, AccountUserId } from '@deepseek-ai/dsh-deepseek-account/types' -import { AccountUnauthorizedError, PlatformAuthError, requestAccount, requestBonusNotified, requestUnnotifiedBonuses } from './protocol.ts' +import type { AccountDetails, AccountProfile, AccountUserId } from './types.ts' +import { AccountUnauthorizedError, PlatformAuthError, requestAccount } from './protocol.ts' const user = z.object({ id: z.string().nullish(), @@ -15,15 +15,6 @@ const wallet = z.object({ currency: z.enum(['CNY', 'USD']), balance: z.string().regex(decimal), }) const summary = z.object({ normal_wallets: z.array(wallet), bonus_wallets: z.array(wallet) }) -// Protocol responses are JSON-decoded; metadata keeps any JSON value without field validation. -const bonusMetadata = z.custom>().optional() -const bonus = z.object({ - campaign: bonusMetadata, amount: bonusMetadata, currency: bonusMetadata, granted_at: bonusMetadata, - order_id: z.string(), title: z.string().nullish().transform(value => value ?? undefined), expires_at: z.string().nullish().transform(value => value ?? ''), msg: z.string(), -}) -// The shared response reader already unwraps biz_data, so the payload is the bonus list itself. -const unnotified = z.array(bonus) - /** Project Platform user data without retaining credentials or unneeded fields. * @param value - current or exchange user response. * @returns UI account profile. @@ -43,7 +34,7 @@ function projectProfile(value: z.infer): AccountProfile { } } -function accountPayload(schema: z.ZodType, value: unknown, field: 'profile' | 'balance' | 'bonus'): T { +function accountPayload(schema: z.ZodType, value: unknown, field: 'profile' | 'balance'): T { const parsed = schema.safeParse(value) if (!parsed.success) { console.error(`[deepseek-account] ${field} schema rejected`, { @@ -70,7 +61,7 @@ const queries: { [K in keyof AccountDetails]: { /** * Read one Platform account field without waiting for the other query. * @param field - profile or recharge and bonus wallet balances. - * @param origin - configured origin matching the stored grant issuer. + * @param origin - configured account API origin. * @param token - stored authorization token; response tokens are discarded. * @param signal - request and credential lifetime. * @param headers - validated deployment headers for the configured origin. @@ -86,38 +77,3 @@ export async function readAccountDetail(field: K return { status: 'failed' } } } - -/** - * Read the unnotified bonus list for one captured credential. - * @param origin - configured origin matching the stored grant issuer. - * @param token - captured account grant; the caller has already bound it to the account. - * @param signal - credential lifetime and request timeout. - * @param headers - deployment and client identity headers for the configured origin. - * @returns notifications in Platform order; a malformed payload is a protocol failure. - */ -export async function readUnnotifiedBonuses(origin: string, token: string, - signal: AbortSignal, headers: Record): Promise { - const parsed = accountPayload(unnotified, await requestUnnotifiedBonuses(origin, token, signal, headers), 'bonus') - return parsed.map(row => ({ - ...(row.campaign === undefined ? {} : { campaign: row.campaign }), - ...(row.amount === undefined ? {} : { amount: row.amount }), - ...(row.currency === undefined ? {} : { currency: row.currency }), - ...(row.granted_at === undefined ? {} : { grantedAt: row.granted_at }), - orderId: row.order_id as AccountBonusOrderId, expiresAt: row.expires_at, message: row.msg, - ...(row.title === undefined ? {} : { title: row.title }), - })) -} - -/** - * Record one displayed bonus as notified with the credential it was read under. - * @param origin - configured origin matching the stored grant issuer. - * @param token - captured account grant; the caller has already bound it to the account. - * @param orderId - granted bonus order the user saw. - * @param signal - credential lifetime and request timeout. - * @param headers - deployment and client identity headers for the configured origin. - * @returns after Platform records the acknowledgement; HTTP and business failures throw. - */ -export async function sendBonusNotified(origin: string, token: string, orderId: AccountBonusOrderId, - signal: AbortSignal, headers: Record): Promise { - await requestBonusNotified(origin, token, orderId, signal, headers) -} diff --git a/packages/credentials/deepseek-account/src/index.ts b/packages/credentials/deepseek-account/src/index.ts index 20b0a8b81d..8dddec9074 100644 --- a/packages/credentials/deepseek-account/src/index.ts +++ b/packages/credentials/deepseek-account/src/index.ts @@ -1,42 +1,222 @@ -/** Account Service Definition shared by platform, API, and model consumers. */ +/** DeepSeek account service; browser approval never bypasses local cancellation. */ +import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto' +import type { ServerResponse } from 'node:http' +import type {} from '@deepseek-ai/dsh-host-webserver' +import { arch, platform, release } from 'node:os' +import { promises as streamPromises } from 'node:stream' import { Context, Service } from '@deepseek-ai/cordis' -import type { AccountBonusBatch, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountUserId, AccountView, SignInAttemptId } from './types.ts' -export type { AccountBonusBatch, AccountBonusNotification, AccountBonusOrderId, AccountClientMetadata, AccountDetails, AccountProfile, AccountUserId, AccountWallet, AccountLinks, AccountView, SignInAttemptId, SignInAttemptView, SignInErrorCode } from './types.ts' -export { isRunningAccountTask, installAccountTaskCancellation } from './account-tasks.ts' +import { Remote, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol' +import Schema from '@deepseek-ai/schemastery' +import { z } from 'zod' +import { installAccountTaskCancellation, isRunningAccountTask } from './account-tasks.ts' +import { mergePlatformCookies, platformClientHeaders, platformWireLocale } from './client-metadata.ts' +import { type AccountNotification, type AccountNotificationBatch, type AccountNotificationEvent, type AccountNotificationId, type AccountClientMetadata, type AccountDetails, type AccountUserId, type AccountView, type AccountUpdate, type PlatformSession, type SignInAttemptId, type SignInAttemptView } from './types.ts' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AuthorizationSession } from '@deepseek-ai/dsh-authorization' +import { profile, readAccountDetail } from './details.ts' +import { readNotificationContent, readNotifications, sendNotificationEvent } from './notifications.ts' +import { revokeAccount, type LogoutRetryPolicy } from './logout.ts' +import { AccountUnauthorizedError, PlatformAuthError, platformHeaders, platformOrigin, browserUrl, requestPlatform, initialization, exchange, loginOrigin } from './protocol.ts' + +export type * from './types.ts' declare module '@deepseek-ai/cordis' { + interface Context { deepseekAccount: DeepSeekAccount } interface Events { /** Local grant removal has completed. * @mode emit */ 'deepseek-account/signed-out'(): void } - interface Context { - deepseekAccount: DeepSeekAccount +} + + +const KEY = credentialKey('deepseek-account-platform', 'default') +const DEVICE = credentialKey('deepseek-account-platform', 'device') +const grant = z.object({ version: z.literal(1), token: z.string().min(1), issuer: z.url() }) +const device = z.object({ id: z.uuid() }) + +/** Deployment-specific platform and request deadlines. */ +export interface Config { + /** Platform origin serving auth-api and browser pages. */ + platformOrigin?: string + /** Harness API origin for account notifications. */ + harnessOrigin?: string + /** Native desktop identity for Host API and embedded Platform requests; null identifies the client as web. */ + desktopPlatform?: 'darwin' | 'win32' | null + /** Optional frontend deployment selector for embedded Usage and Top-up pages. */ + embeddedPageDist?: string + /** Exact HTTP(S) origin allowed to receive account tokens for inference and files. */ + inferenceOrigin?: string + /** Allow HTTP only on loopback for the development Mock. */ + allowLoopbackHttp?: boolean + /** Map authorization and completion pages to platformOrigin for private development proxies. */ + rewriteBrowserOrigin?: boolean + /** Host-only headers for Platform and notification APIs; account authorization cannot be overridden. */ + requestHeaders?: Record + /** Overrides for profile, balance, notification and embedded Platform requests; + * Cookie pairs merge by name. Logout retains requestHeaders. + */ + accountRequestHeaders?: Record + /** Deadline for each platform HTTP request. */ + requestTimeoutMs?: number + /** Deadline for recharge-wallet queries; timeout returns a failed balance outcome. */ + balanceTimeoutMs?: number + /** Additional logout attempts after the first request fails, at most five. */ + logoutMaxRetries?: number + /** Delay before the first logout retry; each later delay doubles. */ + logoutRetryDelayMs?: number + /** Upper bound for the entire local attempt, even if the server advertises a longer TTL. */ + attemptTimeoutMs?: number +} +/** Validated deployment choices. */ +const Config = Schema.object({ + platformOrigin: Schema.string().default('https://platform.deepseek.com'), + harnessOrigin: Schema.string().default('https://harness.deepseek.com'), + desktopPlatform: Schema.union([Schema.const('darwin'), Schema.const('win32'), Schema.const(null)]).default(null), + embeddedPageDist: Schema.string().default(''), + inferenceOrigin: Schema.string().default('https://api.deepseek.com'), + allowLoopbackHttp: Schema.boolean().default(false), + rewriteBrowserOrigin: Schema.boolean().default(false), + requestHeaders: Schema.dict(Schema.string().role('secret')).default({}), + accountRequestHeaders: Schema.dict(Schema.string().role('secret')).default({}), + requestTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), + balanceTimeoutMs: Schema.number().min(1).max(120_000).default(30_000), + logoutMaxRetries: Schema.number().min(0).max(5).step(1).default(5), + logoutRetryDelayMs: Schema.number().min(1).max(60_000).default(1_000), + attemptTimeoutMs: Schema.number().min(1).max(3_600_000).default(600_000), +}) + +interface Attempt { + locale: 'en_US' | 'zh_CN' + clientHeaders: Record + view: SignInAttemptView + controller: AbortController + done: Promise + running: Promise + origin: string + loginSource: 'web' | 'desktop' + disposeCallback?: () => Promise + callback?: ServerResponse + initialProfile?: { token: string; value: AccountDetails['profile'] } + completionUrl?: string +} + +/** Account login, credentials, and client-safe Remote operations. */ +export class DeepSeekAccount extends TypertRemoteService { + static inject = ['credentials', 'authorization'] + static Config = Config + private readonly origin: string + private readonly harnessOrigin: string + private readonly embeddedPageDist: string + private readonly inferenceOrigin: string + private readonly rewriteBrowserOrigin: boolean + private readonly platform: 'darwin' | 'win32' | null + private readonly requestHeaders: Record + private readonly accountRequestHeaders: Record + private readonly requestTimeout: number + private readonly balanceTimeout: number + private readonly attemptTimeout: number + private readonly logoutPolicy: LogoutRetryPolicy + private readonly logoutLifetime = new AbortController() + private readonly revocations = new Set>() + private attempt: Attempt | undefined + private readonly listeners = new Set<(kind: 'snapshot' | 'credentials-changed' | 'identity') => void>() + /** + * Latest ready profile read and the grant token it was read with. Binding the token keeps a + * cached identity from answering for a credential that has since changed. + */ + private lastProfile: { readonly token: string; readonly profile: Extract } | undefined + private detailsLifetime = new AbortController() + private closed = false + private removing: Promise | undefined + + /** @param ctx - Host with authorization and credentials services. @param config - deployment options. */ + constructor(ctx: Context, config: Config = {}) { + super(ctx, 'deepseekAccount', { namespace: 'account' }) + installAccountTaskCancellation(ctx) + const resolved = Config(config) + this.embeddedPageDist = resolved.embeddedPageDist + this.origin = platformOrigin(resolved.platformOrigin, resolved.allowLoopbackHttp, 'platformOrigin') + this.harnessOrigin = platformOrigin(resolved.harnessOrigin, resolved.allowLoopbackHttp, 'harnessOrigin') + const inference = new URL(resolved.inferenceOrigin) + if (!['http:', 'https:'].includes(inference.protocol) || inference.username || inference.password + || inference.pathname !== '/' || inference.search || inference.hash) { + throw new Error('account: inferenceOrigin must be an HTTP(S) origin without credentials, path, query or fragment') + } + this.inferenceOrigin = inference.origin + this.rewriteBrowserOrigin = resolved.rewriteBrowserOrigin + this.platform = resolved.desktopPlatform + this.requestHeaders = platformHeaders(resolved.requestHeaders) + const accountHeaders = platformHeaders(resolved.accountRequestHeaders) + this.accountRequestHeaders = { ...this.requestHeaders, ...accountHeaders } + if (accountHeaders.cookie !== undefined) { + this.accountRequestHeaders.cookie = mergePlatformCookies(this.requestHeaders.cookie ?? '', accountHeaders.cookie) + } + this.requestTimeout = resolved.requestTimeoutMs + this.balanceTimeout = resolved.balanceTimeoutMs + this.attemptTimeout = resolved.attemptTimeoutMs + this.logoutPolicy = { + maxRetries: resolved.logoutMaxRetries, delayMs: resolved.logoutRetryDelayMs, requestTimeoutMs: this.requestTimeout, + } + ctx.authorization.registerFlow({ + key: KEY, label: 'DeepSeek', methods: [{ id: 'browser', label: 'DeepSeek' }], + run: (session) => { + const attempt = this.attempt + if (attempt === undefined) return Promise.reject(new PlatformAuthError('protocol')) + attempt.running = this.run(session, attempt) + return attempt.running + }, + }) + ctx.on('credentials/record-updated', (key) => { + if (key !== KEY) return + this.invalidateDetails() + this.changed('credentials-changed') + }) + ctx.effect(() => async () => { + this.closed = true + this.logoutLifetime.abort() + this.invalidateDetails() + const active = this.attempt + if (active !== undefined) { + if (active.view.phase !== 'committing') active.controller.abort() + await active.done + } + await this.removing + await Promise.all(this.revocations) + this.changed('snapshot') + }, 'account: active attempt lifetime') } -} -/** Host-only credentials for an embedded Platform document; never expose through account RPC. */ -export interface PlatformSession { - readonly origin: string - readonly token: string - /** Stable issuer account ID from the last successful profile read; null requires disposable browser storage. */ - readonly userId: AccountUserId | null - /** Optional dist query value selecting the embedded frontend deployment. */ - readonly embeddedPageDist?: string - /** Host-only deployment request headers; the consuming client adds its own dynamic identity, and neither reaches renderer bootstrap. */ - readonly requestHeaders?: Readonly> -} + async [Service.init](): Promise { + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined) return + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + if (parsed.data.issuer === this.origin) return + await this.ctx.credentials.deleteRecord(KEY) + } -/** Account operations; only Host consumers can obtain a request credential. */ -export abstract class DeepSeekAccount extends Service { - /** @param ctx - context owning this account implementation. */ - constructor(ctx: Context) { super(ctx, 'deepseekAccount') } /** * Read stored-account presence and the latest login attempt. * @returns a snapshot without credentials or PKCE secrets. */ - abstract getState(): Promise + @Remote + async getState(): Promise { + const record = await this.ctx.credentials.readRecord(KEY) + if (record !== undefined && (record.kind !== 'grant' || !grant.safeParse(record.payload).success)) { + throw new PlatformAuthError('storage') + } + const attempt = this.attempt?.view ?? null + return { + status: record === undefined ? 'signed-out' : 'credential-stored', + // Credential removal can notify watchers before sign-out finishes clearing the attempt. + attempt: record === undefined && attempt?.phase === 'succeeded' ? null : attempt, + links: { usageUrl: new URL('/usage', this.origin).href, topUpUrl: new URL('/top_up', this.origin).href }, + } + } + /** * Query Platform profile independently of wallet balances. * A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch @@ -44,27 +224,251 @@ export abstract class DeepSeekAccount extends Service { * @param client - identity of the requesting UI for this call. * @returns profile outcome, or null if signed out or the grant changed during the query. */ - abstract getProfile(client: AccountClientMetadata): Promise + @Remote + async getProfile(client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + const result = await this.getDetail('profile', this.detailHeaders(client), { lifetime, stored }) + if (this.detailsLifetime !== lifetime) return null + if (result !== null) this.cacheProfile(stored.token, result) + if (result?.status !== 'failed') return result + // Only this same grant's last ready read may stand in for a failed refresh. + const cached = this.lastProfile?.token === stored.token ? this.lastProfile.profile : undefined + return cached ?? result + } + /** * Query Platform recharge and bonus wallet balances independently of profile data. * @param client - identity of the requesting UI for this call. * @returns balance outcome, or null if signed out or the grant changed during the query. */ - abstract getBalance(client: AccountClientMetadata): Promise + @Remote + getBalance(client: AccountClientMetadata): Promise { + return this.getDetail('balance', this.detailHeaders(client)) + } + /** - * Query the granted bonuses Platform has not yet recorded as displayed. + * Query unconsumed account notifications in server order without reading profile data. * @param client - identity of the requesting UI for this call; its language selects the server-authored message. - * @returns bonuses with their account, or null if signed out or the grant changed during the query. + * @returns notifications with their next query delay, or null if signed out or the grant changed during the query. */ - abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise + @Remote + async getNotifications(client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return null + try { + const batch = await readNotifications(this.harnessOrigin, stored.token, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime ? batch : null + } catch (error) { + if (this.detailsLifetime !== lifetime) return null + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return null + } + throw error + } + } + /** - * Record one displayed bonus as notified for the account it belongs to. - * @param accountId - account the notification was read for; a different current account is never acknowledged. - * @param orderId - granted bonus order the user saw. - * @param client - identity of the requesting UI for this call. - * @returns true once Platform records the acknowledgement; false if signed out or the account changed. + * Query localized content of a notification, including one already consumed. + * @param id - notification whose content is requested. + * @param client - identity of the requesting UI; its language selects the localized content. + * @returns content without changing consumption, or null if signed out or the grant changed. */ - abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise + @Remote + async getNotificationContent(id: AccountNotificationId, + client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return null + try { + const content = await readNotificationContent(this.harnessOrigin, stored.token, id, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime ? content : null + } catch (error) { + if (this.detailsLifetime !== lifetime) return null + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return null + } + throw error + } + } + + /** + * Report a notification interaction; the backend decides consumption. + * @param id - notification the user interacted with. + * @param event - displayed frame, non-dismiss action click, or explicit dismissal. + * @param client - identity of the requesting UI for this call. + * @returns true once the server accepts the event; false if signed out or credentials changed during the call. + */ + @Remote + async reportNotificationEvent(id: AccountNotificationId, + event: AccountNotificationEvent, client: AccountClientMetadata): Promise { + const lifetime = this.detailsLifetime + const headers = this.detailHeaders(client) + const stored = await this.readCurrentGrant(lifetime) + if (stored === null) return false + try { + await sendNotificationEvent(this.harnessOrigin, stored.token, id, event, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(this.requestTimeout)]), headers) + return this.detailsLifetime === lifetime + } catch (error) { + if (this.detailsLifetime !== lifetime) return false + if (error instanceof AccountUnauthorizedError) { + await this.expireCredential(stored.token, lifetime) + return false + } + throw error + } + } + + /** + * Cache one ready profile against the grant token it was read with, so identity reuse cannot cross + * a credential change. A stable ID that first appears or changes notifies identity-enabled watch consumers, so + * identity consumers re-read getPlatformSession; repeated IDs stay silent. + * @param token - grant the profile was read with. + * @param profile - profile outcome to record when it carries account data. + */ + private cacheProfile(token: string, profile: AccountDetails['profile']): void { + if (profile.status !== 'ready') return + // Identity publishers re-read the session snapshot; wake them only when the stable ID changes. + const previous = this.lastProfile?.profile.value.id || null + this.lastProfile = { token, profile } + if (previous !== (profile.value.id || null)) this.changed('identity') + } + + private async getDetail(field: K, headers: Record, + captured?: { lifetime: AbortController; stored: z.infer }): Promise { + const lifetime = captured?.lifetime ?? this.detailsLifetime + const stored = captured?.stored ?? await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + if (field === 'profile' && this.attempt?.initialProfile?.token === stored.token) { + const initial = this.attempt.initialProfile.value + delete this.attempt.initialProfile + return initial as AccountDetails[K] + } + try { + const details = await readAccountDetail(field, this.origin, stored.token, + AbortSignal.any([lifetime.signal, AbortSignal.timeout(field === 'balance' ? this.balanceTimeout : this.requestTimeout)]), headers) + return this.detailsLifetime !== lifetime ? null : details + } catch (_unauthorized) { + // readAccountDetail exposes only authenticated credential rejection failures. + if (this.detailsLifetime === lifetime) await this.expireCredential(stored.token, lifetime) + return null + } + } + + /** Deployment account headers plus the client identity headers derived from one call's metadata. */ + private detailHeaders(client: AccountClientMetadata): Record { + return { ...this.accountRequestHeaders, ...platformClientHeaders(this.platform, client) } + } + + /** + * Remove an inference-rejected token only while it still matches the stored login. + * @param token - token captured by the rejected inference request. + * @returns after matching credentials are removed and the expiry notification is emitted. + */ + async rejectToken(token: string): Promise { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored?.token !== token || this.detailsLifetime !== lifetime) return + await this.expireCredential(token, lifetime) + } + + private async expireCredential(token: string, lifetime: AbortController): Promise { + this.removing ??= (async () => { + if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) + const record = await this.ctx.credentials.readRecord(KEY) + if (this.closed || this.detailsLifetime !== lifetime || record?.kind !== 'grant') return this.getState() + const current = grant.parse(record.payload) + if (current.token !== token || current.issuer !== this.origin) return this.getState() + await this.ctx.credentials.deleteRecord(KEY) + this.ctx.emit('deepseek-account/session-expired') + this.attempt = undefined + this.ctx.emit('deepseek-account/signed-out') + this.changed('snapshot') + return this.getState() + })().finally(() => { this.removing = undefined }) + await this.removing + } + + /** + * Read existing login identity without creating a device or returning credentials. + * @returns optional device/account identifiers and the provider's OS version string. + */ + async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> { + const [record, session] = await Promise.all([ + this.ctx.credentials.readRecord(DEVICE), + this.getPlatformSession(), + ]) + const parsed = record?.kind === 'grant' ? device.safeParse(record.payload) : undefined + return { + ...parsed?.success ? { deviceId: parsed.data.id } : {}, + ...session?.userId == null ? {} : { userId: session.userId }, + osVersion: deviceOsVersion(), + } + } + + /** + * Read credentials for the configured embedded-page origin, bound to their account environment, and + * pair them with the account ID from the last successful profile read; no profile request is made. + * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. + */ + async getPlatformSession(): Promise { + const lifetime = this.detailsLifetime + const stored = await this.readCurrentGrant(lifetime) + if (stored === null || lifetime.signal.aborted) return null + // Deployment headers only; the consuming client adds the identity of its own UI. + const requestHeaders = { ...this.accountRequestHeaders } + // Identity comes from the profile read for this same grant; an unknown ID requires disposable + // browser storage. A replaced credential never publishes the account its predecessor named. + return { origin: this.origin, token: stored.token, + userId: this.lastProfile?.token === stored.token ? this.lastProfile.profile.value.id || null : null, + ...(this.embeddedPageDist ? { embeddedPageDist: this.embeddedPageDist } : {}), + requestHeaders } + } + + private async readCurrentGrant(lifetime: AbortController): Promise | null> { + if (this.closed) return null + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined || lifetime.signal.aborted) return null + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + // A private origin override must never forward a grant issued by another environment. + if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') + return parsed.data + } + + /** + * Resolve a credential only for the inference origin allowed by the provider. + * @param url - actual request destination or API base URL. + * @returns stored token, or undefined for other origins or a signed-out account. + */ + async resolveToken(url: string): Promise { + if (this.closed || this.removing !== undefined) return undefined + const destination = new URL(url) + if (destination.origin !== this.inferenceOrigin || destination.username || destination.password) return undefined + const record = await this.ctx.credentials.readRecord(KEY) + if (record === undefined) return undefined + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const result = grant.safeParse(record.payload) + if (!result.success) throw new PlatformAuthError('storage') + // Development grants cannot authenticate production model or file requests. + const issuer = new URL(result.data.issuer) + if (result.data.token.startsWith('dsh_mock_')) return undefined + if (this.inferenceOrigin === 'https://api.deepseek.com') { + if (['localhost', '127.0.0.1', '[::1]'].includes(issuer.hostname)) return undefined + } else if (issuer.origin !== this.origin) return undefined + return result.data.token + } + /** * Join an active attempt or start browser authorization. * @param client - identity of the requesting UI; a new attempt captures it, and joining retains the original attempt's identity. @@ -72,103 +476,346 @@ export abstract class DeepSeekAccount extends Service { * @param loginSource - initiating UI, used to return from a failed exchange. * @returns the initial snapshot without waiting for browser approval. */ - abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise + @Remote + async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: 'web' | 'desktop'): Promise { + if (this.removing !== undefined) await this.removing + const origin = loginOrigin(callbackOrigin) + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== undefined && ['initializing', 'waiting-browser', 'exchanging', 'committing'].includes(this.attempt.view.phase)) { + return this.getState() + } + const previous = this.attempt + if (previous !== undefined) { + await previous.done + // Disposal can close the provider while the previous attempt settles. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== previous) return this.getState() + } + const attempt: Attempt = { + origin, loginSource, + locale: platformWireLocale(client.locale), + clientHeaders: platformClientHeaders(this.platform, client), + view: { id: randomUUID() as SignInAttemptId, phase: 'initializing' }, + controller: new AbortController(), done: Promise.resolve(), running: Promise.resolve(), + } + this.attempt = attempt + attempt.done = this.ctx.authorization.begin({ + key: KEY, signal: attempt.controller.signal, + interaction: { notify: () => undefined, prompt: () => Promise.reject(new PlatformAuthError('protocol')) }, + }).then((outcome) => { + this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' }) + if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) { + attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end() + } else attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() + }).catch((error: unknown) => { + const code = error instanceof PlatformAuthError ? error.code : 'protocol' + console.error('[deepseek-account] sign-in failed', { errorCode: code }) + this.update(attempt, { phase: code === 'expired' ? 'expired' : 'failed', errorCode: code }) + this.finishFailedCallback(attempt) + }).then(async () => { + // begin() may report cancellation before the HTTP work observes its signal. + await attempt.running.catch(() => undefined) + if (attempt.callback !== undefined) { + await streamPromises.finished(attempt.callback, { cleanup: true }).catch(() => undefined) + } + await attempt.disposeCallback?.() + }) + this.changed('snapshot') + return this.getState() + } + /** * Cancel only the named attempt; committing attempts settle before returning. - * @param id - attempt identity from this Host. + * @param attemptId - attempt identity from this Host. * @returns state after cancellation or an already-started commit. */ - abstract cancelSignIn(id: SignInAttemptId): Promise + @Remote + async cancelSignIn(attemptId: SignInAttemptId): Promise { + const attempt = this.attempt + if (attempt?.view.id === attemptId) { + if (attempt.view.phase !== 'committing') { + attempt.controller.abort() + this.ctx.authorization.cancel(KEY) + } + await attempt.done + } + return this.getState() + } + /** * Remove the local grant while retaining API keys; the provider revokes it in the background. * @param client - identity of the requesting UI, captured for the background revocation retries. * @returns the signed-out state after local removal; remote failures never restore the grant. */ - abstract signOut(client: AccountClientMetadata): Promise + @Remote + signOut(client: AccountClientMetadata): Promise { + this.removing ??= (async () => { + if (this.closed) throw new PlatformAuthError('protocol') + if (this.attempt !== undefined) await this.cancelSignIn(this.attempt.view.id) + const record = await this.ctx.credentials.readRecord(KEY) + if (record !== undefined) { + if (record.kind !== 'grant') throw new PlatformAuthError('storage') + const parsed = grant.safeParse(record.payload) + if (!parsed.success) throw new PlatformAuthError('storage') + if (parsed.data.issuer !== this.origin) throw new PlatformAuthError('protocol') + await this.ctx.credentials.deleteRecord(KEY) + this.revoke(parsed.data.token, platformClientHeaders(this.platform, client)) + } + this.attempt = undefined + this.ctx.emit('deepseek-account/signed-out') + this.changed('snapshot') + return this.getState() + })().finally(() => { this.removing = undefined }) + return this.removing + } + /** - * Subscribe to snapshots including a complete initial state. + * Inspect running work before sign-out. + * @returns whether a running task's latest request uses the account route; false when the optional agents service is absent. + */ + @Remote + hasRunningAccountTasks(): boolean { + return this.ctx.get('agents')?.list().some(isRunningAccountTask) ?? false + } + + /** + * Subscribe to live credential expiry without replay. + * @param signal - subscription lifetime; provider disposal also ends it. + * @returns expiry notifications emitted during the subscription. + */ + @Remote({ mode: 'stream' }) + async *watchExpiry(signal: AbortSignal): AsyncIterable<'session-expired'> { + const lifetime = AbortSignal.any([signal, this.logoutLifetime.signal]) + let pending = 0 + let wake: (() => void) | undefined + const stop = this.ctx.on('deepseek-account/session-expired', () => { pending++; wake?.() }) + const abort = (): void => { wake?.() } + lifetime.addEventListener('abort', abort, { once: true }) + try { + while (!lifetime.aborted) { + if (pending > 0) { pending--; yield 'session-expired'; continue } + await new Promise((resolve) => { wake = resolve }) + } + } finally { + stop() + lifetime.removeEventListener('abort', abort) + } + } + + /** + * Subscribe to ordered updates including a complete initial snapshot. * @param signal - subscription lifetime; ending it never cancels login. * @param includeIdentityChanges - also notify when cached Platform identity changes; defaults to false. - * @returns complete snapshots as account state changes. + * @returns complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce. */ - abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable + watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable { + return this.observeUpdates(signal, includeIdentityChanges) + } + /** - * Resolve a credential only for the inference origin allowed by the provider. - * @param url - actual request destination or API base URL. - * @returns stored token, or undefined for other origins or a signed-out account. + * Stream account state without the Host-only identity subscription option. + * @param signal - subscription lifetime. + * @returns initial state, login progress, and credential-change updates. */ - abstract resolveToken(url: string): Promise - /** - * Remove an inference-rejected token only while it still matches the stored login. - * @param token - token captured by the rejected inference request. - * @returns after matching credentials are removed and the expiry notification is emitted. - */ - abstract rejectToken(token: string): Promise - /** - * Read credentials for the configured Platform origin, bound to their issuing environment, and - * pair them with the account ID from the last successful profile read; no profile request is made. - * @returns a Host-only snapshot, or null while signed out or when the credential changed during the read. - */ - abstract getPlatformSession(): Promise - /** - * Read existing login identity without creating a device or returning credentials. - * @returns optional device/account identifiers and the provider's OS version string. - */ - abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }> + @Remote({ name: 'watch', mode: 'stream' }) + watchState(signal: AbortSignal): AsyncIterable { + return this.observeUpdates(signal, false) + } + + private async *observeUpdates(signal: AbortSignal, includeIdentityChanges: boolean): AsyncIterable { + let pending: AccountUpdate['type'] | undefined = 'snapshot' + let wake: (() => void) | undefined + const changed = (kind: 'snapshot' | 'credentials-changed' | 'identity'): void => { + if (kind === 'identity' && !includeIdentityChanges) return + if (kind === 'credentials-changed' || pending === undefined) { + pending = kind === 'credentials-changed' ? kind : 'snapshot' + } + wake?.() + } + const abort = (): void => { wake?.() } + this.listeners.add(changed) + signal.addEventListener('abort', abort, { once: true }) + try { + while (!this.closed && !signal.aborted) { + if (pending !== undefined) { + const type = pending + pending = undefined + const lifetime = this.detailsLifetime + const state = await this.getState() + // A credential write during the read owns the next event and its replacement state. + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- Abort or disposal can occur during the state read. + if (lifetime !== this.detailsLifetime || signal.aborted || this.closed) continue + yield { type, state } + continue + } + await new Promise((resolve) => { wake = resolve }) + } + } finally { + this.listeners.delete(changed) + signal.removeEventListener('abort', abort) + } + } + + private revoke(token: string, headers: Record): void { + if (this.closed) return + const revocation = revokeAccount(this.origin, token, this.logoutPolicy, + this.logoutLifetime.signal, { ...this.requestHeaders, ...headers }).finally(() => { this.revocations.delete(revocation) }) + this.revocations.add(revocation) + } + + private invalidateDetails(): void { + this.lastProfile = undefined + this.detailsLifetime.abort() + this.detailsLifetime = new AbortController() + } + + private changed(kind: 'snapshot' | 'credentials-changed' | 'identity'): void { + for (const listener of this.listeners) listener(kind) + } + + private update(attempt: Attempt, value: Partial): void { + const { authorizeUrl: _url, ...rest } = attempt.view + attempt.view = { ...rest, ...value } + this.changed('snapshot') + } + + private async run(session: AuthorizationSession, attempt: Attempt): Promise { + const webServer = this.ctx.get('webServer') + if (webServer === undefined) throw new PlatformAuthError('protocol') + const verifier = randomBytes(32).toString('base64url') + const state = randomBytes(32).toString('base64url') + const challenge = createHash('sha256').update(verifier).digest('base64url') + let authorizeId: string | undefined + const code = Promise.withResolvers() + // Callback requests may precede initialization settlement; the rejection is observed immediately. + void code.promise.catch(() => undefined) + const deadline = new AbortController() + let expiresAt = Date.now() + this.attemptTimeout + const signal = AbortSignal.any([session.signal, deadline.signal]) + let timer = setTimeout(() =>{ deadline.abort() }, this.attemptTimeout) + const abort = (): void => { code.reject(new PlatformAuthError('expired')) } + signal.addEventListener('abort', abort, { once: true }) + try { + attempt.disposeCallback = this.ctx.effect(() => webServer.register({ + kind: 'exact', path: '/oauth/callback', handler: (req, res) => { + let url: URL + try { url = new URL(req.url ?? '/', 'http://127.0.0.1') } + catch { res.writeHead(400, { 'cache-control': 'no-store' }).end(); return } + const receivedCode = url.searchParams.get('code') + const receivedState = url.searchParams.get('state') ?? '' + const validState = Buffer.byteLength(receivedState) === Buffer.byteLength(state) + && timingSafeEqual(Buffer.from(receivedState), Buffer.from(state)) + if (req.method !== 'GET' || url.pathname !== '/oauth/callback' || !validState || !receivedCode + || url.searchParams.getAll('state').length !== 1 || url.searchParams.getAll('code').length !== 1) { + res.writeHead(400, { 'cache-control': 'no-store' }).end(); return + } + if (signal.aborted || attempt.callback !== undefined || attempt.view.phase !== 'waiting-browser') { + res.writeHead(410, { 'cache-control': 'no-store' }).end(); return + } + attempt.callback = res + code.resolve(receivedCode) + }, + }), 'account: browser callback') + signal.throwIfAborted() + const redirectUri = `${attempt.origin}/oauth/callback` + const init = initialization.safeParse(await this.request('auth_init', { + code_challenge: challenge, code_challenge_method: 'S256', state, redirect_uri: redirectUri, locale: attempt.locale, + login_source: attempt.loginSource, + }, signal, attempt.clientHeaders), { reportInput: true }) + if (!init.success) this.rejectPayload('auth_init', init.error) + const authorizeUrl = browserUrl(init.data.authorize_url, this.origin, '/dsh/authorize', this.rewriteBrowserOrigin) + authorizeId = init.data.authorize_id + signal.throwIfAborted() + const now = Date.now() + expiresAt = Math.min(expiresAt, now + init.data.expires_in * 1000) + const remaining = expiresAt - now + if (remaining <= 0) { deadline.abort(); signal.throwIfAborted() } + clearTimeout(timer) + timer = setTimeout(() =>{ deadline.abort() }, remaining) + this.update(attempt, { phase: 'waiting-browser', authorizeUrl, expiresAt }) + const receivedCode = await code.promise + signal.throwIfAborted() + this.update(attempt, { phase: 'exchanging' }) + const deviceRecord = await this.ctx.credentials.modifyRecord(DEVICE, current => Promise.resolve(current === undefined + ? { kind: 'grant', payload: { id: randomUUID() } } : undefined)) + if (deviceRecord?.kind !== 'grant') throw new PlatformAuthError('storage') + const identity = device.parse(deviceRecord.payload) + const result = exchange.safeParse(await this.request('auth_exchange', { + code: receivedCode, code_verifier: verifier, redirect_uri: redirectUri, + device_id: identity.id, device_model: `${platform()}-${arch()}`, os_version: deviceOsVersion(), + }, signal, attempt.clientHeaders), { reportInput: true }) + if (!result.success) this.rejectPayload('auth_exchange', result.error) + const completionUrl = new URL(browserUrl(result.data.authorized_url, this.origin, '/dsh/authorized', this.rewriteBrowserOrigin)) + completionUrl.searchParams.set('login_source', attempt.loginSource) + attempt.completionUrl = completionUrl.href + if (Date.now() >= expiresAt) deadline.abort() + signal.throwIfAborted() + if (result.data.user != null) { + try { attempt.initialProfile = { token: result.data.token, value: { status: 'ready', value: profile(result.data.user) } } } + catch { + // Invalid optional user data falls back to current without discarding a valid authorization. + } + } + this.update(attempt, { phase: 'committing' }) + clearTimeout(timer) + try { await session.commit({ kind: 'grant', payload: { version: 1, token: result.data.token, issuer: this.origin } }) } + catch { throw new PlatformAuthError('storage') } + } catch (error) { + if (deadline.signal.aborted) throw new PlatformAuthError('expired') + throw error + } finally { + if (signal.aborted && authorizeId !== undefined) this.cancelRequest(authorizeId, verifier, attempt.clientHeaders) + clearTimeout(timer) + signal.removeEventListener('abort', abort) + // begin() settles the browser response and removes only this attempt’s route. + } + } + + private rejectPayload(stage: string, error: z.ZodError): never { + console.error('[deepseek-account] payload rejected', { + stage, issues: error.issues.map(issue => ({ + path: issue.path, code: issue.code, + receivedType: issue.input === null ? 'null' : Array.isArray(issue.input) ? 'array' : typeof issue.input, + })), + }) + throw new PlatformAuthError('protocol') + } + + private cancelRequest(authorizeId: string, verifier: string, headers: Record): void { + if (this.closed) return + const cancellation = this.request('auth_cancel', { authorize_id: authorizeId, code_verifier: verifier }, + this.logoutLifetime.signal, headers).then(() => undefined, () => { + // Remote cancellation failures never reverse local cancellation or expose verifier diagnostics. + }).finally(() => { this.revocations.delete(cancellation) }) + this.revocations.add(cancellation) + } + + private request(method: string, body: unknown, signal: AbortSignal, headers: Record): Promise { + return requestPlatform(this.origin, method, body, + AbortSignal.any([signal, AbortSignal.timeout(this.requestTimeout)]), { ...this.requestHeaders, ...headers }) + } + + private finishFailedCallback(attempt: Attempt): void { + if (attempt.loginSource === 'web') { + const nonce = randomBytes(16).toString('base64url') + const message = attempt.locale === 'zh_CN' ? '登录失败,请关闭此标签页并在原页面重试。' + : 'Sign-in failed. Close this tab and try again in the original tab.' + attempt.callback?.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', + 'content-security-policy': `default-src 'none'; script-src 'nonce-${nonce}'; frame-ancestors 'none'`, + 'referrer-policy': 'no-referrer', + }).end(`${message}` + + `

${message}

`) + } else { + // Native account subscribers focus the login window; retain the browser’s Platform document. + attempt.callback?.writeHead(204, { 'cache-control': 'no-store' }).end() + } + } } export default DeepSeekAccount - -/** Merge Cookie header pairs by case-sensitive name, retaining unrelated cookies. - * @param base - existing request cookies. - * @param override - deployment cookies whose values take precedence. - * @returns one Cookie header with at most one pair per name. - */ -export function mergePlatformCookies(base: string, override: string): string { - const cookies = new Map() - for (const header of [base, override]) { - for (const pair of header.split(';')) { - const separator = pair.indexOf('=') - if (separator < 1) continue - cookies.set(pair.slice(0, separator).trim(), pair.slice(separator + 1).trim()) - } - } - return [...cookies].map(([name, value]) => `${name}=${value}`).join('; ') -} - -/** - * Identify native desktop API requests; null leaves non-desktop requests unchanged. - * @param platform - Operating system supplied by the desktop composition. - * @returns Platform request headers shared by account and update-policy clients. - */ -export function desktopClientHeaders(platform: 'darwin' | 'win32' | null): Record { - if (platform === null) return {} - return { 'x-client-platform': platform === 'win32' ? 'desktop-win' : 'desktop-mac' } -} - -/** - * Build the Platform client identity headers for one call. - * @param platform - Operating system supplied by the desktop composition; null identifies the client as web. - * @param client - identity of the requesting UI for this call. - * @returns the five client headers; the bundle ID is intentionally empty. - */ -export function platformClientHeaders(platform: 'darwin' | 'win32' | null, client: AccountClientMetadata): Record { - return { - 'x-client-bundle-id': '', - 'x-client-platform': 'web', - ...desktopClientHeaders(platform), - 'x-client-version': client.version, - 'x-client-locale': platformWireLocale(client.locale), - 'x-client-timezone-offset': String(client.timezoneOffsetSeconds), - } -} - -/** - * Reduce a caller's UI language to the region-tagged Platform locale. - * Shares one normalization with the header and with request body locale fields. - * @param locale - active UI language such as `zh-CN`, `zh_TW`, or `en-US`. - * @returns the region-tagged Platform locale for that language, `zh_CN` or `en_US`. - */ -export function platformWireLocale(locale: string): 'zh_CN' | 'en_US' { - return locale.toLowerCase().split(/[-_]/)[0] === 'zh' ? 'zh_CN' : 'en_US' +/** OS identification shared by login and credential-free identity reads. */ +function deviceOsVersion(): string { + return `${platform()} ${release()}` } diff --git a/packages/credentials/deepseek-account-platform/src/logout.ts b/packages/credentials/deepseek-account/src/logout.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/src/logout.ts rename to packages/credentials/deepseek-account/src/logout.ts diff --git a/packages/credentials/deepseek-account/src/notifications.ts b/packages/credentials/deepseek-account/src/notifications.ts new file mode 100644 index 0000000000..c998137248 --- /dev/null +++ b/packages/credentials/deepseek-account/src/notifications.ts @@ -0,0 +1,98 @@ +/** Validated, localized notification queries through the account API. */ +import { z } from 'zod' +import type { AccountNotification, AccountNotificationBatch, AccountNotificationEvent, AccountNotificationId } from './types.ts' +import { PlatformAuthError, requestNotificationContent, requestNotificationEvent, requestNotifications } from './protocol.ts' + +const action = z.object({ + label: z.string(), + style: z.enum(['primary', 'secondary']), + target: z.discriminatedUnion('type', [ + z.object({ type: z.literal('app_route'), name: z.literal('account') }), + z.object({ type: z.literal('dismiss') }), + ]), +}) +// The HTTP reader supplies JSON values; business data has no notification-specific fields. +const notification = z.object({ + id: z.string(), created_at: z.iso.datetime({ offset: true }), + display_until: z.iso.datetime({ offset: true }).nullable(), + title: z.string(), body: z.string(), actions: z.array(action), data: z.json().optional(), +}) +const list = z.object({ + next_poll_after: z.number().positive().max(2_147_483_647 / 1_000), + notifications: z.array(z.unknown()), +}) + +function project(value: z.infer): AccountNotification { + return { + id: value.id as AccountNotificationId, createdAt: value.created_at, + displayUntil: value.display_until, title: value.title, body: value.body, actions: value.actions, + ...(value.data === undefined ? {} : { data: value.data }), + } +} + +function parse(schema: z.ZodType, value: unknown): T { + const parsed = schema.safeParse(value) + if (!parsed.success) { + console.error('[deepseek-account] notification schema rejected', { + issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })), + }) + throw new PlatformAuthError('protocol') + } + return parsed.data +} + +/** + * Read unconsumed notifications for one captured account credential. + * @param origin - configured account API origin. + * @param token - captured account grant. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns supported notifications in server order and the next query delay in seconds; malformed entries are skipped, + * while HTTP and list-envelope failures reject. + */ +export async function readNotifications(origin: string, token: string, + signal: AbortSignal, headers: Record): Promise { + const value = parse(list, await requestNotifications(origin, token, signal, headers)) + const notifications = value.notifications.flatMap((entry, index) => { + const parsed = notification.safeParse(entry) + if (!parsed.success) { + console.error('[deepseek-account] skipping unsupported notification', { + index, issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })), + }) + return [] + } + return [project(parsed.data)] + }) + return { nextPollAfterSeconds: value.next_poll_after, notifications } +} + +/** + * Read localized content without changing notification consumption. + * @param origin - configured account API origin. + * @param token - captured token for this request's credential lifetime. + * @param id - notification whose content is requested. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns content with the requested identity; mismatched IDs and malformed responses reject. + */ +export async function readNotificationContent(origin: string, token: string, id: AccountNotificationId, + signal: AbortSignal, headers: Record): Promise { + const value = parse(notification, await requestNotificationContent(origin, token, id, signal, headers)) + if (value.id !== id) throw new PlatformAuthError('protocol') + return project(value) +} + +/** + * Report an interaction; the response's consumption decision never closes the local card. + * @param origin - configured account API origin. + * @param token - captured token for this request's credential lifetime. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers. + * @returns after the server accepts the event; HTTP and malformed responses reject. + */ +export async function sendNotificationEvent(origin: string, token: string, id: AccountNotificationId, + event: AccountNotificationEvent, signal: AbortSignal, headers: Record): Promise { + parse(z.object({ acked: z.boolean() }), await requestNotificationEvent(origin, token, id, event, signal, headers)) +} diff --git a/packages/credentials/deepseek-account-platform/src/protocol.ts b/packages/credentials/deepseek-account/src/protocol.ts similarity index 84% rename from packages/credentials/deepseek-account-platform/src/protocol.ts rename to packages/credentials/deepseek-account/src/protocol.ts index 54d1afd9ad..b7a6a234a6 100644 --- a/packages/credentials/deepseek-account-platform/src/protocol.ts +++ b/packages/credentials/deepseek-account/src/protocol.ts @@ -1,6 +1,6 @@ /** Validated platform HTTP messages and restricted browser destinations. */ import { z } from 'zod' -import type { AccountBonusOrderId, SignInErrorCode } from '@deepseek-ai/dsh-deepseek-account/types' +import type { AccountNotificationEvent, AccountNotificationId, SignInErrorCode } from './types.ts' /** Protocol errors expose a stable code, never a response body or authorization URL. */ export class PlatformAuthError extends Error { @@ -17,14 +17,16 @@ export class AccountUnauthorizedError extends PlatformAuthError { * Accept HTTPS platform endpoints, or explicitly configured loopback development HTTP. * @param value - configured origin. * @param allowLoopbackHttp - development-only opt-in. + * @param field - configuration field named in validation errors. * @returns normalized origin. */ -export function platformOrigin(value: string, allowLoopbackHttp: boolean): string { +export function platformOrigin(value: string, allowLoopbackHttp: boolean, + field: 'platformOrigin' | 'harnessOrigin'): string { const url = new URL(value) const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) if (url.username || url.password || url.pathname !== '/' || url.search || url.hash || !(url.protocol === 'https:' || (allowLoopbackHttp && loopback && url.protocol === 'http:'))) { - throw new Error('account: platformOrigin must be an HTTPS origin or explicitly enabled loopback HTTP origin') + throw new Error(`account: ${field} must be an HTTPS origin or explicitly enabled loopback HTTP origin`) } return url.origin } @@ -113,33 +115,49 @@ export function requestAccount(origin: string, path: '/auth-api/v0/users/current } /** - * Read the granted bonuses Platform has not yet recorded as displayed. - * @param origin - configured origin matching the grant issuer. + * Read unconsumed account notifications in server order. + * @param origin - configured account API origin. * @param token - stored account grant. * @param signal - credential lifetime and request timeout. * @param headers - deployment and client identity headers for this origin. - * @returns successful business payload holding the unnotified bonus list. + * @returns successful business payload holding the notification list. */ -export function requestUnnotifiedBonuses(origin: string, token: string, +export function requestNotifications(origin: string, token: string, signal: AbortSignal, headers: Record): Promise { - return platformRequest(`${origin}/api/v0/users/get_unnotified_bonuses`, + return platformRequest(`${origin}/api/v0/users/notifications/list`, { method: 'GET', headers: accountHeaders(headers, token) }, signal) } /** - * Acknowledge an actually displayed bonus to Platform. - * @param origin - configured origin matching the grant issuer. + * Read localized notification content, including a consumed notification. + * @param origin - configured account API origin. * @param token - stored account grant. - * @param orderId - granted bonus order the user saw. + * @param id - notification requested by its owning account. * @param signal - credential lifetime and request timeout. * @param headers - deployment and client identity headers for this origin. - * @returns successful business payload, which carries no data. + * @returns successful business payload containing one notification. */ -export function requestBonusNotified(origin: string, token: string, orderId: AccountBonusOrderId, +export function requestNotificationContent(origin: string, token: string, id: AccountNotificationId, signal: AbortSignal, headers: Record): Promise { - return platformRequest(`${origin}/api/v0/users/ack_bonus_notified`, { + return platformRequest(`${origin}/api/v0/users/notifications/content?id=${encodeURIComponent(id)}`, + { method: 'GET', headers: accountHeaders(headers, token) }, signal) +} + +/** + * Report an account notification interaction to the events endpoint. + * @param origin - configured account API origin. + * @param token - stored account grant. + * @param id - notification the user interacted with. + * @param event - displayed frame, business-action click, or explicit dismissal. + * @param signal - credential lifetime and request timeout. + * @param headers - deployment and client identity headers for this origin. + * @returns successful business payload containing the consumption decision. + */ +export function requestNotificationEvent(origin: string, token: string, id: AccountNotificationId, + event: AccountNotificationEvent, signal: AbortSignal, headers: Record): Promise { + return platformRequest(`${origin}/api/v0/users/notifications/events`, { method: 'POST', headers: { ...accountHeaders(headers, token), 'content-type': 'application/json' }, - body: JSON.stringify({ order_id: orderId }), + body: JSON.stringify({ notification_id: id, type: event }), }, signal) } @@ -150,7 +168,7 @@ function accountHeaders(headers: Record, token: string): Record< /** * End the Platform session using its existing logout endpoint. - * @param origin - configured origin matching the grant issuer. + * @param origin - configured account API origin. * @param token - stored account token. * @param signal - logout request deadline. * @param headers - validated deployment headers for this origin. diff --git a/packages/credentials/deepseek-account/src/types.ts b/packages/credentials/deepseek-account/src/types.ts index 39f1f086fb..5ccd36303b 100644 --- a/packages/credentials/deepseek-account/src/types.ts +++ b/packages/credentials/deepseek-account/src/types.ts @@ -41,6 +41,13 @@ export interface AccountView { readonly attempt: SignInAttemptView | null } +/** Ordered account stream item; every item carries the latest safe state. */ +export interface AccountUpdate { + /** Initial state and progress use snapshot; credential writes and removal use credentials-changed. */ + readonly type: 'snapshot' | 'credentials-changed' + readonly state: AccountView +} + /** Platform account identifier supplied by the current-user endpoint. */ export type AccountUserId = Branded<'AccountUserId'> /** Display identity; contacts retain Platform masking. */ @@ -62,27 +69,33 @@ export interface AccountDetails { readonly balance: { readonly status: 'ready'; readonly value: readonly AccountWallet[]; readonly bonusWallets: readonly AccountWallet[] } | { readonly status: 'failed' } } -/** Identity of one granted bonus order; stable across devices and sign-ins. */ -export type AccountBonusOrderId = Branded<'AccountBonusOrderId'> -/** One granted bonus Platform has not yet recorded as displayed; copy is server-authored. */ -export interface AccountBonusNotification { - /** Server-localized plain-text title; absent responses use the localized bonus title. */ - readonly title?: string - readonly orderId: AccountBonusOrderId - /** Optional Platform metadata, forwarded without validation. */ - readonly campaign?: JsonValue - readonly amount?: JsonValue - readonly currency?: JsonValue - readonly grantedAt?: JsonValue - /** Platform expiry timestamp; an empty string means the notice never expires. */ - readonly expiresAt: string - /** Server-localized plain text ready for display. */ - readonly message: string +/** Opaque string notification identity; stable across devices, sign-ins, and languages. */ +export type AccountNotificationId = Branded<'AccountNotificationId'> +/** Presentation, any non-dismiss action click, or explicit dismissal; independent of backend consumption. */ +export type AccountNotificationEvent = 'displayed' | 'cta_clicked' | 'dismissed' +/** Client action supported by the account notification presentation. */ +export interface AccountNotificationAction { + readonly label: string + readonly style: 'primary' | 'secondary' + readonly target: { readonly type: 'app_route'; readonly name: 'account' } | { readonly type: 'dismiss' } } -/** Unnotified bonuses with the account they belong to, in Platform order. */ -export interface AccountBonusBatch { - readonly accountId: AccountUserId - readonly bonuses: readonly AccountBonusNotification[] +/** One account notification with server-localized plain text and actions. */ +export interface AccountNotification { + readonly id: AccountNotificationId + readonly createdAt: string + /** Display deadline; null means the notification never expires. */ + readonly displayUntil: string | null + readonly title: string + readonly body: string + readonly actions: readonly AccountNotificationAction[] + /** Optional business data, retained independently of the localized copy. */ + readonly data?: JsonValue +} +/** Unconsumed notifications in server order, without account-profile data. */ +export interface AccountNotificationBatch { + /** Positive delay in seconds before querying again, within the browser timer range. */ + readonly nextPollAfterSeconds: number + readonly notifications: readonly AccountNotification[] } declare module '@deepseek-ai/cordis' { @@ -97,3 +110,15 @@ declare module '@deepseek-ai/cordis' { 'deepseek-account/model-sign-in-required'(): void } } + +/** Host-only credentials for an embedded Platform document; never expose through account RPC. */ +export interface PlatformSession { + readonly origin: string + readonly token: string + /** Stable issuer account ID from the last successful profile read; null requires disposable browser storage. */ + readonly userId: AccountUserId | null + /** Optional dist query value selecting the embedded frontend deployment. */ + readonly embeddedPageDist?: string + /** Host-only deployment request headers; the consuming client adds its own dynamic identity, and neither reaches renderer bootstrap. */ + readonly requestHeaders?: Readonly> +} diff --git a/packages/credentials/deepseek-account-platform/tests/account.spec.ts b/packages/credentials/deepseek-account/tests/account.spec.ts similarity index 98% rename from packages/credentials/deepseek-account-platform/tests/account.spec.ts rename to packages/credentials/deepseek-account/tests/account.spec.ts index 590fb0b7be..267616dab3 100644 --- a/packages/credentials/deepseek-account-platform/tests/account.spec.ts +++ b/packages/credentials/deepseek-account/tests/account.spec.ts @@ -11,7 +11,7 @@ import AuthorizationService from '@deepseek-ai/dsh-authorization' import type { AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' import { credentialKey, credentialRef } from '@deepseek-ai/dsh-credentials' -import { Config, PlatformAccount } from '../src/index.ts' +import { DeepSeekAccount } from '../src/index.ts' import { browserUrl, platformHeaders, platformOrigin, loginOrigin } from '../src/protocol.ts' const cleanups: Array<() => Promise> = [] @@ -157,18 +157,18 @@ async function fixture( const authorization = ctx.plugin(AuthorizationService) await authorization await beforeAccount?.(ctx, origin) - const provider = ctx.plugin(PlatformAccount, { + const provider = ctx.plugin(DeepSeekAccount, { platformOrigin: origin, inferenceOrigin, embeddedPageDist, desktopPlatform, allowLoopbackHttp: true, requestHeaders, accountRequestHeaders, rewriteBrowserOrigin, logoutRetryDelayMs: 1, balanceTimeoutMs, }) await provider cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose(); await web.dispose() }) - const account = ctx.deepseekAccount as PlatformAccount + const account = ctx.deepseekAccount const states = new AbortController() cleanups.push(async () => { states.abort() }) async function wait(phase: string) { - for await (const state of account.watch(states.signal)) if (state.attempt?.phase === phase) return state + for await (const { state } of account.watch(states.signal)) if (state.attempt?.phase === phase) return state throw new Error(`missing phase ${phase}`) } return { cancellations, cancellationReceived, holdCancel: () => { holdCancel = true }, @@ -307,9 +307,9 @@ it('allows real account credentials only on the exact official HTTPS origin', as }) it('restricts platform destinations to the configured origin and route', () => { - expect(() => platformOrigin('http://localhost:8081', false)).toThrow() - expect(platformOrigin('http://localhost:8081', true)).toBe('http://localhost:8081') - expect(() => platformOrigin('http://example.com', true)).toThrow() + expect(() => platformOrigin('http://localhost:8081', false, 'platformOrigin')).toThrow() + expect(platformOrigin('http://localhost:8081', true, 'platformOrigin')).toBe('http://localhost:8081') + expect(() => platformOrigin('http://example.com', true, 'platformOrigin')).toThrow() expect(() => browserUrl('https://evil.test/dsh/authorized', 'https://platform.deepseek.com', '/dsh/authorized')).toThrow() expect(() => browserUrl('https://platform.deepseek.com/other', 'https://platform.deepseek.com', '/dsh/authorized')).toThrow() }) @@ -719,7 +719,7 @@ it('never exports an embedded Platform token to a different configured issuer', await expect(f.account.getPlatformSession()).rejects.toThrow() }) -async function readDetails(account: Pick) { +async function readDetails(account: Pick) { const [profile, balance] = await Promise.all([account.getProfile(clientMetadata()), account.getBalance(clientMetadata())]) return profile === null || balance === null ? null : { profile, balance } } @@ -958,7 +958,7 @@ it('derives the client headers independently for profile, balance, and logout ca it('rejects unsupported native desktop platforms in configuration', () => { // @ts-expect-error Configuration files can name unsupported operating systems. - expect(() => Config({ desktopPlatform: 'linux' })).toThrow() + expect(() => DeepSeekAccount.Config({ desktopPlatform: 'linux' })).toThrow() }) it('retains successful profile data on current failure only for the same credential', async () => { @@ -1153,7 +1153,7 @@ it.each([{ kind: 'api-key' as const, key: 'wrong-kind' }, { kind: 'grant' as con it.each(['ftp://api.example', 'https://user:password@api.example', 'https://api.example/path', 'https://api.example/?query=1', 'https://api.example/#fragment'])('rejects invalid inference origin %s', async (inferenceOrigin) => { - expect(() => new PlatformAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin') + expect(() => new DeepSeekAccount(new Context(), { inferenceOrigin })).toThrow('account: inferenceOrigin') }) it('rejects authorization begun without a local account attempt', async () => { @@ -1451,9 +1451,9 @@ it.each([false, true])('notifies only identity-enabled watchers on profile ident await storeAccount(f) expect(await f.account.getProfile(clientMetadata())).toEqual({ status: 'failed' }) const lifetime = new AbortController() - const states: Awaited>[] = [] + const states: Awaited>[] = [] const watching = (async () => { - for await (const state of f.account.watch(lifetime.signal, includeIdentityChanges)) states.push(state) + for await (const { state } of f.account.watch(lifetime.signal, includeIdentityChanges)) states.push(state) })() try { await expect.poll(() => states.length).toBe(1) diff --git a/packages/credentials/deepseek-account-platform/tests/authorization-response.spec.ts b/packages/credentials/deepseek-account/tests/authorization-response.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/authorization-response.spec.ts rename to packages/credentials/deepseek-account/tests/authorization-response.spec.ts diff --git a/packages/credentials/deepseek-account/tests/client-headers.spec.ts b/packages/credentials/deepseek-account/tests/client-headers.spec.ts index d46d936e44..c346aec13c 100644 --- a/packages/credentials/deepseek-account/tests/client-headers.spec.ts +++ b/packages/credentials/deepseek-account/tests/client-headers.spec.ts @@ -1,6 +1,6 @@ /** Platform client identity headers derived from one call's metadata. */ import { expect, it } from 'vitest' -import { platformClientHeaders } from '../src/index.ts' +import { platformClientHeaders } from '../src/client-metadata.ts' it.each([ ['darwin', 'desktop-mac'], ['win32', 'desktop-win'], [null, 'web'], diff --git a/packages/credentials/deepseek-account-platform/tests/details.spec.ts b/packages/credentials/deepseek-account/tests/details.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/details.spec.ts rename to packages/credentials/deepseek-account/tests/details.spec.ts diff --git a/packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts b/packages/credentials/deepseek-account/tests/diagnostics.spec.ts similarity index 92% rename from packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts rename to packages/credentials/deepseek-account/tests/diagnostics.spec.ts index fe2a60b14d..935eb27d5a 100644 --- a/packages/credentials/deepseek-account-platform/tests/diagnostics.spec.ts +++ b/packages/credentials/deepseek-account/tests/diagnostics.spec.ts @@ -1,7 +1,8 @@ import { expect, it, vi } from 'vitest' -import { browserUrl, logoutAccount, requestAccount, requestBonusNotified, requestPlatform, requestUnnotifiedBonuses } from '../src/protocol.ts' -import type { AccountBonusOrderId } from '@deepseek-ai/dsh-deepseek-account/types' -import { readAccountDetail, readUnnotifiedBonuses } from '../src/details.ts' +import { browserUrl, logoutAccount, requestAccount, requestNotificationEvent, requestPlatform, requestNotifications } from '../src/protocol.ts' +import type { AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account/types' +import { readAccountDetail } from '../src/details.ts' +import { readNotifications } from '../src/notifications.ts' it.each(['/dsh/authorize', '/dsh/authorized'])('maps %s to the configured development origin and preserves query bytes', (path) => { const origin = 'http://localhost:8081' @@ -133,8 +134,8 @@ it('keeps successful authorization, account, bonus and logout requests silent', for (const path of ['/auth-api/v0/users/current', '/api/v0/users/get_user_summary'] as const) { await requestAccount(origin, path, 'private-token', signal, {}) } - await requestUnnotifiedBonuses(origin, 'private-token', signal, {}) - await requestBonusNotified(origin, 'private-token', 'fixture-order' as AccountBonusOrderId, signal, {}) + await requestNotifications(origin, 'private-token', signal, {}) + await requestNotificationEvent(origin, 'private-token', 'fixture-order' as AccountNotificationId, 'displayed', signal, {}) await logoutAccount(origin, 'private-token', signal, {}) fetcher.mockResolvedValueOnce(new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { email: 'private-email' } }, @@ -174,16 +175,16 @@ it.each([ }) -it('reports invalid bonus fields without logging bonus data', async () => { +it('reports skipped notification fields without logging notification data', async () => { const output = vi.spyOn(console, 'error').mockImplementation(() => undefined) const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValue(new Response(JSON.stringify({ - code: 0, data: { biz_code: 0, biz_data: [{ order_id: 42, msg: 'private-message' }] }, + code: 0, data: { biz_code: 0, biz_data: { next_poll_after: 600, notifications: [{ id: 42, body: 'private-message' }] } }, }))) try { - await expect(readUnnotifiedBonuses('https://platform.deepseek.com', 'private-token', - new AbortController().signal, {})).rejects.toThrow('account: protocol') - expect(output.mock.calls[0]?.[0]).toBe('[deepseek-account] bonus schema rejected') - expect(JSON.stringify(output.mock.calls)).toContain('order_id') + await expect(readNotifications('https://platform.deepseek.com', 'private-token', + new AbortController().signal, {})).resolves.toEqual({ nextPollAfterSeconds: 600, notifications: [] }) + expect(output.mock.calls[0]?.[0]).toBe('[deepseek-account] skipping unsupported notification') + expect(JSON.stringify(output.mock.calls)).toContain('id') expect(JSON.stringify(output.mock.calls)).not.toContain('private-') } finally { fetcher.mockRestore() diff --git a/packages/credentials/deepseek-account-platform/tests/expected/web-exchange-failure.txt b/packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/expected/web-exchange-failure.txt rename to packages/credentials/deepseek-account/tests/expected/web-exchange-failure.txt diff --git a/packages/credentials/deepseek-account-platform/tests/logout.spec.ts b/packages/credentials/deepseek-account/tests/logout.spec.ts similarity index 100% rename from packages/credentials/deepseek-account-platform/tests/logout.spec.ts rename to packages/credentials/deepseek-account/tests/logout.spec.ts diff --git a/packages/credentials/deepseek-account/tests/notifications.spec.ts b/packages/credentials/deepseek-account/tests/notifications.spec.ts new file mode 100644 index 0000000000..5f0edf8067 --- /dev/null +++ b/packages/credentials/deepseek-account/tests/notifications.spec.ts @@ -0,0 +1,630 @@ +/** Bonus notification reads and acknowledgements over the real Host HTTP path. */ +import { afterEach, expect, it, vi } from 'vitest' +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' +import { Context } from '@deepseek-ai/cordis' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AccountNotificationBatch, AccountNotificationId, AccountClientMetadata } from '@deepseek-ai/dsh-deepseek-account' +import { DeepSeekAccount } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) + +const ORDER = '4c1b0000-0000-4000-8000-000000000000' +const SECOND_ORDER = '5d2c0000-0000-4000-8000-000000000000' +const USER = 'test-user' + +/** Client identity supplied with each account operation; only the locale's primary subtag selects the wire locale. */ +const clientMetadata = (locale = 'en-US'): AccountClientMetadata => ({ version: '1.2.3', locale, timezoneOffsetSeconds: 28_800 }) + +interface Recorded { + readonly method: string | undefined + readonly url: string | undefined + readonly token: string | undefined + readonly locale: string | undefined + readonly bundleId: string | undefined + readonly platform: string | undefined + readonly version: string | undefined + readonly timezoneOffset: string | undefined + readonly contentType: string | undefined + readonly body: string | undefined +} + +/** Read one request body; the acknowledgement carries its order id in JSON, so the fixture keeps the exact bytes. */ +function requestBody(req: IncomingMessage): Promise { + return new Promise((resolve, reject) => { + let body = '' + req.setEncoding('utf8') + req.on('data', (chunk: string) => { body += chunk }) + req.on('error', reject) + req.on('end', () => { resolve(body) }) + }) +} + +/** @param id - opaque notification ID. @param fields - wire fields overridden by the scenario. @returns a complete notification. */ +function wire(id: string, fields: Record = {}) { + return { id, created_at: '2026-10-21T08:00:00Z', display_until: null, + title: 'Product news', body: 'New features are available.', actions: [], ...fields } +} + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), 'dsh-bonus-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const requests: Recorded[] = [] + let profileId: string | null = USER + let profileBizCode = 0 + let profileStatus = 200 + let bonusBizCode = 0 + let bonusStatus = 200 + let nextPollAfter: unknown = 300 + let bonuses: unknown = [wire(ORDER), wire(SECOND_ORDER)] + let content: unknown = wire(ORDER) + let contentStatus = 200 + let contentBizCode = 0 + let beforeListResponse: (() => Promise) | undefined + let beforeEventResponse: (() => Promise) | undefined + let acked = true + let beforeContentResponse: (() => Promise) | undefined + let ackBizCode = 0 + let ackStatus = 200 + let beforeProfileResponse: (() => Promise) | undefined + let origin = '' + const handle = async (req: IncomingMessage, res: ServerResponse): Promise => { + expect(req.headers.authorization).toBeUndefined() + const body = await requestBody(req) + requests.push({ method: req.method, url: req.url, token: req.headers['x-dsh-auth-token'] as string | undefined, + locale: req.headers['x-client-locale'] as string | undefined, + bundleId: req.headers['x-client-bundle-id'] as string | undefined, + platform: req.headers['x-client-platform'] as string | undefined, + version: req.headers['x-client-version'] as string | undefined, + timezoneOffset: req.headers['x-client-timezone-offset'] as string | undefined, + contentType: req.headers['content-type'], body: body === '' ? undefined : body }) + res.setHeader('content-type', 'application/json') + if (req.url === '/auth-api/v0/users/current') { + await beforeProfileResponse?.() + res.writeHead(profileStatus).end(JSON.stringify({ code: profileStatus === 200 ? 0 : 1, data: { biz_code: profileBizCode, + biz_data: { id: profileId, email: 't***@example.invalid', id_profile: { name: 'Test', picture: null } } } })) + return + } + if (req.url === '/api/v0/users/notifications/list') { + await beforeListResponse?.() + res.writeHead(bonusStatus).end(JSON.stringify({ code: bonusStatus === 200 ? 0 : 1, + data: { biz_code: bonusBizCode, biz_data: { next_poll_after: nextPollAfter, notifications: bonuses } } })) + return + } + if (req.url?.startsWith('/api/v0/users/notifications/content?')) { + await beforeContentResponse?.() + res.writeHead(contentStatus).end(JSON.stringify({ code: contentStatus === 200 ? 0 : 1, + data: { biz_code: contentBizCode, biz_data: content } })) + return + } + // The exact path is the assertion: a query parameter would fall through to the 404 below. + if (req.url === '/api/v0/users/notifications/events') { + await beforeEventResponse?.() + res.writeHead(ackStatus).end(JSON.stringify(ackStatus === 200 + ? { code: 0, msg: '', data: { biz_code: ackBizCode, biz_msg: ackBizCode === 0 ? '' : 'NOTIFICATION_NOT_FOUND', biz_data: { acked } } } + : { code: 1, msg: 'INTERNAL', data: null })) + return + } + res.writeHead(404).end('{}') + } + const server = createServer((req, res) => { void handle(req, res).catch(() => { res.writeHead(500).end('{}') }) }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + const address = server.address() + if (!address || typeof address === 'string') throw new Error('missing listener') + origin = `http://127.0.0.1:${address.port}` + cleanups.push(async () => { + await new Promise((resolve) => { server.close(() => { resolve() }); server.closeAllConnections() }) + }) + const ctx = new Context() + const credentials = ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await credentials + const authorization = ctx.plugin(AuthorizationService) + await authorization + // The composed client identity is this fixture's choice; `null` is the web profile's documented setting. + const provider = ctx.plugin(DeepSeekAccount, { + platformOrigin: origin, harnessOrigin: origin, allowLoopbackHttp: true, requestTimeoutMs: 5_000, desktopPlatform: null, + }) + await provider + cleanups.push(async () => { await provider.dispose(); await authorization.dispose(); await credentials.dispose() }) + const key = credentialKey('deepseek-account-platform', 'default') + return { + account: ctx.deepseekAccount, ctx, requests, key, + grant: async (token: string) => { + await ctx.credentials.modifyRecord(key, () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token, issuer: origin }, + })) + }, + signOut: async () => { + await ctx.credentials.deleteRecord(key) + }, + profileId: (value: string | null) => { profileId = value }, + failProfile: (bizCode = 17, status = 200) => { profileBizCode = bizCode; profileStatus = status }, + nextPollAfter: (value: unknown) => { nextPollAfter = value }, + notifications: (value: unknown) => { bonuses = value }, + content: (value: unknown) => { content = value }, + failContent: (bizCode = 0, status = 200) => { contentBizCode = bizCode; contentStatus = status }, + onContent: (hook: () => Promise) => { beforeContentResponse = hook }, + failBonuses: (bizCode = 17, status = 200) => { bonusBizCode = bizCode; bonusStatus = status }, + failAck: (bizCode = 0, status = 200) => { ackBizCode = bizCode; ackStatus = status }, + onList: (hook: () => Promise) => { beforeListResponse = hook }, + onEvent: (hook: () => Promise) => { beforeEventResponse = hook }, + acknowledged: (value: boolean) => { acked = value }, + onProfile: (hook: () => Promise) => { beforeProfileResponse = hook }, + } +} + +it('sends client identity headers on notification requests without a profile preflight', async () => { + const f = await fixture() + await f.grant('test-account-token') + const client = { version: '3.0.0', locale: 'zh-TW', timezoneOffsetSeconds: -18_000 } + await f.account.getNotifications(client) + await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', client) + expect(f.requests.map(request => [ + request.url, request.bundleId, request.platform, request.version, request.locale, request.timezoneOffset, + ])).toEqual([ + ['/api/v0/users/notifications/list', '', 'web', '3.0.0', 'zh_CN', '-18000'], + ['/api/v0/users/notifications/events', '', 'web', '3.0.0', 'zh_CN', '-18000'], + ]) +}) + +it('does not query the account identity across repeated notification reads and reports', async () => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata('en')) + await f.account.getNotifications(clientMetadata('en')) + await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')) + expect(f.requests.filter(request => request.url === '/auth-api/v0/users/current')).toHaveLength(0) +}) + +it('does not reuse a cached identity from another grant', async () => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + await f.grant('rotated-token') + await f.account.getNotifications(clientMetadata('en')) + expect(f.requests.map(request => [request.url, request.token])).toEqual([ + ['/auth-api/v0/users/current', 'test-account-token'], + ['/api/v0/users/notifications/list', 'rotated-token'], + ]) +}) + +it('leaves profile identity unknown when only notifications were queried', async () => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata()) + expect(await f.account.getPlatformSession()).toMatchObject({ userId: null, token: 'test-account-token' }) + expect(f.requests.map(request => request.url)).toEqual(['/api/v0/users/notifications/list']) +}) + +it.each([undefined, null, 0, -1, '300', 2_147_483.648])('rejects an invalid next_poll_after value: %s', async (delay) => { + const f = await fixture() + await f.grant('test-account-token') + f.nextPollAfter(delay) + await expect(f.account.getNotifications(clientMetadata())).rejects.toMatchObject({ code: 'protocol' }) +}) + +it.each([0.5, 300, 2_147_483.647])('preserves the server polling delay in seconds: %s', async (delay) => { + const f = await fixture() + await f.grant('test-account-token') + f.nextPollAfter(delay) + expect((await f.account.getNotifications(clientMetadata()))?.nextPollAfterSeconds).toBe(delay) +}) + +it('reads generic notifications in server order with account and client headers', async () => { + const f = await fixture() + await f.grant('test-account-token') + const result = await f.account.getNotifications(clientMetadata('zh-CN')) + expect(result).toEqual({ nextPollAfterSeconds: 300, notifications: [ + { id: ORDER as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Product news', body: 'New features are available.', actions: [] }, + { id: SECOND_ORDER as AccountNotificationId, createdAt: '2026-10-21T08:00:00Z', + displayUntil: null, title: 'Product news', body: 'New features are available.', actions: [] }, + ] }) + expect(f.requests).toEqual([ + { method: 'GET', url: '/api/v0/users/notifications/list', token: 'test-account-token', locale: 'zh_CN', + bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800' }, + ]) +}) + +it.each(['list', 'content'] as const)('accepts a %s notification without a business classification', async (operation) => { + const f = await fixture() + await f.grant('test-account-token') + const value = wire(ORDER) + f.notifications([value]) + f.content(value) + const notification = operation === 'list' ? (await f.account.getNotifications(clientMetadata()))?.notifications[0] + : await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + expect(notification).toMatchObject({ id: ORDER, title: 'Product news', body: 'New features are available.', actions: [] }) + expect(notification).not.toHaveProperty('type') +}) + +it.each(['notice', '123', '', '产品公告/one?lang=zh&part=2#latest%'])('preserves the string ID %j across list, content, and events', async (value) => { + const f = await fixture() + await f.grant('test-account-token') + const id = value as AccountNotificationId + f.notifications([wire(id)]) + f.content(wire(id)) + expect((await f.account.getNotifications(clientMetadata()))?.notifications[0]?.id).toBe(id) + expect((await f.account.getNotificationContent(id, clientMetadata()))?.id).toBe(id) + expect(await f.account.reportNotificationEvent(id, 'dismissed', clientMetadata())).toBe(true) + expect([f.requests[0]?.url, f.requests[2]?.url]).toEqual([ + '/api/v0/users/notifications/list', + '/api/v0/users/notifications/events', + ]) + const contentUrl = new URL(f.requests[1]!.url!, 'https://fixture.invalid') + expect(contentUrl.pathname).toBe('/api/v0/users/notifications/content') + expect([...contentUrl.searchParams]).toEqual([['id', id]]) + expect(contentUrl.hash).toBe('') + expect(f.requests.at(-1)?.body).toBe(JSON.stringify({ notification_id: id, type: 'dismissed' })) +}) + +it('keeps action targets and business expiry separate from the display deadline', async () => { + const f = await fixture() + await f.grant('test-account-token') + const actions = [{ label: 'View balance', style: 'primary', target: { type: 'app_route', name: 'account' } }, + { label: 'Got it', style: 'secondary', target: { type: 'dismiss' } }] + const data = { order_id: 'business-order', expires_at: '2026-11-21T08:00:00Z', amount: '5.00' } + f.notifications([wire(ORDER, { display_until: '2026-10-28T08:00:00Z', actions, data })]) + expect((await f.account.getNotifications(clientMetadata()))?.notifications).toEqual([ + { id: ORDER, createdAt: '2026-10-21T08:00:00Z', displayUntil: '2026-10-28T08:00:00Z', + title: 'Product news', body: 'New features are available.', actions, data }, + ]) +}) + +it.each([ + ['zh-CN', 'zh_CN'], + ['en-US', 'en_US'], +])('selects %s copy through the locale header and never a language query', async (locale, wireLocale) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getNotifications(clientMetadata(locale)) + expect(f.requests.map(request => request.locale)).toEqual([wireLocale]) + expect(f.requests.map(request => request.url)).toEqual([ + '/api/v0/users/notifications/list', + ]) +}) + +it.each([ + ['a non-string title', [wire(ORDER, { title: 42 })]], + ['a null title', [wire(ORDER, { title: null })]], + ['a non-string ID', [wire(ORDER, { id: 42 })]], + ['an invalid display deadline', [wire(ORDER, { display_until: '' })]], + ['an invalid creation time', [wire(ORDER, { created_at: 'yesterday' })]], + ['a missing body', [wire(ORDER, { body: undefined })]], + ['a non-array actions field', [wire(ORDER, { actions: null })]], + ['an unsupported action style', [wire(ORDER, { actions: [{ label: 'Open', style: 'danger', target: { type: 'dismiss' } }] })]], + ['an unsupported route', [wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'app_route', name: 'other' } }] })]], + ['an unsupported target', [wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'url', url: 'https://example.invalid' } }] })]], +])('skips malformed or unsupported notifications without losing valid neighbors: %s', async (_name, payload) => { + const f = await fixture() + await f.grant('test-account-token') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + f.notifications([wire('before'), ...payload, wire('after')]) + const result = await f.account.getNotifications(clientMetadata()) + expect(result?.notifications.map(value => value.id)).toEqual(['before', 'after']) + expect(result?.nextPollAfterSeconds).toBe(300) + expect(log).toHaveBeenCalledOnce() + expect(log.mock.calls[0]?.[0]).toBe('[deepseek-account] skipping unsupported notification') + expect(log.mock.calls[0]?.[1]).toMatchObject({ index: 1 }) + } finally { log.mockRestore() } +}) + +it('returns an empty batch when every notification is unsupported', async () => { + const f = await fixture() + await f.grant('test-account-token') + const log = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + f.notifications([wire(ORDER, { actions: [{ label: 'Open', style: 'primary', target: { type: 'future' } }] })]) + expect(await f.account.getNotifications(clientMetadata())).toEqual({ notifications: [], nextPollAfterSeconds: 300 }) + } finally { log.mockRestore() } +}) + +it('rejects a notification payload that is not a list', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.notifications({}) + await expect(f.account.getNotifications(clientMetadata())).rejects.toThrow('account: protocol') +}) + +it('streams credential changes with current state and leaves profile reads silent', async () => { + const f = await fixture() + const lifetime = new AbortController() + const iterator = f.account.watch(lifetime.signal)[Symbol.asyncIterator]() + try { + expect(await iterator.next()).toMatchObject({ value: { type: 'snapshot', state: { status: 'signed-out' } } }) + await f.grant('first-token') + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + await f.account.getProfile(clientMetadata()) + const next = iterator.next() + await f.grant('second-token') + expect(await next).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + await f.signOut() + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'signed-out' } } }) + } finally { + lifetime.abort() + await iterator.return?.() + } +}) + +it('keeps a queued credential change ahead of a later profile snapshot', async () => { + const f = await fixture() + const lifetime = new AbortController() + const iterator = f.account.watch(lifetime.signal, true)[Symbol.asyncIterator]() + try { + expect(await iterator.next()).toMatchObject({ value: { type: 'snapshot' } }) + await f.grant('first-token') + await f.account.getProfile(clientMetadata()) + expect(await iterator.next()).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } finally { + lifetime.abort() + await iterator.return?.() + } +}) + +it.each(['replacement', 'abort'] as const)('discards an opening snapshot invalidated by %s during the read', async (change) => { + const f = await fixture() + const lifetime = new AbortController() + const reading = Promise.withResolvers() + const release = Promise.withResolvers() + const readState = f.account.getState.bind(f.account) + vi.spyOn(f.account, 'getState').mockImplementationOnce(async () => { + const state = await readState() + reading.resolve(undefined) + await release.promise + return state + }) + const iterator = f.account.watch(lifetime.signal)[Symbol.asyncIterator]() + const first = iterator.next() + try { + await reading.promise + if (change === 'replacement') await f.grant('replacement-token') + else lifetime.abort() + release.resolve(undefined) + if (change === 'replacement') { + expect(await first).toMatchObject({ value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } else expect(await first).toMatchObject({ done: true }) + } finally { + release.resolve(undefined) + lifetime.abort() + await first + await iterator.return?.() + } +}) + +it.each(['displayed', 'cta_clicked', 'dismissed'] as const)('reports %s with the grant, locale, and a JSON body', async (event) => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, event, clientMetadata('zh-CN'))).toBe(true) + expect(f.requests).toEqual([ + { method: 'POST', url: '/api/v0/users/notifications/events', token: 'test-account-token', locale: 'zh_CN', + bundleId: '', platform: 'web', version: '1.2.3', timezoneOffset: '28800', + contentType: 'application/json', body: JSON.stringify({ notification_id: ORDER, type: event }) }, + ]) +}) + +it.each([ + ['the unnotified read', (f: Awaited>) => { + f.failBonuses(0, 401) + return f.account.getNotifications(clientMetadata('en')) + }, null], + ['the acknowledgement', (f: Awaited>) => { + f.failAck(0, 401) + return f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')) + }, false], +])('expires the rejected grant when %s returns HTTP 401', async (_name, run, signedOutOutcome) => { + const f = await fixture() + await f.grant('test-account-token') + const expired = vi.fn() + f.ctx.on('deepseek-account/session-expired', expired) + // A rejected authenticated request names an invalid credential, so the provider drops it locally + // exactly as the profile and balance reads do; the caller sees its signed-out outcome. + expect(await run(f)).toBe(signedOutOutcome) + expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) + expect(expired).toHaveBeenCalledOnce() +}) + +it.each([ + ['read', (f: Awaited>) => f.account.getNotifications(clientMetadata('en')), null], + ['acknowledgement', (f: Awaited>) => + f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en')), false], +])('ignores a bonus %s rejection whose response cleanup overlaps a credential replacement', async (_name, run, outcome) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getProfile(clientMetadata()) + const response = new Response('', { status: 401 }) + const cancel = response.body!.cancel.bind(response.body) + // Credential changes can arrive while the response reader releases a rejected response body. + const cleanup = vi.spyOn(response.body!, 'cancel').mockImplementation(async () => { + await f.grant('replacement-token') + await cancel() + }) + const fetchResponse = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) + const expired = vi.fn() + f.ctx.on('deepseek-account/session-expired', expired) + try { + expect(await run(f)).toBe(outcome) + expect(cleanup).toHaveBeenCalledOnce() + expect(expired).not.toHaveBeenCalled() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) + } finally { cleanup.mockRestore(); fetchResponse.mockRestore() } +}) + +it('retains the grant when an acknowledgement returns HTTP 500', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(0, 500) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))) + .rejects.toThrow('account: network') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it('rejects the supplied NOTIFICATION_NOT_FOUND envelope as a business failure', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(1) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))) + .rejects.toThrow('account: protocol') + expect(f.requests[0]).toMatchObject({ + method: 'POST', url: '/api/v0/users/notifications/events', locale: 'en_US', + contentType: 'application/json', body: JSON.stringify({ notification_id: ORDER, type: 'displayed' }), + }) +}) + +it.each([ + ['a business failure', 1, 200, 'account: protocol'], + ['an HTTP failure', 0, 500, 'account: network'], +])('surfaces %s as a retryable acknowledgement failure', async (_name, bizCode, status, message) => { + const f = await fixture() + await f.grant('test-account-token') + f.failAck(bizCode, status) + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).rejects.toThrow(message) +}) + +it('accepts an acked false response without treating it as a retryable failure', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.acknowledged(false) + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'dismissed', clientMetadata())).toBe(true) + expect(f.requests.map(request => request.url)).toEqual(['/api/v0/users/notifications/events']) + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it('returns signed-out outcomes without any request', async () => { + const f = await fixture() + expect(await f.account.getNotifications(clientMetadata('en'))).toBeNull() + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).toBe(false) + expect(f.requests).toEqual([]) +}) + +it('discards a list response invalidated by a credential change', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.onList(async () => { await f.grant('rotated-token') }) + expect(await f.account.getNotifications(clientMetadata())).toBeNull() + expect(f.requests.map(request => [request.url, request.token])).toEqual([ + ['/api/v0/users/notifications/list', 'test-account-token'], + ]) +}) + +it('queries notifications and reports events while profile data is unavailable', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.failProfile(17, 503) + expect((await f.account.getNotifications(clientMetadata()))?.notifications).toHaveLength(2) + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toMatchObject({ id: ORDER }) + expect(await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata())).toBe(true) + expect(f.requests.map(request => request.url)).toEqual([ + '/api/v0/users/notifications/list', `/api/v0/users/notifications/content?id=${ORDER}`, '/api/v0/users/notifications/events', + ]) +}) + +it('reuses a cached identity for the same credential after a failed query', async () => { + const f = await fixture() + await f.grant('test-account-token') + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + f.failProfile() + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata('en'))).resolves.toBe(true) +}) + +it('queries notifications independently of a profile without a user ID', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.profileId(null) + expect(await f.account.getProfile(clientMetadata())).toMatchObject({ status: 'ready' }) + f.failProfile() + await expect(f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata())).resolves.toBe(true) + expect(f.requests.at(-1)?.url).toBe('/api/v0/users/notifications/events') +}) + +it('reads localized content of a consumed notification without listing or acknowledging it', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.notifications([]) + f.content(wire(ORDER, { title: '产品公告', body: '新功能已上线', actions: [ + { label: '知道了', style: 'secondary', target: { type: 'dismiss' } }, + ] })) + const content = await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata('zh')) + expect(content).toMatchObject({ id: ORDER, title: '产品公告', body: '新功能已上线', + actions: [{ label: '知道了', style: 'secondary', target: { type: 'dismiss' } }] }) + expect(f.requests.map(request => request.url)).toEqual([ + `/api/v0/users/notifications/content?id=${ORDER}`, + ]) + expect(f.requests.at(-1)).toMatchObject({ method: 'GET', token: 'test-account-token', locale: 'zh_CN' }) +}) + +it('does not query notification content while signed out', async () => { + const f = await fixture() + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toBeNull() + expect(f.requests).toEqual([]) +}) + +it.each([ + ['a mismatched ID', wire(SECOND_ORDER)], + ['malformed content', { title: 'private-content' }], +])('rejects %s returned by the content endpoint', async (_name, content) => { + const f = await fixture() + await f.grant('test-account-token') + f.content(content) + await expect(f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())) + .rejects.toThrow('account: protocol') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) +}) + +it.each([401, 500])('handles a content HTTP %s without discarding a usable grant', async (status) => { + const f = await fixture() + await f.grant('test-account-token') + f.failContent(0, status) + const result = f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + if (status === 401) { + expect(await result).toBeNull() + expect(await f.account.getState()).toMatchObject({ status: 'signed-out' }) + } else { + await expect(result).rejects.toThrow('account: network') + expect(await f.account.getState()).toMatchObject({ status: 'credential-stored' }) + } +}) + +it('discards content when the credential changes before its response', async () => { + const f = await fixture() + await f.grant('test-account-token') + f.onContent(async () => { await f.grant('replacement-token') }) + expect(await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata())).toBeNull() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) +}) + +it.each(['list', 'content', 'display'] as const)('discards a successful %s response whose reader cleanup overlaps credential replacement', async (operation) => { + const f = await fixture() + await f.grant('test-account-token') + await f.account.getProfile(clientMetadata()) + const payload = operation === 'list' ? { next_poll_after: 300, notifications: [wire(ORDER)] } : operation === 'content' ? wire(ORDER) : { acked: true } + const response = new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: payload } })) + const body = response.body! + const reader = body.getReader() + const cancel = reader.cancel.bind(reader) + const cleanup = vi.spyOn(reader, 'cancel').mockImplementationOnce(async () => { + await f.grant('replacement-token') + await cancel() + }) + const getReader = vi.spyOn(body, 'getReader').mockReturnValue(reader) + const fetcher = vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(response) + try { + const result = operation === 'list' ? await f.account.getNotifications(clientMetadata()) + : operation === 'content' ? await f.account.getNotificationContent(ORDER as AccountNotificationId, clientMetadata()) + : await f.account.reportNotificationEvent(ORDER as AccountNotificationId, 'displayed', clientMetadata()) + expect(result).toBe(operation === 'display' ? false : null) + expect(cleanup).toHaveBeenCalledOnce() + expect(await f.ctx.credentials.readRecord(f.key)).toMatchObject({ payload: { token: 'replacement-token' } }) + } finally { + fetcher.mockRestore() + getReader.mockRestore() + cleanup.mockRestore() + if (body.locked) { await reader.cancel(); reader.releaseLock() } + } +}) diff --git a/packages/credentials/deepseek-account/tests/origins.spec.ts b/packages/credentials/deepseek-account/tests/origins.spec.ts new file mode 100644 index 0000000000..bd947d88b6 --- /dev/null +++ b/packages/credentials/deepseek-account/tests/origins.spec.ts @@ -0,0 +1,92 @@ +/** Notification destinations are independent of Platform account and browser destinations. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { join } from 'node:path' +import { tmpdir } from 'node:os' +import { afterEach, expect, it, vi } from 'vitest' +import { Context } from '@deepseek-ai/cordis' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import type { AccountNotificationId } from '@deepseek-ai/dsh-deepseek-account' +import { DeepSeekAccount, type Config } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { + while (cleanups.length) await cleanups.pop()!() + vi.restoreAllMocks() +}) + +async function fixture(issuer: string, config: Config = {}) { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-origin-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await ctx.plugin(AuthorizationService) + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token: 'fixture-token', issuer }, + })) + await ctx.plugin(DeepSeekAccount, config) + return ctx.deepseekAccount +} + +it('routes only notification APIs to Harness while account APIs and pages stay on Platform', async () => { + const account = await fixture('https://platform.deepseek.com') + expect(await account.getState()).toMatchObject({ status: 'credential-stored', links: { + usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up', + } }) + expect(await account.getPlatformSession()).toMatchObject({ origin: 'https://platform.deepseek.com', token: 'fixture-token' }) + const id = 'f487920c-a8d5-59b6-90f0-b787adc97980' as AccountNotificationId + const content = { id, created_at: '2026-10-28T06:12:11Z', display_until: null, title: 'News', body: 'Content', actions: [] } + const requests: string[] = [] + vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => { + if (typeof input !== 'string') throw new Error('expected a URL string') + const url = input + requests.push(url) + const path = new URL(url).pathname + const payload = path === '/auth-api/v0/users/current' ? { id: 'account', email: '' } + : path === '/api/v0/users/get_user_summary' ? { normal_wallets: [], bonus_wallets: [] } + : path.endsWith('/list') ? { notifications: [content], next_poll_after: 600 } + : path.endsWith('/content') ? content : { acked: true } + return new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: payload } })) + }) + const client = { version: 'test', locale: 'en', timezoneOffsetSeconds: 0 } + expect(await account.getProfile(client)).toMatchObject({ status: 'ready' }) + expect(await account.getBalance(client)).toMatchObject({ status: 'ready' }) + expect((await account.getNotifications(client))?.notifications[0]?.id).toBe(id) + expect((await account.getNotificationContent(id, client))?.id).toBe(id) + expect(await account.reportNotificationEvent(id, 'dismissed', client)).toBe(true) + expect(requests).toEqual([ + 'https://platform.deepseek.com/auth-api/v0/users/current', + 'https://platform.deepseek.com/api/v0/users/get_user_summary', + 'https://harness.deepseek.com/api/v0/users/notifications/list', + `https://harness.deepseek.com/api/v0/users/notifications/content?id=${id}`, + 'https://harness.deepseek.com/api/v0/users/notifications/events', + ]) +}) + +it('keeps private grants and embedded pages on Platform while allowing a notification origin override', async () => { + const rejected = await fixture('https://platform.deepseek.com', { platformOrigin: 'https://private.example' }) + expect(await rejected.getState()).toMatchObject({ status: 'signed-out' }) + const account = await fixture('https://private.example', { + platformOrigin: 'https://private.example', harnessOrigin: 'https://notifications.example', + requestHeaders: { 'x-deployment': 'base' }, accountRequestHeaders: { 'x-account': 'account' }, + }) + expect(await account.getPlatformSession()).toMatchObject({ + origin: 'https://private.example', token: 'fixture-token', + requestHeaders: { 'x-deployment': 'base', 'x-account': 'account' }, + }) + const fetcher = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { + expect(input).toBe('https://notifications.example/api/v0/users/notifications/list') + expect(init?.headers).toMatchObject({ 'x-deployment': 'base', 'x-account': 'account', 'x-dsh-auth-token': 'fixture-token' }) + return new Response(JSON.stringify({ code: 0, data: { biz_code: 0, biz_data: { notifications: [], next_poll_after: 600 } } })) + }) + await account.getNotifications({ version: 'test', locale: 'en', timezoneOffsetSeconds: 0 }) + expect(fetcher).toHaveBeenCalledOnce() +}) + +it.each(['http://remote.example', 'https://notifications.example/path'])( + 'rejects the invalid notification origin %s during initialization', async (harnessOrigin) => { + await expect(fixture('https://platform.deepseek.com', { harnessOrigin })).rejects.toThrow('harnessOrigin') + }, +) diff --git a/packages/credentials/deepseek-account/tests/remote.spec.ts b/packages/credentials/deepseek-account/tests/remote.spec.ts new file mode 100644 index 0000000000..e33fc547da --- /dev/null +++ b/packages/credentials/deepseek-account/tests/remote.spec.ts @@ -0,0 +1,87 @@ +/** Account Remote exports retain their wire names and exclude Host credentials. */ +import { mkdtemp, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' +import AuthorizationService from '@deepseek-ai/dsh-authorization' +import { LocalCredentialProvider } from '@deepseek-ai/dsh-credentials-local' +import { credentialKey } from '@deepseek-ai/dsh-credentials' +import { remoteMethods } from '@deepseek-ai/dsh-typert-protocol' +import { afterEach, expect, it } from 'vitest' +import { DeepSeekAccount } from '../src/index.ts' + +const cleanups: Array<() => Promise> = [] +afterEach(async () => { while (cleanups.length) await cleanups.pop()!() }) + +async function fixture() { + const home = await mkdtemp(join(tmpdir(), 'dsh-account-remote-')) + cleanups.push(() => rm(home, { recursive: true, force: true })) + const ctx = new Context() + cleanups.push(() => ctx.fiber.dispose()) + await ctx.plugin(LocalCredentialProvider, { path: join(home, 'credentials.yaml'), watch: false }) + await ctx.plugin(AuthorizationService) + const provider = ctx.plugin(DeepSeekAccount) + await provider + return { ctx, account: ctx.deepseekAccount, provider } +} + +it('binds only client-safe operations to the existing account namespace', async () => { + const { account } = await fixture() + expect(account.typertRemote.service instanceof DeepSeekAccount).toBe(true) + expect(account.typertRemote.serviceKey).toBe('deepseekAccount') + expect(account.typertRemote.namespace).toBe('account') + expect(remoteMethods(account).map(method => method.exportName ?? method.method).sort()).toEqual([ + 'cancelSignIn', 'getBalance', 'getNotificationContent', 'getNotifications', 'getProfile', 'getState', + 'hasRunningAccountTasks', 'reportNotificationEvent', 'signOut', 'startSignIn', 'watch', 'watchExpiry', + ]) + expect(remoteMethods(account).filter(method => method.mode === 'stream').map(method => method.exportName ?? method.method).sort()) + .toEqual(['watch', 'watchExpiry']) +}) + +it('streams initial state and credential changes and ends on cancellation', async () => { + const { ctx, account } = await fixture() + const lifetime = new AbortController() + const stream = account.watchState(lifetime.signal)[Symbol.asyncIterator]() + try { + expect(await stream.next()).toMatchObject({ done: false, value: { type: 'snapshot', state: { status: 'signed-out' } } }) + const next = stream.next() + await ctx.credentials.modifyRecord(credentialKey('deepseek-account-platform', 'default'), () => Promise.resolve({ + kind: 'grant', payload: { version: 1, token: 'fixture-token', issuer: 'https://platform.deepseek.com' }, + })) + expect(await next).toMatchObject({ done: false, value: { type: 'credentials-changed', state: { status: 'credential-stored' } } }) + } finally { lifetime.abort() } + expect(await stream.next()).toEqual({ done: true, value: undefined }) +}) + +it('delivers expiry only to current subscribers and stops on disconnect or provider disposal', async () => { + const { ctx, account, provider } = await fixture() + ctx.emit('deepseek-account/session-expired') + const lifetime = new AbortController() + const stream = account.watchExpiry(lifetime.signal)[Symbol.asyncIterator]() + const first = stream.next() + ctx.emit('deepseek-account/session-expired') + expect(await first).toEqual({ done: false, value: 'session-expired' }) + const next = stream.next() + lifetime.abort() + expect(await next).toEqual({ done: true, value: undefined }) + const reopened = account.watchExpiry(new AbortController().signal)[Symbol.asyncIterator]().next() + await provider.dispose() + expect(await reopened).toEqual({ done: true, value: undefined }) +}) + +it('reports running account requests and excludes absent, idle, and other-provider tasks', async () => { + const { ctx, account } = await fixture() + expect(account.hasRunningAccountTasks()).toBe(false) + const active: Array> = [] + const task = (status: Agent['status'], provider?: string): Pick => ({ + status, session: { requestContext: () => provider === undefined ? undefined : { provider, model: 'model' } } as Agent['session'], + }) + ctx.provide('agents', { list: () => active } as Context['agents']) + active.push(task('running'), task('running', 'deepseek-official'), task('idle', 'deepseek-account')) + expect(account.hasRunningAccountTasks()).toBe(false) + active.push(task('running', 'deepseek-account')) + expect(account.hasRunningAccountTasks()).toBe(true) + active.pop() + expect(account.hasRunningAccountTasks()).toBe(false) +}) diff --git a/packages/credentials/deepseek-account/tsconfig.json b/packages/credentials/deepseek-account/tsconfig.json index a0da11ddaa..e4add1d675 100644 --- a/packages/credentials/deepseek-account/tsconfig.json +++ b/packages/credentials/deepseek-account/tsconfig.json @@ -22,6 +22,21 @@ }, { "path": "../../llm/llm" + }, + { + "path": "../authorization" + }, + { + "path": "../credentials" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../host/webserver" + }, + { + "path": "../../typert/protocol" } ] } diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index 8419dfbb18..a868012bd6 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -82,12 +82,13 @@ export const VIEWER_ENDPOINT_CLASSES = { // No reader role names these, so the conservative class is owner-only. A share's method policy // decides whether one installed plugin's method reaches its viewers; this table only decides what // the core share roles grant. - 'account/ackBonusNotified': 'owner-only', // owner account and sign-in; the served page never reads it 'account/cancelSignIn': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getBalance': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getProfile': 'owner-only', // owner account and sign-in; the served page never reads it 'account/getState': 'owner-only', // owner account and sign-in; the served page never reads it - 'account/getUnnotifiedBonuses': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/getNotificationContent': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/getNotifications': 'owner-only', // owner account and sign-in; the served page never reads it + 'account/reportNotificationEvent': 'owner-only', // owner account and sign-in; the served page never reads it 'account/hasRunningAccountTasks': 'owner-only', // owner account and sign-in; the served page never reads it 'account/signOut': 'owner-only', // owner account and sign-in; the served page never reads it 'account/startSignIn': 'owner-only', // owner account and sign-in; the served page never reads it diff --git a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts index 4feed9d4e0..c8fb3ad8a9 100644 --- a/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts +++ b/packages/experimental/liveshare/tests/viewer-access-policy.spec.ts @@ -408,7 +408,8 @@ describe('viewer page startup contract', () => { it('keeps the owner’s own surfaces refused and out of the reader’s snapshot', async () => { const { decide, grants } = await fixture() - const ownerOnly = ['account/watch', 'job/list', 'job/follow', 'settings/describe', + const ownerOnly = ['account/watch', 'account/getNotifications', 'account/getNotificationContent', 'account/reportNotificationEvent', + 'job/list', 'job/follow', 'settings/describe', 'credentials/describe', 'pluginManager/listPlugins', 'schedule/catalog', 'schedule/create', 'schedule/deliveryLimits', 'schedule/deleteInactive', 'schedule/edit', 'schedule/history', 'schedule/list', 'schedule/run', 'schedule/view', 'agentTeams/setEnabled'] as const 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 e581bb7f86..41f4010684 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -3508,7 +3508,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ doc: 'Optional sidebar account launcher; opens the shell-owned settings panel.', registerOptions: [], ownerProps: [ - '/** Sidebar launcher geometry and settings navigation. */\nexport interface SettingsLauncherOwnerProps {\n /** Whether the sidebar shows labels. */\n wide: boolean\n /** Whether the settings dialog covers the sidebar; a launcher may treat a false-to-true edge as one Settings entry. */\n settingsOpen: boolean\n /** Effective Settings key labels and accessible combination; omitted when unbound. */\n settingsShortcut?: { readonly keys: readonly string[]; readonly aria?: string | undefined }\n /** Open the settings panel. */\n openSettings: () => void\n /** @param id - registered onboarding editor to open explicitly. */\n openOnboarding: (id: string) => void\n}', + '/** Sidebar launcher geometry and settings navigation. */\nexport interface SettingsLauncherOwnerProps {\n /** Whether the sidebar shows labels. */\n wide: boolean\n /** Whether the settings dialog covers the sidebar; a launcher may treat a false-to-true edge as one Settings entry. */\n settingsOpen: boolean\n /** Effective Settings key labels and accessible combination; omitted when unbound. */\n settingsShortcut?: { readonly keys: readonly string[]; readonly aria?: string | undefined }\n /** @param sectionId - section to open; absent uses the shell\'s default section. */\n openSettings: (sectionId?: string) => void\n /** @param id - registered onboarding editor to open explicitly. */\n openOnboarding: (id: string) => void\n}', ], ownerPropsReferences: [], standardProps: [ @@ -3534,6 +3534,40 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.launcher\', () => ctx.slots.register(\n { name: \'settings.launcher\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', source: 'packages/client/ui-settings/src/client/contract/slots.ts:17', }, + { + key: 'settings.launcher.notifications', + kind: 'single', + scope: 'root', + summary: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', + doc: 'Notifications anchored at the account menu; the contribution owns its markup and lifecycle.', + registerOptions: [], + ownerProps: [ + '/** Account-menu presentation facts supplied to its notification extension. */\nexport interface AccountNotificationsOwnerProps {\n /** Whether the account menu can display notifications outside onboarding. */\n active: boolean\n /** Open the account section in the existing settings shell. */\n openAccount: () => void\n}', + ], + ownerPropsReferences: [], + standardProps: [ + 'useRemoteAccess: (action: RemoteEndpoint) => boolean', + 'useResource: UseResource', + 'useContextMenu: UseContextMenu', + 'useWorkspaces: SnapshotSelectorHook', + 'usePanelInfo: UsePanelInfo', + 'useSessions: UseSessions', + 'useSessionStatus: UseSessionStatus', + 'useSessionRetainInfo: UseSessionRetainInfo', + 'useSessionAccess: (sessionId: SessionId, action: RemoteEndpoint) => boolean', + 'useWorkspaceAccess: (workspaceId: WorkspaceId, action: RemoteEndpoint) => boolean', + ], + keyDomain: '', + hookContext: '', + slotInject: '', + declaredBy: 'an entry in \'settings.launcher\' (client-ui-settings-account), so it exists while that entry is mounted', + occupants: [ + 'client-ui-account-notifications AccountNotifications', + ], + replaceRisk: 'shadows-shipped-ui', + example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'settings.launcher.notifications\', () => ctx.slots.register(\n { name: \'settings.launcher.notifications\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', + source: 'packages/client/ui-settings-account/src/client/account-ui.ts:47', + }, { key: 'settings.models.footer', kind: 'list', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 704d2670df..0ac2e9e122 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -978,86 +978,110 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { key: 'deepseekAccount', - summary: 'Account operations; only Host consumers can obtain a request credential.', - description: 'Account operations; only Host consumers can obtain a request credential.', + summary: 'Account login, credentials, and client-safe Remote operations.', + description: 'Account login, credentials, and client-safe Remote operations.', methods: [ { - signature: 'abstract getState(): Promise', + signature: '@Remote async getState(): Promise', description: 'Read stored-account presence and the latest login attempt.', parameters: [], returns: 'a snapshot without credentials or PKCE secrets.', }, { - signature: 'abstract getProfile(client: AccountClientMetadata): Promise', + signature: '@Remote async getProfile(client: AccountClientMetadata): Promise', description: 'Query Platform profile independently of wallet balances. A ready result whose stable profile ID first becomes available or changes notifies identity-enabled watch consumers, so they re-read getPlatformSession; repeated IDs stay silent.', parameters: [{ name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'profile outcome, or null if signed out or the grant changed during the query.', }, { - signature: 'abstract getBalance(client: AccountClientMetadata): Promise', + signature: '@Remote getBalance(client: AccountClientMetadata): Promise', description: 'Query Platform recharge and bonus wallet balances independently of profile data.', parameters: [{ name: 'client', description: 'identity of the requesting UI for this call.' }], returns: 'balance outcome, or null if signed out or the grant changed during the query.', }, { - signature: 'abstract getUnnotifiedBonuses(client: AccountClientMetadata): Promise', - description: 'Query the granted bonuses Platform has not yet recorded as displayed.', + signature: '@Remote async getNotifications(client: AccountClientMetadata): Promise', + description: 'Query unconsumed account notifications in server order without reading profile data.', parameters: [{ name: 'client', description: 'identity of the requesting UI for this call; its language selects the server-authored message.' }], - returns: 'bonuses with their account, or null if signed out or the grant changed during the query.', + returns: 'notifications with their next query delay, or null if signed out or the grant changed during the query.', }, { - signature: 'abstract ackBonusNotified(accountId: AccountUserId, orderId: AccountBonusOrderId, client: AccountClientMetadata): Promise', - description: 'Record one displayed bonus as notified for the account it belongs to.', - parameters: [{ name: 'accountId', description: 'account the notification was read for; a different current account is never acknowledged.' }, { name: 'orderId', description: 'granted bonus order the user saw.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }], - returns: 'true once Platform records the acknowledgement; false if signed out or the account changed.', + signature: '@Remote async getNotificationContent(id: AccountNotificationId, client: AccountClientMetadata): Promise', + description: 'Query localized content of a notification, including one already consumed.', + parameters: [{ name: 'id', description: 'notification whose content is requested.' }, { name: 'client', description: 'identity of the requesting UI; its language selects the localized content.' }], + returns: 'content without changing consumption, or null if signed out or the grant changed.', }, { - signature: 'abstract startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', - description: 'Join an active attempt or start browser authorization.', - parameters: [{ name: 'client', description: 'identity of the requesting UI; a new attempt captures it, and joining retains the original attempt\'s identity.' }, { name: 'callbackOrigin', description: 'browser-accessible loopback HTTP origin, including any SSH local port.' }, { name: 'loginSource', description: 'initiating UI, used to return from a failed exchange.' }], - returns: 'the initial snapshot without waiting for browser approval.', + signature: '@Remote async reportNotificationEvent(id: AccountNotificationId, event: AccountNotificationEvent, client: AccountClientMetadata): Promise', + description: 'Report a notification interaction; the backend decides consumption.', + parameters: [{ name: 'id', description: 'notification the user interacted with.' }, { name: 'event', description: 'displayed frame, non-dismiss action click, or explicit dismissal.' }, { name: 'client', description: 'identity of the requesting UI for this call.' }], + returns: 'true once the server accepts the event; false if signed out or credentials changed during the call.', }, { - signature: 'abstract cancelSignIn(id: SignInAttemptId): Promise', - description: 'Cancel only the named attempt; committing attempts settle before returning.', - parameters: [{ name: 'id', description: 'attempt identity from this Host.' }], - returns: 'state after cancellation or an already-started commit.', - }, - { - signature: 'abstract signOut(client: AccountClientMetadata): Promise', - description: 'Remove the local grant while retaining API keys; the provider revokes it in the background.', - parameters: [{ name: 'client', description: 'identity of the requesting UI, captured for the background revocation retries.' }], - returns: 'the signed-out state after local removal; remote failures never restore the grant.', - }, - { - signature: 'abstract watch(signal: AbortSignal, includeIdentityChanges?: boolean): AsyncIterable', - description: 'Subscribe to snapshots including a complete initial state.', - parameters: [{ name: 'signal', description: 'subscription lifetime; ending it never cancels login.' }, { name: 'includeIdentityChanges', description: 'also notify when cached Platform identity changes; defaults to false.' }], - returns: 'complete snapshots as account state changes.', - }, - { - signature: 'abstract resolveToken(url: string): Promise', - description: 'Resolve a credential only for the inference origin allowed by the provider.', - parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], - returns: 'stored token, or undefined for other origins or a signed-out account.', - }, - { - signature: 'abstract rejectToken(token: string): Promise', + signature: 'async rejectToken(token: string): Promise', description: 'Remove an inference-rejected token only while it still matches the stored login.', parameters: [{ name: 'token', description: 'token captured by the rejected inference request.' }], returns: 'after matching credentials are removed and the expiry notification is emitted.', }, { - signature: 'abstract getPlatformSession(): Promise', - description: 'Read credentials for the configured Platform origin, bound to their issuing environment, and pair them with the account ID from the last successful profile read; no profile request is made.', + signature: 'async getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', + description: 'Read existing login identity without creating a device or returning credentials.', + parameters: [], + returns: 'optional device/account identifiers and the provider\'s OS version string.', + }, + { + signature: 'async getPlatformSession(): Promise', + description: 'Read credentials for the configured embedded-page origin, bound to their account environment, and pair them with the account ID from the last successful profile read; no profile request is made.', parameters: [], returns: 'a Host-only snapshot, or null while signed out or when the credential changed during the read.', }, { - signature: 'abstract getDeviceIdentity(): Promise<{ deviceId?: string; userId?: AccountUserId; osVersion: string }>', - description: 'Read existing login identity without creating a device or returning credentials.', + signature: 'async resolveToken(url: string): Promise', + description: 'Resolve a credential only for the inference origin allowed by the provider.', + parameters: [{ name: 'url', description: 'actual request destination or API base URL.' }], + returns: 'stored token, or undefined for other origins or a signed-out account.', + }, + { + signature: '@Remote async startSignIn(client: AccountClientMetadata, callbackOrigin: string, loginSource: \'web\' | \'desktop\'): Promise', + description: 'Join an active attempt or start browser authorization.', + parameters: [{ name: 'client', description: 'identity of the requesting UI; a new attempt captures it, and joining retains the original attempt\'s identity.' }, { name: 'callbackOrigin', description: 'browser-accessible loopback HTTP origin, including any SSH local port.' }, { name: 'loginSource', description: 'initiating UI, used to return from a failed exchange.' }], + returns: 'the initial snapshot without waiting for browser approval.', + }, + { + signature: '@Remote async cancelSignIn(attemptId: SignInAttemptId): Promise', + description: 'Cancel only the named attempt; committing attempts settle before returning.', + parameters: [{ name: 'attemptId', description: 'attempt identity from this Host.' }], + returns: 'state after cancellation or an already-started commit.', + }, + { + signature: '@Remote signOut(client: AccountClientMetadata): Promise', + description: 'Remove the local grant while retaining API keys; the provider revokes it in the background.', + parameters: [{ name: 'client', description: 'identity of the requesting UI, captured for the background revocation retries.' }], + returns: 'the signed-out state after local removal; remote failures never restore the grant.', + }, + { + signature: '@Remote hasRunningAccountTasks(): boolean', + description: 'Inspect running work before sign-out.', parameters: [], - returns: 'optional device/account identifiers and the provider\'s OS version string.', + returns: 'whether a running task\'s latest request uses the account route; false when the optional agents service is absent.', + }, + { + signature: '@Remote({ mode: \'stream\' }) async *watchExpiry(signal: AbortSignal): AsyncIterable<\'session-expired\'>', + description: 'Subscribe to live credential expiry without replay.', + parameters: [{ name: 'signal', description: 'subscription lifetime; provider disposal also ends it.' }], + returns: 'expiry notifications emitted during the subscription.', + }, + { + signature: 'watch(signal: AbortSignal, includeIdentityChanges: boolean = false): AsyncIterable', + description: 'Subscribe to ordered updates including a complete initial snapshot.', + parameters: [{ name: 'signal', description: 'subscription lifetime; ending it never cancels login.' }, { name: 'includeIdentityChanges', description: 'also notify when cached Platform identity changes; defaults to false.' }], + returns: 'complete state with snapshot or credentials-changed event type; credential changes take priority when updates coalesce.', + }, + { + signature: '@Remote({ name: \'watch\', mode: \'stream\' }) watchState(signal: AbortSignal): AsyncIterable', + description: 'Stream account state without the Host-only identity subscription option.', + parameters: [{ name: 'signal', description: 'subscription lifetime.' }], + returns: 'initial state, login progress, and credential-change updates.', }, ], }, @@ -5550,18 +5574,6 @@ export const EVENT_API: readonly EventApiEntry[] = [ /** Shapes of every exported type the Service and Event signatures reference (transitively), sorted by name. */ export const TYPE_API: readonly TypeApiEntry[] = [ - { - name: 'AccountBonusBatch', - declaration: 'export interface AccountBonusBatch {\n readonly accountId: AccountUserId;\n readonly bonuses: readonly AccountBonusNotification[];\n}', - }, - { - name: 'AccountBonusNotification', - declaration: 'export interface AccountBonusNotification {\n readonly title?: string;\n readonly orderId: AccountBonusOrderId;\n readonly campaign?: JsonValue;\n readonly amount?: JsonValue;\n readonly currency?: JsonValue;\n readonly grantedAt?: JsonValue;\n readonly expiresAt: string;\n readonly message: string;\n}', - }, - { - name: 'AccountBonusOrderId', - declaration: 'export type AccountBonusOrderId = Branded<\'AccountBonusOrderId\'>;', - }, { name: 'AccountClientMetadata', declaration: 'export interface AccountClientMetadata {\n readonly version: string;\n readonly locale: string;\n readonly timezoneOffsetSeconds: number;\n}', @@ -5574,10 +5586,34 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'AccountLinks', declaration: 'export interface AccountLinks {\n readonly usageUrl: string;\n readonly topUpUrl: string;\n}', }, + { + name: 'AccountNotification', + declaration: 'export interface AccountNotification {\n readonly id: AccountNotificationId;\n readonly createdAt: string;\n readonly displayUntil: string | null;\n readonly title: string;\n readonly body: string;\n readonly actions: readonly AccountNotificationAction[];\n readonly data?: JsonValue;\n}', + }, + { + name: 'AccountNotificationAction', + declaration: 'export interface AccountNotificationAction {\n readonly label: string;\n readonly style: \'primary\' | \'secondary\';\n readonly target: {\n readonly type: \'app_route\';\n readonly name: \'account\';\n } | {\n readonly type: \'dismiss\';\n };\n}', + }, + { + name: 'AccountNotificationBatch', + declaration: 'export interface AccountNotificationBatch {\n readonly nextPollAfterSeconds: number;\n readonly notifications: readonly AccountNotification[];\n}', + }, + { + name: 'AccountNotificationEvent', + declaration: 'export type AccountNotificationEvent = \'displayed\' | \'cta_clicked\' | \'dismissed\';', + }, + { + name: 'AccountNotificationId', + declaration: 'export type AccountNotificationId = Branded<\'AccountNotificationId\'>;', + }, { name: 'AccountProfile', declaration: 'export interface AccountProfile {\n readonly id: AccountUserId | null;\n readonly name: string | null;\n readonly contact: string | null;\n readonly avatarUrl?: string | null;\n}', }, + { + name: 'AccountUpdate', + declaration: 'export interface AccountUpdate {\n readonly type: \'snapshot\' | \'credentials-changed\';\n readonly state: AccountView;\n}', + }, { name: 'AccountUserId', declaration: 'export type AccountUserId = Branded<\'AccountUserId\'>;', diff --git a/packages/llm/llm-deepseek/README.i18n.yaml b/packages/llm/llm-deepseek/README.i18n.yaml index 2c756e7492..90547d2b5c 100644 --- a/packages/llm/llm-deepseek/README.i18n.yaml +++ b/packages/llm/llm-deepseek/README.i18n.yaml @@ -27,8 +27,8 @@ en: 559f2a1b85de8d42 zh: 08af2386b3e9ecbd /deepseek-ai-dsh-llm-deepseek/use-this-package/account-credentials: - en: 941f9e4b138a7f6e - zh: b868228c57fbcc87 + en: d3f232309f4963ef + zh: 2e0ccd028de26f3e /deepseek-ai-dsh-llm-deepseek/use-this-package/streaming-with-thinking-and-images: en: 81bf213499f015ba zh: e9107ef322213e56 @@ -87,5 +87,5 @@ en: 05fe57d81d8d8202 zh: 61e85a6f610842dd /deepseek-ai-dsh-llm-deepseek/known-limitations-and-deferred-work/dev-note: - en: fc7d8c8a6258331a + en: 267aab8281b59242 zh: 491b454fe920a17e diff --git a/packages/llm/llm-deepseek/README.md b/packages/llm/llm-deepseek/README.md index 85439d5875..88125ab26d 100644 --- a/packages/llm/llm-deepseek/README.md +++ b/packages/llm/llm-deepseek/README.md @@ -87,9 +87,9 @@ Messages sends text, thinking, tool calls, and tool results as content blocks, r ### Account credentials -`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account provider](../../credentials/deepseek-account-platform/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. +`deepseek-official` resolves only its configured API-key reference. `deepseek-account` resolves only the stored grant from the [account service](../../credentials/deepseek-account/README.md), whose allowed `inferenceOrigin` defaults to `https://api.deepseek.com`. Neither route falls back to the other. Signing out removes the account grant and preserves API keys. -Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account provider owns HTTP 401 classification and credential invalidation; the transport passes failures to its callback. +Messages and Files requests send account tokens as `x-dsh-auth-token` without a Bearer prefix; API keys use `x-api-key`. Neither credential mode follows redirects. The account service owns HTTP 401 classification and credential invalidation; the transport passes failures to its callback. The [shared credential helpers](src/credential.ts) serve model routes and web providers without choosing request headers. `resolveDeepSeekApiKey(ctx, ref)` returns a normalized, validated key or `undefined`; an installed credentials service is authoritative, and only its absence enables launch-environment lookup. Store and key-format failures propagate. `deepSeekApiKeyConfigured(ctx, ref)` checks presence without reading stored key values. Account helpers delegate allowed-destination resolution and exact-token invalidation to the account service; invalidation contains storage failures so the original request error remains visible. @@ -218,4 +218,4 @@ These limits define where the adapter stops and future work begins. They are cur None. -`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account provider owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal. +`deepseek-official` uses only its configured API-key reference; `deepseek-account` uses only the stored DSH grant for the account provider’s allowed inference origin. Both routes share the Messages transport with independently configured model and file settings. Missing or ineligible account credentials reject the request with a sign-in prompt; neither route falls back to the other. Chat and Files requests reject redirects. The account service owns sign-out cancellation using running Agents’ logged request contexts, including tool execution; the transport receives the existing request abort signal. diff --git a/packages/llm/llm-deepseek/README.zh.md b/packages/llm/llm-deepseek/README.zh.md index e7f5974fb5..a8fba1d16c 100644 --- a/packages/llm/llm-deepseek/README.zh.md +++ b/packages/llm/llm-deepseek/README.zh.md @@ -87,9 +87,9 @@ Messages 以内容块发送文本、思考、工具调用和工具结果,以 ` ### 账号凭据 -`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号提供者](../../credentials/deepseek-account-platform/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 +`deepseek-official` 仅解析配置的 API Key 引用。`deepseek-account` 仅解析[账号服务](../../credentials/deepseek-account/README.zh.md)保存的授权,其允许的 `inferenceOrigin` 默认为 `https://api.deepseek.com`。两条路由均不回退到另一凭证。退出登录删除账号授权,保留 API Key。 -Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号 provider 负责 HTTP 401 分类和凭据失效处理;传输层将错误交给其回调。 +Messages 和 Files 请求通过 `x-dsh-auth-token` 发送账号 token,不加 Bearer 前缀;API Key 使用 `x-api-key`。两种凭据模式均拒绝重定向。账号服务负责 HTTP 401 分类和凭据失效处理;传输层将错误交给其回调。 [共享凭据函数](src/credential.ts)为模型路由和 Web 提供方获取凭据,不决定请求头。`resolveDeepSeekApiKey(ctx, ref)` 返回规范化并校验后的密钥或 `undefined`;已安装的凭据服务具有权威性,仅在该服务缺席时读取启动环境。存储与密钥格式错误向上传播。`deepSeekApiKeyConfigured(ctx, ref)` 检查是否存在,不读取已存密钥值。账号函数将目标地址许可检查和精确 token 作废交给账号服务;作废时隔离存储失败,保留原请求错误。 diff --git a/packages/llm/llm-deepseek/tests/account-routing.spec.ts b/packages/llm/llm-deepseek/tests/account-routing.spec.ts index 7bcb3774b4..4a6cd8ddb8 100644 --- a/packages/llm/llm-deepseek/tests/account-routing.spec.ts +++ b/packages/llm/llm-deepseek/tests/account-routing.spec.ts @@ -1,7 +1,8 @@ /** Account route cancellation uses the real loop, registry, and tool lifecycle. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' import { afterEach, expect, it, vi } from 'vitest' -import { installAccountTaskCancellation, type DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' import { Context } from '@deepseek-ai/cordis' import LlmRuntime, { createUserMessage, LlmAdapter, type GenerateOptions, type StreamChunk, ToolCallId } from '@deepseek-ai/dsh-llm' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' diff --git a/packages/llm/llm-deepseek/tests/adapter.spec.ts b/packages/llm/llm-deepseek/tests/adapter.spec.ts index ea30717e92..9629892f70 100644 --- a/packages/llm/llm-deepseek/tests/adapter.spec.ts +++ b/packages/llm/llm-deepseek/tests/adapter.spec.ts @@ -1,6 +1,7 @@ /** HTTP lifecycle, routing and optional Cordis services under real composition. */ import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' -import { installAccountTaskCancellation, type DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import type { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account' +import { installAccountTaskCancellation } from '@deepseek-ai/dsh-deepseek-account/src/account-tasks.ts' import type { AnonymousUserId } from '@deepseek-ai/dsh-anonymous-user-id' import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 2d428212b6..489d3c98ce 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -14,7 +14,6 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | Package | Config | Description | |---|---|---| -| `@deepseek-ai/dsh-api-account-controller` | no | Expose safe account operations over authenticated Remote | | `@deepseek-ai/dsh-api-gateway` | yes | Typert Remote Host dispatcher and Client API endpoint | | `@deepseek-ai/dsh-api-job-controller` | yes | Job Remote observation stream and the reference-counted client job-output service | | `@deepseek-ai/dsh-api-remote-access` | no | Method-level Remote access control for non-owner Peers and the per-Peer access snapshot | @@ -67,6 +66,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-product-analytics` | yes | Desktop product event collection and authenticated Host reporting | | `@deepseek-ai/dsh-client-resources` | no | Unified client resource model: protocol-registered providers turn URL addresses into live values, consumed through the useResource global standard hook | | `@deepseek-ai/dsh-client-shortcuts` | yes | Application keyboard command registry and physical-key routing | +| `@deepseek-ai/dsh-client-ui-account-notifications` | yes | Display account notifications and refresh localized content | | `@deepseek-ai/dsh-client-ui-agent-preset` | no | Agent-preset surfaces: the default for later sessions, this session's seat, and the composition editor | | `@deepseek-ai/dsh-client-ui-agent-team` | no | Web shared task board for a subagent tree | | `@deepseek-ai/dsh-client-ui-approval` | no | Approval composer takeover over the scoped Remote Event waterfall | @@ -171,7 +171,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo |---|---|---| | `@deepseek-ai/dsh-authorization` | no | Authorization seam (ctx.authorization): plugin-owned flows that obtain a credential through a conversation with the human | | `@deepseek-ai/dsh-credentials-local` | yes | File-backed credentials provider ($DSH_HOME/.env under the live process environment) for the DeepSeek Harness | -| `@deepseek-ai/dsh-deepseek-account-platform` | yes | Authorize DeepSeek accounts through browser PKCE | +| `@deepseek-ai/dsh-deepseek-account` | yes | Sign in to DeepSeek and manage account credentials and notifications | ## deliverables 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 4f7270d8cd..f43eae5217 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 @@ -40,8 +40,9 @@ export const remoteDefaultResponses: RemoteTable = { 'account/getProfile': ok(null), 'account/getBalance': ok(null), // ui-settings-account bonus notice read and acknowledgement at signing in. - 'account/getUnnotifiedBonuses': ok(null), - 'account/ackBonusNotified': ok(true), + 'account/getNotifications': ok(null), + 'account/getNotificationContent': ok(null), + 'account/reportNotificationEvent': ok(true), }, // Stream endpoints the roster opens later than boot; declared so a spec that forgets the script gets a stream miss. streams: [ @@ -52,7 +53,7 @@ export const remoteDefaultResponses: RemoteTable = { // api-session-controller client `apply`: the control stream's opening baseline, then open. 'session/control': openStream([{ type: 'baseline', value: { projections: {} } }]), // ui-settings-account shares the account snapshot across settings and the sidebar menu. - 'account/watch': openStream([{ status: 'signed-out', attempt: null, links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } }]), + 'account/watch': openStream([{ type: 'snapshot', state: { status: 'signed-out', attempt: null, links: { usageUrl: 'https://platform.deepseek.com/usage', topUpUrl: 'https://platform.deepseek.com/top_up' } } }]), // api-workspace-controller client `apply`: the follow stream's opening baseline, then open. 'workspace/follow': openStream([{ type: 'baseline', value: { items: [], archivedSessionIds: [], pinnedSessionIds: [] } }]), // api-remote-access client `mountAccess`: the owner's access snapshot, then open. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..b48c3c87c1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1308,25 +1308,6 @@ importers: specifier: workspace:* version: link:../../interaction/user-approval - packages/api/account-controller: - dependencies: - zod: - specifier: 4.6.6 - version: 4.6.6 - devDependencies: - '@deepseek-ai/cordis': - specifier: workspace:~ - version: link:../../../vendor/cordis - '@deepseek-ai/dsh-agent': - specifier: workspace:* - version: link:../../core/agent - '@deepseek-ai/dsh-deepseek-account': - specifier: workspace:* - version: link:../../credentials/deepseek-account - '@deepseek-ai/dsh-typert-protocol': - specifier: workspace:* - version: link:../../typert/protocol - packages/api/gateway: dependencies: '@deepseek-ai/dsh-deque': @@ -1471,9 +1452,6 @@ importers: '@deepseek-ai/dsh-agent-team': specifier: workspace:* version: link:../../team/agent-team - '@deepseek-ai/dsh-api-account-controller': - specifier: workspace:* - version: link:../account-controller '@deepseek-ai/dsh-api-gateway': specifier: workspace:* version: link:../gateway @@ -2446,9 +2424,9 @@ importers: '@deepseek-ai/dsh-credentials-local': specifier: workspace:* version: link:../../credentials/credentials-local - '@deepseek-ai/dsh-deepseek-account-platform': + '@deepseek-ai/dsh-deepseek-account': specifier: workspace:* - version: link:../../credentials/deepseek-account-platform + version: link:../../credentials/deepseek-account '@deepseek-ai/dsh-deepseek-llm-api-extensions': specifier: workspace:* version: link:../../llm/deepseek-llm-api-extensions @@ -2942,9 +2920,6 @@ importers: '@deepseek-ai/dsh-agent-tool-presentation': specifier: workspace:* version: link:../../core/agent-tool-presentation - '@deepseek-ai/dsh-api-account-controller': - specifier: workspace:* - version: link:../../api/account-controller '@deepseek-ai/dsh-api-job-controller': specifier: workspace:* version: link:../../api/job-controller @@ -2993,6 +2968,9 @@ importers: '@deepseek-ai/dsh-client-shortcuts': specifier: workspace:* version: link:../../client/shortcuts + '@deepseek-ai/dsh-client-ui-account-notifications': + specifier: workspace:* + version: link:../../client/ui-account-notifications '@deepseek-ai/dsh-client-ui-agent-preset': specifier: workspace:* version: link:../../client/ui-agent-preset @@ -3706,6 +3684,52 @@ importers: specifier: ~4.5.7 version: 4.5.7(@types/react@18.3.31)(immer@10.2.0)(react@18.3.1) + packages/client/ui-account-notifications: + dependencies: + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-api-remotes': + specifier: workspace:* + version: link:../../api/remotes + '@deepseek-ai/dsh-client-locale': + specifier: workspace:* + version: link:../locale + '@deepseek-ai/dsh-client-test-runtime': + specifier: workspace:* + version: link:../../test-support/client-runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:* + version: link:../ui-primitives + '@deepseek-ai/dsh-client-ui-renderer': + specifier: workspace:* + version: link:../ui-renderer + '@deepseek-ai/dsh-client-ui-settings-account': + specifier: workspace:* + version: link:../ui-settings-account + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:* + version: link:../ui-slots + '@deepseek-ai/dsh-deepseek-account': + specifier: workspace:* + version: link:../../credentials/deepseek-account + '@deepseek-ai/dsh-host-webserver': + specifier: workspace:* + version: link:../../host/webserver + '@testing-library/react': + specifier: ^16.3.3 + version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + react: + specifier: ^18.2.0 + version: 18.3.1 + react-dom: + specifier: ^18.2.0 + version: 18.3.1(react@18.3.1) + packages/client/ui-agent-preset: devDependencies: '@deepseek-ai/cordis': @@ -8180,24 +8204,6 @@ importers: version: link:../../util/launch-environment packages/credentials/deepseek-account: - devDependencies: - '@deepseek-ai/cordis': - specifier: workspace:~ - version: link:../../../vendor/cordis - '@deepseek-ai/dsh-agent': - specifier: workspace:* - version: link:../../core/agent - '@deepseek-ai/dsh-brand': - specifier: workspace:* - version: link:../../util/brand - '@deepseek-ai/dsh-llm': - specifier: workspace:* - version: link:../../llm/llm - '@deepseek-ai/dsh-util-values': - specifier: workspace:* - version: link:../../util/values - - packages/credentials/deepseek-account-platform: dependencies: '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery @@ -8209,18 +8215,30 @@ importers: '@deepseek-ai/cordis': specifier: workspace:~ version: link:../../../vendor/cordis + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent '@deepseek-ai/dsh-authorization': specifier: workspace:* version: link:../authorization + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand '@deepseek-ai/dsh-credentials': specifier: workspace:* version: link:../credentials - '@deepseek-ai/dsh-deepseek-account': - specifier: workspace:* - version: link:../deepseek-account '@deepseek-ai/dsh-host-webserver': specifier: workspace:* version: link:../../host/webserver + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-typert-protocol': + specifier: workspace:* + version: link:../../typert/protocol + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values packages/deliverables/deliverable-file-references: devDependencies: diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 47b3d5fa86..9e5119387d 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -205,6 +205,7 @@ export const SERVICE_WALK_EXEMPTIONS: Record = { commandUi: 'client-side interface-typed browser service — packages/client/ui-commands/README.md owns the API', fileDrag: 'client-side file preparation and transfer service — packages/client/ui-file-drag/README.md owns the API', feedbackUi: 'client-side feedback dialog service — packages/client/ui-message-feedback/README.md owns the API', + accountUi: 'client-side shared account state — packages/client/ui-settings-account/README.md owns the API', conversation: 'client-side interface-typed browser service — packages/client/ui-conversation/README.md owns the API', layout: 'client-side interface-typed browser service — packages/client/ui-layout/README.md owns the API', pluginNavigation: 'client-side bundle navigation — packages/client/ui-plugin-manager/README.md owns the API', @@ -285,6 +286,8 @@ export const EVENT_SCOPE_PAGE: Record = { * exemption cannot mask another declaration in that scope. */ export const EVENT_WALK_EXEMPTIONS: Record = { + 'account-ui/change': 'client-side account lifecycle signal — packages/client/ui-settings-account/README.md owns the API', + 'account-ui/refresh': 'client-side account refresh signal — packages/client/ui-settings-account/README.md owns the API', 'workspace/archive-notice': 'client-face archive follow-up copy — packages/client/ui-workspace/README.md owns the API', 'workspace/archive-followup-failed': 'client-face archive follow-up failure — packages/client/ui-workspace/README.md owns the API', 'workspace/archive-followup-settled': 'client-face archive follow-up settlement — packages/client/ui-workspace/README.md owns the API', @@ -876,10 +879,14 @@ export const LINK_MAP: Readonly> = { AuthorizationNotice: 'credentials.md', AuthorizationOutcome: 'credentials.md', AccountView: 'credentials.md', + AccountUpdate: 'credentials.md', AccountDetails: 'credentials.md', AccountClientMetadata: 'credentials.md', - AccountBonusBatch: 'credentials.md', - AccountBonusOrderId: 'credentials.md', + AccountNotificationBatch: 'credentials.md', + AccountNotificationId: 'credentials.md', + AccountNotification: 'credentials.md', + AccountNotificationAction: 'credentials.md', + AccountNotificationEvent: 'credentials.md', AccountUserId: 'credentials.md', PlatformSession: 'credentials.md', SignInAttemptId: 'credentials.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 5340a41c87..6643bd5b44 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -493,9 +493,9 @@ const SERVICE_ROLES: ServiceRole[] = [ key: 'deepseekAccount', pkg: 'deepseek-account', title: 'DeepSeek account', - mode: 'seam', - implementations: ['deepseek-account-platform'], - consumers: ['api-account-controller', 'llm-deepseek'], + mode: 'service', + implementations: [], + consumers: ['llm-deepseek'], note: 'The Host owns browser authorization and local credentials; UI consumers receive state without tokens.', }, { diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts index 82df732cf6..70a12fd14b 100644 --- a/scripts/plugin-entry-existing-exports.ts +++ b/scripts/plugin-entry-existing-exports.ts @@ -60,7 +60,6 @@ export const EXISTING_PLUGIN_ENTRY_EXPORTS = { 'CREDENTIALS_FILENAME', 'DOCUMENT_VERSION', 'parseCredentialsDocument', 'renderFlatLayoutMigration', 'resolveSpec', ], '@deepseek-ai/dsh-cua': ['CuaConfig', 'installCua'], - '@deepseek-ai/dsh-deepseek-account-platform': ['Config'], '@deepseek-ai/dsh-experimental-claude-code-mods': [ 'DEFAULT_TOOL_ALIASES', 'KNOWN_EVENTS', 'MODS_API_VERSION', 'SERVED_EVENTS', 'defineMod', ], diff --git a/scripts/rescope-vendor.spec.ts b/scripts/rescope-vendor.spec.ts index 786cdb7773..4f43ef08fe 100644 --- a/scripts/rescope-vendor.spec.ts +++ b/scripts/rescope-vendor.spec.ts @@ -90,10 +90,14 @@ describe('product identifiers', () => { 'apps/web/tests/developer-tools-settings.e2e.ts', 'docs/subsystems/extensions.md', 'docs/subsystems/extensions.zh.md', + 'docs/tool-catalog.md', + 'docs/tool-catalog.zh.md', 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.md', 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.zh.md', 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md', 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.zh.md', + 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', + 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', 'docs/user/guide/schedule.md', 'docs/user/guide/schedule.zh.md', 'packages/bundle/web-app/cordis.patch.yml', @@ -109,6 +113,7 @@ describe('product identifiers', () => { 'packages/client/ui-entry-customization/tests/menu.client.spec.tsx', 'packages/client/ui-workspace/tests/workspaces-service.client.spec.ts', 'packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts', + 'scripts/gen-tool-catalog.ts', 'snapshots/session/cordis-inspect-liveness/client-fixture.mjs', 'snapshots/session/cordis-inspect-timeout/client-fixture.mjs', ])('preserves the product values in %s', (file) => { @@ -166,6 +171,7 @@ describe('product identifiers', () => { ['packages/client/ui-entry-customization/tests/menu.client.spec.tsx', 1], ['packages/client/ui-workspace/tests/workspaces-service.client.spec.ts', 1], ['packages/extensions/cordis-host-runner/tests/inspect-registry.spec.ts', 2], + ['scripts/gen-tool-catalog.ts', 1], ['snapshots/session/cordis-inspect-liveness/client-fixture.mjs', 1], ['snapshots/session/cordis-inspect-timeout/client-fixture.mjs', 2], ] as const)('reverses real package references in %s and restores them', (file, lines) => { diff --git a/scripts/rescope-vendor.ts b/scripts/rescope-vendor.ts index acb0385260..7a5dc46818 100644 --- a/scripts/rescope-vendor.ts +++ b/scripts/rescope-vendor.ts @@ -109,6 +109,11 @@ const GENERIC_SKIPS: readonly GenericSkip[] = [ { file: 'apps/cli/tests/optional-bundle-transitions.e2e.ts', upstream: ['cordis'] }, { file: 'apps/web/tests/agent-preset-selection.e2e.ts', upstream: ['cordis'] }, { file: 'apps/web/tests/developer-tools-settings.e2e.ts', upstream: ['cordis'] }, + { file: 'docs/tool-catalog.md', upstream: ['cordis'] }, + { file: 'docs/tool-catalog.zh.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.md', upstream: ['cordis'] }, + { file: 'docs/upgrade-guide/v0.2.2-alpha.2/fs-observation-policy-default-off/guide.zh.md', upstream: ['cordis'] }, + { file: 'scripts/gen-tool-catalog.ts', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.0-rc.2/schedule-bundle-retired/guide.zh.md', upstream: ['cordis'] }, { file: 'docs/upgrade-guide/v0.2.1-alpha.1/subagent-preset-composition/guide.md', upstream: ['cordis'] }, @@ -190,7 +195,7 @@ const POSTCONDITIONS: readonly PostCondition[] = [ { file: 'packages/boot/app-boot/tsdown.config.ts', text: '[\'@deepseek-ai/cordis-plugin-include\']', count: 1 }, { file: 'tsconfig.base.json', text: '"@deepseek-ai/cordis-plugin-loader": ["./vendor/loader/src"]', count: 1 }, // The vendored README owns this required entry; reject its deletion or duplication. - { file: 'vendor/README.md', text: '17. **`@deepseek-ai` rescope**', count: 1 }, + { file: 'vendor/README.md', text: '`@deepseek-ai` rescope**', count: 1 }, { file: 'pnpm-workspace.yaml', text: 'cordis@4.0.0-rc.7', count: 0 }, // The preset ids in this table are product data, not package names. { file: 'packages/client/ui-agent-preset/tests/locales.client.spec.ts', text: '[\'cordis\', \'presetCordisName\'', count: 1 }, diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d1be3c86de..d5001cd021 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -89,9 +89,8 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/document/office-kit': { kind: 'indirect', reason: 'The provider returns rendered and converted bytes; the Office tools own their model-visible results.' }, 'packages/credentials/deepseek-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, - 'packages/credentials/deepseek-account-platform': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, - 'packages/api/account-controller': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, 'packages/client/ui-settings-account': { kind: 'none', reason: 'Account authorization registers no model context or tools; credentials affect HTTP authentication only.' }, + 'packages/client/ui-account-notifications': { kind: 'none', reason: 'Account notification presentation and polling add no model input or Session events.' }, 'packages/attachment/attachment': { kind: 'indirect', reason: 'The storage seam delegates model request rendering to provider adapters.' }, 'packages/attachment/attachment-local': { kind: 'indirect', reason: 'The local backend delegates model request rendering to provider adapters.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index cfecbdc02b..2121904985 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -47,15 +47,14 @@ "@deepseek-ai/dsh-client-product-analytics/types": ["./packages/client/product-analytics/src/events.ts"], "@deepseek-ai/dsh-client-product-analytics/client": ["./packages/client/product-analytics/src/client/index.ts"], "@deepseek-ai/dsh-otel": ["./packages/telemetry/otel/src"], + "@deepseek-ai/dsh-client-ui-account-notifications": ["./packages/client/ui-account-notifications/src/index.ts"], + "@deepseek-ai/dsh-client-ui-account-notifications/client": ["./packages/client/ui-account-notifications/src/client/index.ts"], "@deepseek-ai/dsh-client-ui-settings-account": ["./packages/client/ui-settings-account/src/index.ts"], "@deepseek-ai/dsh-client-ui-settings-account/client": ["./packages/client/ui-settings-account/src/client/index.ts"], "@deepseek-ai/dsh-api-gateway/stream-protocol": ["./packages/api/gateway/src/stream-protocol.ts"], - "@deepseek-ai/dsh-api-account-controller": ["./packages/api/account-controller/src/index.ts"], - "@deepseek-ai/dsh-api-account-controller/types": ["./packages/api/account-controller/src/types.ts"], - "@deepseek-ai/dsh-deepseek-account-platform": ["./packages/credentials/deepseek-account-platform/src/index.ts"], - "@deepseek-ai/dsh-deepseek-account-platform/types": ["./packages/credentials/deepseek-account-platform/src/types.ts"], "@deepseek-ai/dsh-deepseek-account": ["./packages/credentials/deepseek-account/src/index.ts"], "@deepseek-ai/dsh-deepseek-account/types": ["./packages/credentials/deepseek-account/src/types.ts"], + "@deepseek-ai/dsh-deepseek-account/client-metadata": ["./packages/credentials/deepseek-account/src/client-metadata.ts"], "@deepseek-ai/dsh-experimental-speech-to-text": ["./packages/experimental/speech-to-text/src/index.ts"], "@deepseek-ai/dsh-experimental-translator": ["./packages/experimental/translator/src/index.ts"], "@deepseek-ai/dsh-experimental-translator/types": ["./packages/experimental/translator/src/types.ts"], diff --git a/tsconfig.client.json b/tsconfig.client.json index 0075d223e4..f15b78502b 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -75,6 +75,7 @@ { "path": "./packages/core/tool-executor-native" }, { "path": "./packages/core/tool-executor-ptc" }, { "path": "./packages/client/ui-settings-account" }, + { "path": "./packages/client/ui-account-notifications" }, // Shared leaf: web e2e boots the real host webserver (fixture + real-host // smoke policy). webserver has zero workspace deps and no cordis merge, // so it cannot drag host-side Context augmentation into this program. diff --git a/tsconfig.host.json b/tsconfig.host.json index b4a4ff2380..c926055be3 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -331,8 +331,6 @@ { "path": "./packages/document/office-kit" }, { "path": "./packages/document/tool-office" }, - { "path": "./packages/api/account-controller" }, - { "path": "./packages/credentials/deepseek-account-platform" }, { "path": "./packages/credentials/deepseek-account" }, { "path": "./packages/client/ui-deliverables/tsconfig.host.json" }, { "path": "./vendor/cosmokit" }, From d67e146e73e98a564f5f26e880cad1d140fa4eb3 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 17:43:31 +0800 Subject: [PATCH 055/103] fix(goal): report saved objectives when attachment admission closes --- docs/event-producer-consumer.md | 22 ++--- docs/event-producer-consumer.zh.md | 22 ++--- docs/subsystems/core.md | 7 ++ docs/subsystems/core.zh.md | 7 ++ packages/core/agent-loop/src/agent.ts | 2 +- packages/core/agent/src/runtime-types.ts | 7 ++ packages/goal/command-goal/README.i18n.yaml | 4 +- packages/goal/command-goal/README.md | 2 +- packages/goal/command-goal/README.zh.md | 2 +- packages/goal/command-goal/package.json | 1 + packages/goal/command-goal/src/index.ts | 39 +++++---- .../command-goal/tests/command-goal.spec.ts | 87 +++++++++++++++++-- 12 files changed, 152 insertions(+), 50 deletions(-) diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 5247fc4477..e60d35766c 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:302`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:340`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:348`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:362`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f8c8c77e5a..83ff9eb7d4 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,17 +14,17 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:411`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:302`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:311`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:441`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:340`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:348`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:362`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:401`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:321`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:429`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 7e86e6e0d1..0e718fe573 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -74,6 +74,13 @@ interface Agent { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index c82be05f03..c624316f57 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -78,6 +78,13 @@ interface Agent { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 95c27e6c92..56cb982c75 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -265,7 +265,7 @@ export class ReactLoopAgent implements Agent { } while (activity !== this.activityDone) } - private assertOpen(): void { + assertOpen(): void { if (this.lifetimeSignal.aborted) { throw new AgentClosedError(this.id, { cause: this.lifetimeSignal.reason }) } diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 39b15064dc..98f0d3ebe7 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -202,6 +202,13 @@ declare module './types.ts' { /** Agent-scoped context; its contributions are agent-local, unwind on disposal, and reject registration afterward. */ readonly ctx: Context + /** + * Check the driver's admission before a compound operation writes state. + * Drivers without an admission check leave this method absent. + * @throws AgentClosedError once the driver stops accepting work. + */ + assertOpen?(): void + /** * Clear queued and steering work — unless `keepInbox` — and abort the active * turn or between-turn task. The first cause wins for that activity. With no diff --git a/packages/goal/command-goal/README.i18n.yaml b/packages/goal/command-goal/README.i18n.yaml index 9efbb3b229..a057275fbe 100644 --- a/packages/goal/command-goal/README.i18n.yaml +++ b/packages/goal/command-goal/README.i18n.yaml @@ -24,8 +24,8 @@ en: 38a273cb14017e13 zh: d4b7b501bcd9589b /deepseek-ai-dsh-command-goal/use-this-package/attachments: - en: e61cd7437ed4aa73 - zh: 552c36c3b8d16007 + en: 60281bad395286ac + zh: c1a6e51161717616 /deepseek-ai-dsh-command-goal/use-this-package/compose-it: en: ba5792bd8714f1c3 zh: c9e5500c0a3b7651 diff --git a/packages/goal/command-goal/README.md b/packages/goal/command-goal/README.md index a627a15e82..96aa3c7b9a 100644 --- a/packages/goal/command-goal/README.md +++ b/packages/goal/command-goal/README.md @@ -46,7 +46,7 @@ Control words (`clear`, `pause`, `resume`, `edit`) are recognized only when they ### Attachments -`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. +`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. If the Agent starts closing before the command writes the objective, the command rejects with `AGENT_CLOSED`. If attachment submission is rejected after the objective is saved, the command reports the saved objective and leaves the attachments in the composer. ### Compose it diff --git a/packages/goal/command-goal/README.zh.md b/packages/goal/command-goal/README.zh.md index 9e4bac63d9..e8d0b08b85 100644 --- a/packages/goal/command-goal/README.zh.md +++ b/packages/goal/command-goal/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" ### 附件 -`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 +`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 如果 Agent 在命令写入目标前开始关闭,命令会以 `AGENT_CLOSED` 拒绝请求。如果目标已保存,但随后提交附件时遭到拒绝,命令会提示目标已保存,并将附件保留在输入区。 ### 组合方式 diff --git a/packages/goal/command-goal/package.json b/packages/goal/command-goal/package.json index f51a794228..881b44177e 100644 --- a/packages/goal/command-goal/package.json +++ b/packages/goal/command-goal/package.json @@ -32,6 +32,7 @@ ], "license": "MIT", "peerDependencies": { + "@deepseek-ai/dsh-agent": "workspace:*", "@deepseek-ai/dsh-commands": "workspace:*", "@deepseek-ai/dsh-goal": "workspace:*", "@deepseek-ai/dsh-llm": "workspace:*", diff --git a/packages/goal/command-goal/src/index.ts b/packages/goal/command-goal/src/index.ts index 9238d76632..cd84cbddf5 100644 --- a/packages/goal/command-goal/src/index.ts +++ b/packages/goal/command-goal/src/index.ts @@ -4,6 +4,7 @@ */ import type { Context } from '@deepseek-ai/cordis' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import { CommandDefinitionId } from '@deepseek-ai/dsh-commands/brand' import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands' import { GoalError } from '@deepseek-ai/dsh-goal' @@ -109,17 +110,25 @@ function missingGoal(action: string): CommandResult { } /** - * Submit the invocation's admitted composer attachments as one model-visible user - * message ahead of the goal's next round. The attachments precede a fixed text - * block naming their role, so a later goal round reads them from ordinary - * session history without the goal domain storing attachment state. + * Report the committed objective and submit its attachments ahead of the next goal round. + * A closed Agent leaves the objective saved and the attachments in the composer. */ -function submitObjectiveAttachments(invocation: CommandInvocation): void { - if (invocation.attachments.length === 0) return - invocation.agent.followup(createUserMessage({ - content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], - source: { kind: 'user' }, - })) +function finishObjective(invocation: CommandInvocation, title: string, goal: GoalView): CommandResult { + if (invocation.attachments.length > 0) { + try { + invocation.agent.followup(createUserMessage({ + content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], + source: { kind: 'user' }, + })) + } catch (error: unknown) { + if (!(error instanceof AgentClosedError)) throw error + return { + kind: 'error', + text: 'Goal saved. The agent is closing, so the attachments were not submitted.', + } + } + } + return renderGoal(title, goal) } /** Execute one parsed human command through the domain that owns persistence. */ @@ -131,6 +140,7 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman text: 'Attachments only accompany a goal objective: /goal or /goal edit .', } } + if (command.kind === 'create' || command.kind === 'edit') invocation.agent.assertOpen?.() try { const current = ctx.goals.get(invocation.agent) switch (command.kind) { @@ -148,19 +158,16 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman } } const created = ctx.goals.create(invocation.agent, { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal created', created) + return finishObjective(invocation, 'Goal created', created) } case 'edit': { if (current === undefined) return missingGoal('edit') if (current.phase === 'complete') { const replaced = ctx.goals.create(invocation.agent, { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal created', replaced) + return finishObjective(invocation, 'Goal created', replaced) } const edited = ctx.goals.edit(invocation.agent, goalRef(current), { objective: command.objective }) - submitObjectiveAttachments(invocation) - return renderGoal('Goal updated', edited) + return finishObjective(invocation, 'Goal updated', edited) } case 'pause': if (current === undefined) return missingGoal('pause') diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index 6cb4cf83c9..e69b3fe89d 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentRegistry, { AgentClosedError } from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' @@ -15,14 +15,19 @@ interface Harness { readonly ctx: Context readonly agent: Agent readonly session: Session + readonly closing: AbortController readonly plugin: Awaited> } /** Build a live idle agent accepted by the exact-identity goal service. */ -function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } { +function stubAgent(ctx: Context, id: string): Pick { // Store-created: the command executor durably logs lifecycle events on it. const session = ctx.sessions.create(SessionId(id)) const inbox = createInboxStub() + const closing = new AbortController() + const assertOpen = (): void => { + if (closing.signal.aborted) throw new AgentClosedError(session.id) + } let status: AgentStatus = 'idle' const agent: Agent = { id: session.id, @@ -33,14 +38,18 @@ function stubAgent(ctx: Context, id: string): { agent: Agent; session: Session } ctx: new Context(), get status() { return status }, send: () => {}, - followup: () => {}, + assertOpen, + followup(input) { + assertOpen() + inbox.append('next-turn', input) + }, steer: () => {}, inject(input) { this.inbox.append('next-step', input) }, cancel() { status = 'idle' }, runMaintenance: task => task(new AbortController().signal), whenIdle() { return Promise.resolve() }, } - return { agent, session } + return { agent, session, closing } } /** Mount the real command registry, goal domain, and producer. */ @@ -52,9 +61,9 @@ async function harness(): Promise { await ctx.plugin(AgentRegistry) await ctx.plugin(GoalService) const plugin = await ctx.plugin(commandGoal) - const { agent, session } = stubAgent(ctx, `command-goal-${Math.random()}`) + const { agent, session, closing } = stubAgent(ctx, `command-goal-${Math.random()}`) await ctx.agents.register(agent) - return { ctx, agent, session, plugin } + return { ctx, agent, session, closing, plugin } } /** The log with executor-owned command lifecycle bookkeeping stripped (goal assertions target domain events). */ @@ -243,7 +252,7 @@ describe('/goal attachments', () => { const PNG = 'AAAA' /** Wire the fake store the executor admits through (once per harness). */ - function provideStore(test: Harness): void { + function provideStore(test: Harness, beforeSave?: () => Promise): void { let saved = 0 const saveImage = (input: { mediaType: string; name?: string }) => { saved += 1 @@ -260,6 +269,7 @@ describe('/goal attachments', () => { validateImage: () => Promise.resolve(), saveImage, async saveImages(inputs: readonly { mediaType: string; name?: string }[]) { + if (beforeSave !== undefined) await beforeSave() const refs = [] for (const input of inputs) refs.push(await saveImage(input)) return refs @@ -317,6 +327,69 @@ describe('/goal attachments', () => { expect(followup).toHaveBeenCalledTimes(1) }) + it.each(['create', 'edit'] as const)('rejects %s when closure begins during attachment storage', async (operation) => { + const test = await harness() + const saving = Promise.withResolvers() + const release = Promise.withResolvers() + provideStore(test, () => { + saving.resolve(undefined) + return release.promise + }) + const original = operation === 'edit' + ? test.ctx.goals.create(test.agent, { objective: 'original objective' }) + : undefined + const suffix = operation === 'edit' ? ' edit use the reference image' : ' use the reference image' + const result = runWithAttachments(test, suffix) + try { + await saving.promise + test.closing.abort() + release.resolve(undefined) + await expect(result).rejects.toMatchObject({ code: 'AGENT_CLOSED' }) + expect(test.ctx.goals.get(test.agent)).toEqual(original) + expect(test.agent.inbox.nextTurn).toEqual([]) + } finally { + release.resolve(undefined) + await result.catch(() => undefined) + await test.ctx.fiber.dispose() + } + }) + + it('reports the saved objective when closure interrupts attachment delivery after commit', async () => { + const test = await harness() + provideStore(test) + const stop = test.ctx.on('goal/changed', ({ change }) => { + if (change.operation === 'create') test.closing.abort() + }) + try { + const result = await runWithAttachments(test, ' use the reference image') + expect(result).toEqual({ + kind: 'error', + text: 'Goal saved. The agent is closing, so the attachments were not submitted.', + }) + expect(test.ctx.goals.get(test.agent)?.objective).toBe('use the reference image') + expect(test.session.snapshotEvents().at(-1)).toMatchObject({ + type: 'command/done', + data: result, + }) + expect(test.agent.inbox.nextTurn).toEqual([]) + } finally { + stop() + await test.ctx.fiber.dispose() + } + }) + + it('propagates unrelated attachment delivery failures', async () => { + const test = await harness() + provideStore(test) + const failure = new Error('inbox write failed') + vi.spyOn(test.agent, 'followup').mockImplementation(() => { throw failure }) + try { + await expect(runWithAttachments(test, ' use the reference image')).rejects.toBe(failure) + } finally { + await test.ctx.fiber.dispose() + } + }) + it('rejects attachments on sub-commands that cannot use them, leaving the domain untouched', async () => { const test = await harness() provideStore(test) From 24477680bd3bfa6e978964a45d6d70ff30545d09 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Fri, 6 Nov 2026 17:46:22 +0800 Subject: [PATCH 056/103] Guide macOS clicks on clipped elements and verify their effects --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua-macos/src/guidance.ts | 2 +- packages/experimental/cua-macos/tests/guidance.spec.ts | 3 ++- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../session/ptc-script-retained/system-prompt.expected.md | 2 +- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index c03e5a8d1b..db6dcd39a7 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -211,7 +211,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 82de79da81..567ae15da7 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -211,7 +211,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 1739be9639..d57592e9db 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -6,7 +6,7 @@ export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are avail const methodDetails = new Map([ ['mouseMove', 'Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured.'], - ['click', 'Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click.'], + ['click', 'Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) /** Complete model instructions for this provider. */ diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 3ad190d5c8..d16958a36a 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -29,7 +29,8 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const hover = GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE', 'systemPointerHover']) expect(hover).toContain(term) - expect(GUIDANCE.split('\n').find(line => line.startsWith('- click('))).toContain('call app.activate() first') + const click = GUIDANCE.split('\n').find(line => line.startsWith('- click(')) + for (const step of ['call app.activate() first', 'outside the window', 'screenshot pixels', 'before typing or retrying']) expect(click).toContain(step) for (const platformDetail of ['macOS', 'AXShowAlternateUI', 'AXRaise', 'HOVER_UNAVAILABLE', 'systemPointerHover', 'mouse-down']) { expect(COMMON_GUIDANCE).not.toContain(platformDetail) } diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 3d9737ffcf..c9a19ee43f 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -68,7 +68,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index e40ae8bdd0..525f7cbd80 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -70,7 +70,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index c357fcc58d..84b37ec0bc 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -70,7 +70,7 @@ Element ids are opaque strings from the latest successful tree; the object facad Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. -- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Both target forms send mouse-down and mouse-up events: an ID targets the element center and coordinates target the given point. Prefer invoke(id) for a background control’s default action. For a mouse click, call app.activate() first and observe the target again. A background app can ignore a dispatched click. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. Prefer invoke(id) for a background control’s default action. For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. From eed89dea5b8e0e1d2dcec7e8684865d0fe50a71c Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 17:49:06 +0800 Subject: [PATCH 057/103] docs(goal): record the command agent dependency --- docs/module-graph.md | 3 ++- docs/module-graph.zh.md | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1f8dfaee91..41eca08cbd 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -761,6 +761,7 @@ flowchart TD pkg_tools --> pkg_session pkg_tools --> pkg_system_prompt pkg_tools --> pkg_user_approval + pkg_command_goal --> pkg_agent pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm @@ -1786,7 +1787,7 @@ flowchart TD | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index a6070b4f5e..edfeb63f2d 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -763,6 +763,7 @@ flowchart TD pkg_tools --> pkg_session pkg_tools --> pkg_system_prompt pkg_tools --> pkg_user_approval + pkg_command_goal --> pkg_agent pkg_command_goal --> pkg_commands pkg_command_goal --> pkg_goal pkg_command_goal --> pkg_llm @@ -1788,7 +1789,7 @@ flowchart TD | [`workflow`](../packages/workflow/workflow) | `workflow` | [`agent`](../packages/core/agent), [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | | [`llm-deepseek-account`](../packages/llm/llm-deepseek-account) | `llm` | [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm`](../packages/llm/llm), [`llm-deepseek`](../packages/llm/llm-deepseek) | | [`tools`](../packages/core/tools) | `core` | [`agent`](../packages/core/agent), [`llm`](../packages/llm/llm), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`user-approval`](../packages/interaction/user-approval) | -| [`command-goal`](../packages/goal/command-goal) | `goal` | [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | +| [`command-goal`](../packages/goal/command-goal) | `goal` | [`agent`](../packages/core/agent), [`commands`](../packages/interaction/commands), [`goal`](../packages/goal/goal), [`llm`](../packages/llm/llm) | | [`fs-sandbox`](../packages/fs/fs-sandbox) | `fs` | [`fs`](../packages/fs/fs), [`fs-local`](../packages/fs/fs-local), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy) | | [`web-search-deepseek`](../packages/web/web-search-deepseek) | `web` | [`agent`](../packages/core/agent), [`credentials`](../packages/credentials/credentials), [`deepseek-account`](../packages/credentials/deepseek-account), [`launch-environment`](../packages/util/launch-environment), [`llm-deepseek`](../packages/llm/llm-deepseek), [`session`](../packages/core/session), [`web`](../packages/web/web) | | [`api-account-controller`](../packages/api/account-controller) | `api` | [`agent`](../packages/core/agent), [`deepseek-account`](../packages/credentials/deepseek-account), [`typert-protocol`](../packages/typert/protocol) | From 38b59a84bc3d5c3b38c2d8ebeba039b836755161 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:50:54 +0800 Subject: [PATCH 058/103] feat(forge): read pull request commits and commit ranges ForgeProvider gains optional commits and compare methods, which a provider implements together. The forge service returns undefined from commits and an unavailable failure from compare when either is missing. The GitHub provider lists commits through GraphQL pages pinned to one head, bounded by the new maxCommits setting, and reads ranges through the compare API in diff form. --- .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 4 +- .../experimental/forge-github/README.zh.md | 4 +- .../experimental/forge-github/src/commits.ts | 100 ++++++++++++++++++ .../experimental/forge-github/src/index.ts | 9 +- .../experimental/forge-github/src/provider.ts | 45 +++++++- .../forge-github/tests/plugin.spec.ts | 2 + .../forge-github/tests/provider.spec.ts | 76 ++++++++++++- .../forge-github/tests/review.spec.ts | 4 +- packages/experimental/forge/README.i18n.yaml | 4 +- packages/experimental/forge/README.md | 2 + packages/experimental/forge/README.zh.md | 2 + packages/experimental/forge/src/index.ts | 32 +++++- packages/experimental/forge/src/types.ts | 34 ++++++ .../forge/tests/lifecycle.spec.ts | 6 +- .../experimental/forge/tests/registry.spec.ts | 21 ++++ 16 files changed, 327 insertions(+), 22 deletions(-) create mode 100644 packages/experimental/forge-github/src/commits.ts diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index b096b71898..fec538644d 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: f2bd06d91b744305 - zh: ad956b539a43b880 + en: 282129be7093ee26 + zh: ff1eeeb907a46245 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 90f3c10096be642a zh: 4e1b663c52019ac2 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 2d9e2ce57a..f392b899a0 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -34,7 +34,7 @@ Mount the provider after the forge registry and list every GitHub Enterprise hos hosts: [github.com, ghe.example.com] ``` -The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` must be a positive safe integer; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, and `maxOutputBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). +The provider runs `gh` as a host process, even when Sessions execute commands in another execution world. Sign in once per host with `gh auth login --hostname `. The child receives the host environment without `DSH_*` variables and without variables whose names contain `KEY`, `PASSWORD`, `SECRET`, or `TOKEN`, so `GH_TOKEN` and `GITHUB_TOKEN` are not forwarded and `gh` uses its own credential store. Prompts, update notices, pagers, and colors are disabled. `maxOutputBytes` and `maxCommits` must be positive safe integers; only `timeoutMs` is bounded by the runtime timer limit. `ghCommand`, `hosts`, `timeoutMs`, `maxOutputBytes`, and `maxCommits` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge-github). The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `git@github.com:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://///pull/` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname `: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none. @@ -44,7 +44,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos///compare/...` with the diff media type, accepting only full commits, and fails like `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 1ac57ffa7d..da6995e916 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -34,7 +34,7 @@ kind: "package-reference" hosts: [github.com, ghe.example.com] ``` -即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs` 与 `maxOutputBytes` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 +即使 Session 在其他执行环境中运行命令,提供方也以宿主进程的形式运行 `gh`。每个主机执行一次 `gh auth login --hostname ` 完成登录。子进程继承的宿主环境去掉了 `DSH_*` 变量以及名称包含 `KEY`、`PASSWORD`、`SECRET` 或 `TOKEN` 的变量,因此 `GH_TOKEN` 与 `GITHUB_TOKEN` 不会被转发,`gh` 使用自己的凭据存储。交互提示、更新提醒、分页器与颜色输出均被关闭。`maxOutputBytes` 与 `maxCommits` 必须是正安全整数;只有 `timeoutMs` 受运行时定时器上限约束。`ghCommand`、`hosts`、`timeoutMs`、`maxOutputBytes` 与 `maxCommits` 见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge-github)。 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 @@ -44,7 +44,7 @@ kind: "package-reference" pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型读取 `repos///compare/...`,只接受完整提交,失败时与 `diff` 相同。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 diff --git a/packages/experimental/forge-github/src/commits.ts b/packages/experimental/forge-github/src/commits.ts new file mode 100644 index 0000000000..24a0d830b0 --- /dev/null +++ b/packages/experimental/forge-github/src/commits.ts @@ -0,0 +1,100 @@ +/** GitHub pull request commit listing through GraphQL, pinned to one head commit across pages. */ + +import type { ChangeRequestRef, ForgeCommit, ForgeCommitList, ForgeFailure } from '@deepseek-ai/dsh-experimental-forge' +import { z } from 'zod' +import { checkedRepository } from './urls.ts' + +/** Commits GitHub returns per GraphQL page, its connection maximum. */ +const PAGE = 100 + +/** One page of a pull request's commits with its head; `cursor` continues after the previous page. */ +export const COMMITS_QUERY = `query($owner: String!, $name: String!, $number: Int!, $first: Int!, $cursor: String) { + repository(owner: $owner, name: $name) { + pullRequest(number: $number) { + headRefOid + commits(first: $first, after: $cursor) { + totalCount + pageInfo { hasNextPage endCursor } + nodes { commit { oid messageHeadline authoredDate author { name user { login } } parents(first: 1) { nodes { oid } } } } + } + } + } +}` + +const pageSchema = z.object({ + data: z.object({ + repository: z.object({ + pullRequest: z.object({ + headRefOid: z.string(), + commits: z.object({ + totalCount: z.number().int().nonnegative(), + pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }), + nodes: z.array(z.object({ + commit: z.object({ + oid: z.string(), + messageHeadline: z.string(), + authoredDate: z.string(), + author: z.object({ name: z.string().nullable(), user: z.object({ login: z.string() }).nullable() }).nullable(), + parents: z.object({ nodes: z.array(z.object({ oid: z.string() })) }), + }), + })), + }), + }).nullable(), + }).nullable(), + }), +}) + +/** Runs one `gh` GraphQL request; resolves to its parsed JSON body, or why GitHub did not answer it. */ +export type GraphqlReader = (args: readonly string[], signal: AbortSignal) => Promise< + { readonly ok: true; readonly body: unknown } | { readonly ok: false; readonly failure: ForgeFailure }> + +/** + * List a pull request's commits oldest first, at most `limit`, reading pages until the limit or the last commit. + * Every page must report the head of the first page, so the list never mixes two pushes. + * @param read - runs one GraphQL request. + * @param ref - validated pull request address. + * @param limit - most commits listed. + * @param signal - cancellation of every page. + * @returns the commits at one head, or why GitHub did not list them. + */ +export async function listCommits( + read: GraphqlReader, + ref: ChangeRequestRef, + limit: number, + signal: AbortSignal, +): Promise { + const { host, owner, name } = checkedRepository(ref) + const commits: ForgeCommit[] = [] + let head: string | undefined + let cursor: string | null = null + for (;;) { + const body = await read([ + 'api', 'graphql', '--hostname', host, '-f', `query=${COMMITS_QUERY}`, '-f', `owner=${owner}`, '-f', `name=${name}`, + '-F', `number=${ref.number}`, '-F', `first=${Math.min(PAGE, limit - commits.length)}`, + ...cursor === null ? [] : ['-f', `cursor=${cursor}`], + ], signal) + if (!body.ok) return body.failure + const parsed = pageSchema.safeParse(body.body) + if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the commit listing' } + const pull = parsed.data.data.repository?.pullRequest + if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` } + if (head !== undefined && pull.headRefOid !== head) { + return { code: 'unavailable', message: 'The pull request head changed while its commits were read' } + } + head = pull.headRefOid + for (const { commit } of pull.commits.nodes) { + commits.push({ + sha: commit.oid, + parent: commit.parents.nodes[0]?.oid ?? null, + title: commit.messageHeadline, + author: commit.author?.user?.login ?? commit.author?.name ?? null, + authoredAt: commit.authoredDate, + }) + } + const { hasNextPage, endCursor } = pull.commits.pageInfo + if (!hasNextPage || endCursor === null || commits.length >= limit) { + return { headSha: head, commits, truncated: pull.commits.totalCount > commits.length } + } + cursor = endCursor + } +} diff --git a/packages/experimental/forge-github/src/index.ts b/packages/experimental/forge-github/src/index.ts index a0bc66126a..16481d8c81 100644 --- a/packages/experimental/forge-github/src/index.ts +++ b/packages/experimental/forge-github/src/index.ts @@ -20,6 +20,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } export const Config: z = z.object({ @@ -27,6 +29,7 @@ export const Config: z = z.object({ hosts: z.array(z.string()).default(['github.com']), timeoutMs: z.number().default(30_000), maxOutputBytes: z.number().default(8_388_608), + maxCommits: z.number().default(250), }) const HOST = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d+)?$/i @@ -41,8 +44,8 @@ export function apply(ctx: Context, config: Config): void { if (!Number.isSafeInteger(resolved.timeoutMs) || resolved.timeoutMs <= 0 || resolved.timeoutMs > MAX_TIMER_DELAY_MS) { throw new Error(`forge-github: timeoutMs must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } - if (!Number.isSafeInteger(resolved.maxOutputBytes) || resolved.maxOutputBytes <= 0) { - throw new Error('forge-github: maxOutputBytes must be a positive safe integer') + for (const key of ['maxOutputBytes', 'maxCommits'] as const) { + if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-github: ${key} must be a positive safe integer`) } - ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes)) + ctx.forge.register(new GitHubProvider(ghRunner(resolved), resolved.hosts, resolved.maxOutputBytes, resolved.maxCommits)) } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index ca56473956..c73a174f72 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -2,9 +2,11 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, - ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, + ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' +import { listCommits } from './commits.ts' +import type { GraphqlReader } from './commits.ts' import { GhOutputLimitError, GhTimeoutError, GhUnavailableError } from './gh.ts' import type { GhOutput, GhRunner } from './gh.ts' import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapSnapshotResponse, snapshotQuery } from './graphql.ts' @@ -40,8 +42,14 @@ export class GitHubProvider implements ForgeProvider { * @param gh - runner that executes `gh` on the host. * @param hosts - host names this provider serves, such as `github.com` and Enterprise hosts. * @param maxOutputBytes - maximum combined JSON bytes retained by an explicit check read. + * @param maxCommits - most commits one commit listing returns. */ - constructor(private readonly gh: GhRunner, hosts: readonly string[], private readonly maxOutputBytes: number) { + constructor( + private readonly gh: GhRunner, + hosts: readonly string[], + private readonly maxOutputBytes: number, + private readonly maxCommits: number, + ) { this.hosts = new Set(hosts.map(host => host.toLowerCase())) } @@ -160,6 +168,26 @@ export class GitHubProvider implements ForgeProvider { ], signal) } + /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */ + async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { + const failure = this.hostFailure(ref.repository.host) + if (failure !== undefined) return failure + return await listCommits(this.graphql, ref, this.maxCommits, signal) + } + + /** Read the changes between two commits through the compare API in its diff form. */ + async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + const { host, owner, name } = checkedRepository(ref) + const failure = this.hostFailure(host) + if (failure !== undefined) return failure + for (const commit of [base, head]) { + if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + } + return await this.read([ + 'api', '--hostname', host, '-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`, + ], signal) + } + fileUrl(ref: ChangeRequestRef, commit: string, path: string): string { const { host, owner, name } = ref.repository return `https://${host}/${owner}/${name}/blob/${commit}/${encodedPath(path)}` @@ -199,6 +227,17 @@ export class GitHubProvider implements ForgeProvider { return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message } } + /** Run one GraphQL request; a refusal, a body that is not GraphQL, and GraphQL errors become failures. */ + private readonly graphql: GraphqlReader = async (args, signal) => { + const output = await this.read(args, signal) + if (typeof output !== 'string') return { ok: false, failure: output } + const body = parseJson(output) + if (!hasGraphqlFields(body)) return { ok: false, failure: { code: 'unavailable', message: 'unexpected GitHub response' } } + const errors = typeof body === 'object' && body !== null && 'errors' in body && Array.isArray(body.errors) ? body.errors : [] + if (errors.length > 0) return { ok: false, failure: responseFailure({ exitCode: 0, stdout: output, stderr: '' }, errors[0]) } + return { ok: true, body } + } + /** Run one changing `gh` command; a refusal or a `gh` that cannot start becomes a failure. */ private async act(args: readonly string[], signal: AbortSignal): Promise { const output = await this.attempt(args, signal) diff --git a/packages/experimental/forge-github/tests/plugin.spec.ts b/packages/experimental/forge-github/tests/plugin.spec.ts index a214182694..2701a2720e 100644 --- a/packages/experimental/forge-github/tests/plugin.spec.ts +++ b/packages/experimental/forge-github/tests/plugin.spec.ts @@ -56,6 +56,8 @@ describe('forge-github plugin', () => { [{ maxOutputBytes: 1.5 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: 0 }, 'forge-github: maxOutputBytes must be a positive safe integer'], [{ maxOutputBytes: Number.MAX_SAFE_INTEGER + 1 }, 'forge-github: maxOutputBytes must be a positive safe integer'], + [{ maxCommits: 0 }, 'forge-github: maxCommits must be a positive safe integer'], + [{ maxCommits: 2.5 }, 'forge-github: maxCommits must be a positive safe integer'], ])('rejects %j at load', async (config, message) => { const context = await forge() diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index ce513e0ab8..2433e580f7 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -24,7 +24,7 @@ function output(stdout: unknown, exitCode = 0, stderr = ''): GhOutput { } function provider(run: GhRunner): GitHubProvider { - return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608) + return new GitHubProvider(run, ['github.com', 'GHE.corp.example'], 8_388_608, 250) } describe('GitHub provider addressing', () => { @@ -46,7 +46,7 @@ describe('GitHub provider addressing', () => { it('uses a configured HTTP port for URL mapping and GitHub queries', async () => { const gh = fakeGh(() => output({ data: { r0: { p0: pullRequestNode(1) } } })) - const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608) + const subject = new GitHubProvider(gh.run, ['ghe.example.com:8443'], 8_388_608, 250) const repository = subject.repositoryFromRemote('https://ghe.example.com:8443/team/repo.git')! const ref = { repository, number: 1 } expect(subject.changeRequestFromUrl(subject.changeRequestUrl(ref))).toEqual(ref) @@ -92,7 +92,7 @@ describe('GitHub provider fetch', () => { const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(last.stdout) for (const limit of [total, total - 1, Buffer.byteLength(first.stdout) - 1]) { const gh = fakeGh(args => args.includes('id=fixed-rollup') ? last : first) - const result = await new GitHubProvider(gh.run, ['github.com'], limit).fetchChecks(pull(1), signal) + const result = await new GitHubProvider(gh.run, ['github.com'], limit, 250).fetchChecks(pull(1), signal) if (limit === total) expect(result).toMatchObject({ checksTruncated: false }) else expect(result).toMatchObject({ code: 'too-large' }) expect(gh.calls).toHaveLength(limit < Buffer.byteLength(first.stdout) ? 1 : 2) @@ -192,7 +192,7 @@ describe('GitHub provider fetch', () => { it('rejects references retained after their host was removed from configuration', async () => { const gh = fakeGh(() => output('')) const retained = provider(gh.run).changeRequestFromUrl('https://ghe.corp.example/team/svc/pull/2')! - const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608) + const replacement = new GitHubProvider(gh.run, ['github.com'], 8_388_608, 250) const results = await replacement.fetch([retained], signal) await expect(replacement.findByHead(retained.repository, 'topic', signal)).rejects.toThrow('is not configured') expect(results.get(changeRequestKey(retained))).toMatchObject({ code: 'unavailable' }) @@ -419,6 +419,72 @@ describe('GitHub provider reads', () => { }) }) +describe('GitHub provider commits', () => { + const sha = (n: number): string => String(n).repeat(40).slice(0, 40) + const node = (n: number, author: unknown = { name: 'Octo Cat', user: { login: 'octo' } }) => ({ commit: { + oid: sha(n), messageHeadline: `commit ${n}`, authoredDate: `2026-10-0${n}T00:00:00Z`, author, + parents: { nodes: n === 1 ? [] : [{ oid: sha(n - 1) }] }, + } }) + const page = (nodes: unknown[], next: string | null, head = sha(3), total = 3) => output({ data: { repository: { pullRequest: { + headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage: next !== null, endCursor: next }, nodes }, + } } } }) + + it('lists the commits oldest first across pages pinned to one head, bounded by maxCommits', async () => { + const gh = fakeGh(args => args.includes('cursor=page-1') ? page([node(3, { name: 'Ann', user: null })], null) : page([node(1), node(2, null)], 'page-1')) + + await expect(provider(gh.run).commits(pull(7), signal)).resolves.toEqual({ + headSha: sha(3), + truncated: false, + commits: [ + { sha: sha(1), parent: null, title: 'commit 1', author: 'octo', authoredAt: '2026-10-01T00:00:00Z' }, + { sha: sha(2), parent: sha(1), title: 'commit 2', author: null, authoredAt: '2026-10-02T00:00:00Z' }, + { sha: sha(3), parent: sha(2), title: 'commit 3', author: 'Ann', authoredAt: '2026-10-03T00:00:00Z' }, + ], + }) + expect(gh.calls[0]).toEqual(expect.arrayContaining(['--hostname', 'github.com', 'owner=octo', 'name=demo', 'number=7', 'first=100'])) + expect(gh.calls[0]?.some(arg => arg.startsWith('cursor='))).toBe(false) + expect(gh.calls[1]).toEqual(expect.arrayContaining(['cursor=page-1'])) + + const bounded = fakeGh(() => page([node(1), node(2)], 'page-1')) + await expect(new GitHubProvider(bounded.run, ['github.com'], 8_388_608, 2).commits(pull(7), signal)) + .resolves.toMatchObject({ truncated: true, commits: [{ sha: sha(1) }, { sha: sha(2) }] }) + expect(bounded.calls).toHaveLength(1) + expect(bounded.calls[0]).toEqual(expect.arrayContaining(['first=2'])) + }) + + it('refuses a listing whose head moves between pages, a missing pull request, and an unexpected response', async () => { + const moved = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(4)) : page([node(1)], 'page-1')) + await expect(provider(moved.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: null } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: null } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) + await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: { headRefOid: 1 } } } })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response to the commit listing' }) + }) + + it('reports GraphQL errors, a body that is not GraphQL, and a refused request as failures', async () => { + await expect(provider(fakeGh(() => output({ errors: [{ type: 'FORBIDDEN', message: 'Resource not accessible' }] })).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'Resource not accessible' }) + await expect(provider(fakeGh(() => output('not json')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'unexpected GitHub response' }) + await expect(provider(fakeGh(() => output('', 1, 'To get started with GitHub CLI, please run: gh auth login')).run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unauthenticated', message: 'To get started with GitHub CLI, please run: gh auth login' }) + }) + + it('reads the changes between two commits through the compare API in its diff form', async () => { + const gh = fakeGh(() => output('diff --git a/x b/x\n')) + + await expect(provider(gh.run).compare(pull(7, enterprise), sha(1), sha(3), signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls).toEqual([[ + 'api', '--hostname', 'ghe.corp.example', '-H', 'Accept: application/vnd.github.diff', `repos/team/svc/compare/${sha(1)}...${sha(3)}`, + ]]) + await expect(provider(gh.run).compare(pull(7), 'main', sha(3), signal)).rejects.toThrow('forge-github: invalid commit "main"') + await expect(provider(gh.run).compare(pull(7), sha(1), 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"') + }) +}) + it('rejects readiness, actions, and content reads for an unconfigured host without starting gh', async () => { const gh = fakeGh(() => output('unexpected')) const subject = provider(gh.run) @@ -429,5 +495,7 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.merge(target, { method: 'squash', headSha: 'a'.repeat(40) }, signal)).resolves.toEqual({ code: 'failed', message }) await expect(subject.diff(target, signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.commits(target, signal)).resolves.toEqual({ code: 'unavailable', message }) + await expect(subject.compare(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) expect(gh.calls).toEqual([]) }) diff --git a/packages/experimental/forge-github/tests/review.spec.ts b/packages/experimental/forge-github/tests/review.spec.ts index e128508994..7b45b6d9d8 100644 --- a/packages/experimental/forge-github/tests/review.spec.ts +++ b/packages/experimental/forge-github/tests/review.spec.ts @@ -11,7 +11,7 @@ const single: ForgeReviewRequest = { kind: 'comment', headSha: head, comment } const success = { exitCode: 0, stdout: JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#discussion_r1' }), stderr: '' } function fixture() { const gh = vi.fn().mockResolvedValueOnce({ exitCode: 0, stdout: JSON.stringify({ head: { sha: head }, state: 'open' }), stderr: '' }).mockResolvedValue(success) - return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608), signal: new AbortController().signal } + return { gh, provider: new GitHubProvider(gh, ['github.com'], 8_388_608, 250), signal: new AbortController().signal } } describe('review submission', () => { @@ -91,7 +91,7 @@ describe('review submission', () => { }) it('rejects a host outside the provider configuration without invoking gh', async () => { const { gh, signal } = fixture() - expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) + expect(await new GitHubProvider(gh, ['enterprise.test'], 8_388_608, 250).submitReview(ref, single, signal)).toMatchObject({ ok: false, code: 'failed' }) expect(gh).not.toHaveBeenCalled() }) }) diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index a51d57819e..164392fafd 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 9ca86ee541048ff2 - zh: 7aef4feb76542dd6 + en: e99829d47d5d3863 + zh: 64413f0ab530b37f /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index 5d2bb55ec6..f2df88eb54 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -38,6 +38,8 @@ Mount the registry with at least one provider package, such as the GitHub provid `diff(ref, signal)` reads the change request's unified patch as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. +Providers may implement `commits` and `compare` together. `commits(ref, signal)` lists a change request's commits oldest first, each with its full object name, first parent, title, author, and author time, at one head commit and with a `truncated` flag; `compare(ref, base, head, signal)` reads the unified patch from commit `base` to commit `head`. The registry returns undefined from `commits` and an `unavailable` failure from `compare` when the provider lacks either method, so a consumer can offer commit views only where both exist. + `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. `ctx.forge.watch(ref, listener)` is also an effect. The first watcher of a change request polls it at once; `latest(ref)` returns the most recent result. Each forge has at most one polling fetch in flight, and that fetch includes every due change request of the forge. An open change request is polled every `activeIntervalMs` while checks are pending or mergeability is unknown, and every `idleIntervalMs` otherwise. Closed change requests use `idleIntervalMs` to detect reopening; merged requests stop automatic polling. `refresh(ref)` polls a watched change request at once, including after a terminal state; if a fetch is already in flight for its forge, another fetch starts immediately after it settles. A failed read repeats after `activeIntervalMs` doubled for each consecutive failure, up to `maxBackoffMs`, which must be at least `activeIntervalMs`. Unregistering a provider settles its watched change requests as `unavailable`. Polling stops when the last watcher leaves. The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-forge) lists the defaults. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 8961c8d31d..8515de0652 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -38,6 +38,8 @@ kind: "package-reference" `diff(ref, signal)` 读取托管平台计算出的变更请求统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 +提供方可以同时实现 `commits` 与 `compare`。`commits(ref, signal)` 在一个 head 提交上按从旧到新列出变更请求的提交,每个提交带完整对象名、第一个父提交、标题、作者与作者时间,并带 `truncated` 标志;`compare(ref, base, head, signal)` 读取从提交 `base` 到提交 `head` 的统一补丁。提供方缺少其中任一方法时,注册表的 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此使用方只在两者都存在时提供按提交查看。 + `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 `ctx.forge.watch(ref, listener)` 同样是 effect。变更请求的第一个监听方会立即触发轮询;`latest(ref)` 返回最近一次结果。每个 forge 同时最多只有一次轮询读取在进行,这次读取包含该 forge 所有到期的变更请求。打开状态的变更请求在检查未完成或可合并性未知时每 `activeIntervalMs` 轮询一次,否则每 `idleIntervalMs` 轮询一次。已关闭的变更请求按 `idleIntervalMs` 轮询以检测重新打开;已合并的停止自动轮询。`refresh(ref)` 立即轮询一个被监听的变更请求,已结束的也包括在内;该 forge 已有读取在进行时,等待其结束后立即再读一次。读取失败后,重试间隔为 `activeIntervalMs` 按连续失败次数翻倍,最长 `maxBackoffMs`;该值必须大于或等于 `activeIntervalMs`。注销提供方会让其被监听的变更请求以 `unavailable` 结束。最后一个监听方离开后轮询停止。默认值见[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-forge)。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index d5204d988a..2ed58446a1 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -6,7 +6,7 @@ import { deadline, MAX_TIMER_DELAY_MS } from '@deepseek-ai/dsh-timeout' import { changeRequestKey } from './keys.ts' import { nextPollDelay } from './schedule.ts' import type { - ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, + ChangeRequestKey, ChangeRequestListener, ChangeRequestRef, ChangeRequestSnapshot, ChangeRequestUpdate, Config, ForgeCommitList, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, ForgeRepository, ForgeReviewRequest, ForgeReviewResult, MergeRequest, } from './types.ts' @@ -247,6 +247,36 @@ export class ForgeService extends Service { (provider, operation) => provider.diff(ref, operation)) } + /** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve(undefined) : provider.commits(ref, operation)) + } + + /** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ + async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { + return await this.invoke(this.registration(ref.repository.forge), signal, + (provider, operation) => provider.commits === undefined || provider.compare === undefined + ? Promise.resolve({ code: 'unavailable', message: 'This provider does not read commits' } as const) + : provider.compare(ref, base, head, operation)) + } + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. diff --git a/packages/experimental/forge/src/types.ts b/packages/experimental/forge/src/types.ts index 35a977dcfe..1aa84c15aa 100644 --- a/packages/experimental/forge/src/types.ts +++ b/packages/experimental/forge/src/types.ts @@ -176,6 +176,30 @@ export interface ForgeActionFailure { readonly message: string } +/** One commit of a change request. */ +export interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} + +/** The commits of a change request at one head commit. */ +export interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} + /** Whether a provider can reach one host with the current credentials. */ export interface ForgeReadiness { /** `ready`, `unauthenticated` (sign-in needed), or `unavailable` (tool missing or host unreachable). */ @@ -220,6 +244,16 @@ export interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } /** diff --git a/packages/experimental/forge/tests/lifecycle.spec.ts b/packages/experimental/forge/tests/lifecycle.spec.ts index 26e779eb87..42f649cefa 100644 --- a/packages/experimental/forge/tests/lifecycle.spec.ts +++ b/packages/experimental/forge/tests/lifecycle.spec.ts @@ -120,7 +120,7 @@ it('does not announce provider withdrawal after its registry has stopped', async expect(observer).toHaveBeenCalledTimes(1) }) -it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks'] as const)( +it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', 'fetchChecks', 'commits', 'compare'] as const)( 'cancels and drains %s when its provider stops', async (method) => { ctx = await forgeContext() const provider: ForgeProvider = new FakeProvider() @@ -141,6 +141,8 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', vi.spyOn(provider, 'fileText').mockImplementation(async (_ref, _commit, _path, signal) => { await hold(signal); return 'file' }) provider.submitReview = async (_ref, _request, signal) => { await hold(signal); return { ok: true, url: 'https://fake.test/review' } } provider.fetchChecks = async (target, signal) => { await hold(signal); return snapshot(target) } + provider.commits = async (_ref, signal) => { await hold(signal); return { headSha: 'a'.repeat(40), commits: [], truncated: false } } + provider.compare = async (_ref, _base, _head, signal) => { await hold(signal); return 'diff' } const fiber = await provide(ctx, provider) const service = ctx.forge const signal = new AbortController().signal @@ -152,6 +154,8 @@ it.each(['readiness', 'markReady', 'merge', 'diff', 'fileText', 'submitReview', merge: () => service.merge(ref(1), { method: 'squash', headSha: 'a'.repeat(40) }, signal), diff: () => service.diff(ref(1), signal), fileText: () => service.fileText(ref(1), 'a'.repeat(40), 'file.txt', signal), + commits: () => service.commits(ref(1), signal), + compare: () => service.compare(ref(1), 'a'.repeat(40), 'b'.repeat(40), signal), } const rejected = expect(calls[method]()).rejects.toThrow('was unregistered') let disposed = false diff --git a/packages/experimental/forge/tests/registry.spec.ts b/packages/experimental/forge/tests/registry.spec.ts index c70a07057b..68bdf8811b 100644 --- a/packages/experimental/forge/tests/registry.spec.ts +++ b/packages/experimental/forge/tests/registry.spec.ts @@ -104,6 +104,27 @@ describe('forge registry', () => { expect(provider.actions).toEqual(['diff 3', `text 3 ${'b'.repeat(40)} src/a.ts`]) }) + it('reads commits and commit ranges only from a provider that implements both', async () => { + ctx = await forgeContext() + const provider = new FakeProvider() + await provide(ctx, provider) + const signal = new AbortController().signal + const list = { headSha: 'b'.repeat(40), truncated: false, commits: [] } + + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'This provider does not read commits' }) + const commits = vi.fn(async () => list) + Object.assign(provider, { commits }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBeUndefined() + const compare = vi.fn(async () => 'diff --git a/x b/x') + Object.assign(provider, { compare }) + await expect(ctx.forge.commits(ref(3), signal)).resolves.toBe(list) + await expect(ctx.forge.compare(ref(3), 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toBe('diff --git a/x b/x') + expect(commits).toHaveBeenCalledWith(ref(3), expect.any(AbortSignal)) + expect(compare).toHaveBeenCalledWith(ref(3), 'a'.repeat(40), 'b'.repeat(40), expect.any(AbortSignal)) + }) + it('delegates change request actions to the provider of their forge and returns its outcome', async () => { ctx = await forgeContext() const provider = new FakeProvider() From 929e283c5e414a43585aa729471bce2799f09ff3 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:51:06 +0800 Subject: [PATCH 059/103] feat(forge-panel): classify changed files into review layers and read chosen commits Each diff file now carries a review layer and a change digest. The layer follows the new testPaths and interfacePaths globs and the linguist-generated lines of the root .gitattributes, which the panel reads at the compared side and caches beside change request patches. localCommits and changeRequestCommits list commits, and a branch scope or change request diff can name consecutive commits to show instead of the whole comparison. --- .../experimental/client-ui-forge/package.json | 6 +- .../experimental/client-ui-forge/src/diff.ts | 85 ++++++--- .../experimental/client-ui-forge/src/index.ts | 165 +++++++++++++++--- .../client-ui-forge/src/layers.ts | 87 +++++++++ .../client-ui-forge/src/local-diff.ts | 108 ++++++++++-- .../client-ui-forge/src/patch-cache.ts | 30 ++-- .../experimental/client-ui-forge/src/types.ts | 53 +++++- .../tests/controller.host.spec.ts | 122 +++++++++++-- .../client-ui-forge/tests/diff.host.spec.ts | 34 +++- .../client-ui-forge/tests/harness.ts | 15 +- .../client-ui-forge/tests/layers.host.spec.ts | 65 +++++++ .../tests/local-diff-safety.host.spec.ts | 29 +-- .../tests/local-diff.host.spec.ts | 151 ++++++++++++++-- .../tests/patch-cache.host.spec.ts | 41 +++-- .../client-ui-forge/tsconfig.host.json | 1 + pnpm-lock.yaml | 14 +- 16 files changed, 863 insertions(+), 143 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/layers.ts create mode 100644 packages/experimental/client-ui-forge/tests/layers.host.spec.ts diff --git a/packages/experimental/client-ui-forge/package.json b/packages/experimental/client-ui-forge/package.json index 7ab090b292..8dd840d825 100644 --- a/packages/experimental/client-ui-forge/package.json +++ b/packages/experimental/client-ui-forge/package.json @@ -71,7 +71,8 @@ "diff": "^9.0.0", "zod": "4.6.6", "@deepseek-ai/dsh-typert-protocol": "workspace:*", - "@deepseek-ai/dsh-storage-domain": "workspace:*" + "@deepseek-ai/dsh-storage-domain": "workspace:*", + "picomatch": "^4.0.7" }, "devDependencies": { "@deepseek-ai/cordis": "workspace:~", @@ -115,7 +116,8 @@ "@deepseek-ai/dsh-timeout": "workspace:*", "@deepseek-ai/dsh-session-projection-cache": "workspace:*", "@deepseek-ai/dsh-session-query": "workspace:*", - "@deepseek-ai/dsh-api-remote-access": "workspace:*" + "@deepseek-ai/dsh-api-remote-access": "workspace:*", + "@types/picomatch": "^4.0.3" }, "files": [ "locale/*.json", diff --git a/packages/experimental/client-ui-forge/src/diff.ts b/packages/experimental/client-ui-forge/src/diff.ts index aa6cc8515a..4ec3d62b71 100644 --- a/packages/experimental/client-ui-forge/src/diff.ts +++ b/packages/experimental/client-ui-forge/src/diff.ts @@ -1,7 +1,11 @@ /** Unified patch parsing into the panel's browser-safe diff model, and the diff and size of an untracked file. */ +import { createHash } from 'node:crypto' import { parsePatch } from 'diff' -import type { ForgeChangedFile, ForgeDiffFile, ForgeDiffStatus } from './types.ts' +import type { ForgeChangedFile, ForgeDiffFile, ForgeDiffHunk, ForgeDiffStatus } from './types.ts' + +/** A changed file before its path is classified into a review layer. */ +export type ParsedDiffFile = Omit /** Git's name for the missing side of an added or deleted file. */ const NULL_PATH = '/dev/null' @@ -9,6 +13,9 @@ const NULL_PATH = '/dev/null' /** Bytes Git inspects for a NUL byte before it calls content binary. */ const BINARY_PROBE_BYTES = 8000 +/** Blob names of both sides on a Git `index` header line, which identify a binary change that carries no hunks. */ +const INDEX_LINE = /^index ([0-9a-f]+\.\.[0-9a-f]+)/m + /** * Parse a Git-style unified patch, as `git diff` or a code host prints it, * with `a/` and `b/` path prefixes. Hunk ranges follow jsdiff: a range that @@ -16,8 +23,11 @@ const BINARY_PROBE_BYTES = 8000 * @param patch - the patch text. * @returns one file per patch section in patch order. */ -export function parseDiff(patch: string): ForgeDiffFile[] { - return parsePatch(patch).flatMap((section) => { +export function parseDiff(patch: string): ParsedDiffFile[] { + const parsed = parsePatch(patch) + // Hunk lines start with a space, `+`, `-`, or `\`, so only a Git section header starts a line with `diff --git `. + const headers = patch.split(/^(?=diff --git )/m).filter(section => section.startsWith('diff --git ')) + return parsed.flatMap((section, index) => { const before = pathOf(section.oldFileName, 'a/') const after = pathOf(section.newFileName, 'b/') const path = after ?? before @@ -33,46 +43,67 @@ export function parseDiff(patch: string): ForgeDiffFile[] { else if (line.startsWith('-')) deletions++ } } + const binary = section.isBinary === true + const previousPath = status === 'renamed' ? before : null + const hunks = section.hunks.map(({ oldStart, oldLines, newStart, newLines, lines }) => ( + { oldStart, oldLines, newStart, newLines, lines })) + // Each header matches its parsed section only when every section starts with a Git header. + const header = binary && headers.length === parsed.length ? String(headers[index]) : '' + const blobs = INDEX_LINE.exec(header)?.[1] ?? '' return [{ - path, - previousPath: status === 'renamed' ? before : null, - status, - binary: section.isBinary === true, - oversized: false, - untracked: false, - additions, - deletions, - hunks: section.hunks.map(({ oldStart, oldLines, newStart, newLines, lines }) => ({ oldStart, oldLines, newStart, newLines, lines })), + path, previousPath, status, binary, oversized: false, untracked: false, additions, deletions, hunks, + digest: changeDigest(path, previousPath, status, hunks, blobs), }] }) } +/** Digest of one change: its paths, status, hunks, and the identity of content that hunks do not show. */ +function changeDigest( + path: string, previousPath: string | null, status: ForgeDiffStatus, hunks: readonly ForgeDiffHunk[], content: string, +): string { + return createHash('sha256').update(JSON.stringify([path, previousPath, status, hunks, content])).digest('hex').slice(0, 32) +} + /** * Describe an untracked file as added in full. * @param path - path relative to the repository root. * @param content - the file's bytes. * @returns the file with one hunk of added lines, none when it is empty, or none and `binary` when its content is not text. */ -export function untrackedFile(path: string, content: Uint8Array): ForgeDiffFile { - const file: ForgeDiffFile = { - path, previousPath: null, status: 'added', binary: false, oversized: false, untracked: true, additions: 0, deletions: 0, hunks: [], - } +export function untrackedFile(path: string, content: Uint8Array): ParsedDiffFile { const text = decodeText(content) - if (text === undefined) return { ...file, binary: true } - if (text.length === 0) return file + if (text === undefined) return addedFile(path, [], { binary: true, oversized: false, content: createHash('sha256').update(content).digest('hex') }) + if (text.length === 0) return addedFile(path, [], { binary: false, oversized: false, content: '' }) const lines = text.split('\n') const ended = lines.at(-1) === '' if (ended) lines.pop() + return addedFile(path, [{ + oldStart: 1, + oldLines: 0, + newStart: 1, + newLines: lines.length, + lines: [...lines.map(line => `+${line}`), ...ended ? [] : ['\\ No newline at end of file']], + }], { binary: false, oversized: false, content: '' }) +} + +/** + * Describe an untracked file over `maxDiffBytes`, which carries no hunks and whose content is not read. + * @param path - path relative to the repository root. + * @returns the oversized added file. + */ +export function oversizedUntrackedFile(path: string): ParsedDiffFile { + return addedFile(path, [], { binary: false, oversized: true, content: 'oversized' }) +} + +/** An untracked file as added, whose digest also covers `content`, the identity of content its hunks do not show. */ +function addedFile(path: string, hunks: readonly ForgeDiffHunk[], { binary, oversized, content }: { + readonly binary: boolean + readonly oversized: boolean + readonly content: string +}): ParsedDiffFile { return { - ...file, - additions: lines.length, - hunks: [{ - oldStart: 1, - oldLines: 0, - newStart: 1, - newLines: lines.length, - lines: [...lines.map(line => `+${line}`), ...ended ? [] : ['\\ No newline at end of file']], - }], + path, previousPath: null, status: 'added', binary, oversized, untracked: true, + additions: hunks[0]?.newLines ?? 0, deletions: 0, hunks, digest: changeDigest(path, null, 'added', hunks, content), } } diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 6800a70b34..c1679818d2 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -5,7 +5,10 @@ import z from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-api-remote-access' import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' -import type { ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, MergeMethod } from '@deepseek-ai/dsh-experimental-forge' +import type { + ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeReviewRequest, ForgeReviewResult, + MergeMethod, +} from '@deepseek-ai/dsh-experimental-forge' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session' import type { WorktreeCleanup } from '@deepseek-ai/dsh-experimental-worktree/types' import { appendPluginRecord } from '@deepseek-ai/dsh-session' @@ -19,15 +22,17 @@ import { gitIn, inspectCheckout, listBranches } from './git.ts' import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, FilterConfigError, forkPoint, localDiff, localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, FilterConfigError, forkPoint, localCommits, localDiff, + localText, NoForkPoint, } from './local-diff.ts' +import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' import { PatchCache } from './patch-cache.ts' import { ChangeRequestStates, changeRequestStatesDomain } from './states.ts' import type { PanelConfig } from './panel.ts' import type { - Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeLocalDiff, ForgeLocalScope, - ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, + Config, ForgeBaseBranches, ForgeBranches, ForgeChangeRequestDiff, ForgeChangeRequestStatesFrame, ForgeCommitRange, ForgeLocalCommits, + ForgeLocalDiff, ForgeLocalScope, ForgeMissingWorktree, ForgePanelState, ForgeSessionWorktree, ForgeWorktreeState, } from './types.ts' import { forgeWorktreeProjection, messageOf, within, WORKTREE_RECORD, WorktreeCreations } from './worktree.ts' import type { HeldWork } from './worktree.ts' @@ -41,8 +46,28 @@ declare module '@deepseek-ai/cordis' { } } -/** Panel limits plus the branch listing limit and the worktree branch prefix. */ -type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly worktreePrefix: string } +/** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */ +type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string } + +/** + * Tests, test data, snapshots, locale dictionaries, and lockfiles, after the review plugin's collapsed and + * non-interface paths; `locales.ts` is the typed dictionary module of a DSH Client plugin. + */ +const TEST_PATHS = [ + '**/test/**', '**/tests/**', '**/__tests__/**', '**/__mocks__/**', '**/__fixtures__/**', '**/e2e/**', + '**/*.spec.*', '**/*.test.*', '**/*.e2e.*', + '**/__snapshots__/**', 'snapshots/**', '**/*.snap', + '**/locale/*.json', '**/locales/**', '**/locales.ts', + '**/pnpm-lock.yaml', '**/package-lock.json', '**/npm-shrinkwrap.json', '**/yarn.lock', +] as const + +/** Package manifests, type declarations, and configuration by extension, name, or directory, after the review plugin's scanner. */ +const INTERFACE_PATHS = [ + '**/package.json', '**/*.d.ts', '**/*.d.mts', '**/*.d.cts', '**/types.ts', + '**/*.{json,jsonc,yaml,yml,toml,ini,conf,cfg,properties,xml,plist}', + '**/.env', '**/.env.*', '**/.*rc', '**/.*rc.*', '**/*{config,settings,preferences,options}*', + '**/{config,configs,settings,profiles}/**', +] as const /** * Serves the forge panel. Following a Session inspects the checkout of its @@ -75,6 +100,9 @@ export class ForgePanelController extends TypertRemoteService { maxDiffBytes: z.number().default(8_388_608), maxUntrackedFiles: z.number().default(100), maxCachedDiffBytes: z.number().default(16_777_216), + maxCommits: z.number().default(250), + testPaths: z.array(z.string()).default([...TEST_PATHS]), + interfacePaths: z.array(z.string()).default([...INTERFACE_PATHS]), }) private readonly home: Context @@ -83,6 +111,7 @@ export class ForgePanelController extends TypertRemoteService { private worktreeStates!: ProjectionHandle private creations!: WorktreeCreations private readonly patches: PatchCache + private readonly layers: FileLayers private states: ChangeRequestStates | undefined private readonly stopPanels: () => Promise private readonly stopStates: () => Promise @@ -97,10 +126,14 @@ export class ForgePanelController extends TypertRemoteService { throw new Error(`forge-panel: ${key} must be a positive integer no greater than ${MAX_TIMER_DELAY_MS}`) } } - for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes'] as const) { + for (const key of ['maxBranches', 'maxDiffBytes', 'maxUntrackedFiles', 'maxCachedDiffBytes', 'maxCommits'] as const) { if (!Number.isSafeInteger(resolved[key]) || resolved[key] <= 0) throw new Error(`forge-panel: ${key} must be a positive integer`) } if (!branchPrefix(resolved.worktreePrefix)) throw new Error('forge-panel: worktreePrefix must start a valid Git branch name') + for (const key of ['testPaths', 'interfacePaths'] as const) { + if (resolved[key].some(glob => glob.trim() === '')) throw new Error(`forge-panel: ${key} entries must not be empty`) + } + this.layers = new FileLayers(resolved.testPaths, resolved.interfacePaths) this.home = ctx this.config = resolved this.patches = new PatchCache(resolved.maxCachedDiffBytes) @@ -271,7 +304,8 @@ export class ForgePanelController extends TypertRemoteService { * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote @@ -283,19 +317,42 @@ export class ForgePanelController extends TypertRemoteService { const created = this.worktreeState(session).created const fork = scope.kind !== 'branch' ? null : await diffing(scope.base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, scope.base)) - return await diffing(localDiff(this.home, this.config, session, root, fork, scope, signal)) + return await diffing(localDiff(this.home, this.config, session, root, fork, scope, this.layers, signal)) + } + + /** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ + @Remote + async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise { + signal.throwIfAborted() + const inspection = await this.checkoutOf(session, signal) + const git = gitIn(this.home, { ...this.config, maxOutputBytes: this.config.maxDiffBytes }, session, inspection.checkout.root, signal) + const created = this.worktreeState(session).created + const fork = await diffing(base === null ? forkPoint(git, inspection, created) : chosenForkPoint(git, base)) + if (fork === null) throw new RemoteError('forgePanel/no-fork-point', 'The checkout has no fork point to compare its branch with', {}) + return await localCommits(git, fork, this.config.maxCommits) } /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise { @@ -325,36 +382,63 @@ export class ForgePanelController extends TypertRemoteService { } /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ @Remote - async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise { + async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise { + signal.throwIfAborted() + const list = await this.home.forge.commits(this.bound(session, url).ref, signal) + if (list !== undefined && 'code' in list) throw readError(list) + return list ?? null + } + + /** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ + @Remote + async changeRequestDiff( + session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, + ): Promise { signal.throwIfAborted() const { ref, update } = this.bound(session, url) if (update === null || !('snapshot' in update)) { throw new RemoteError('forgePanel/diff-failed', 'The change request status has not been read yet', {}) } + if (commits !== null) return await this.commitsDiff(ref, commits, signal) const { headSha, headBranch, baseBranch } = update.snapshot const key = changeRequestKey(ref) const version = JSON.stringify([headSha, baseBranch]) - let patch = this.patches.get(key, version) - if (patch === undefined) { - const read = await this.home.forge.diff(ref, signal) - if (typeof read !== 'string') throw readError(read) + let read = this.patches.get(key, version) + if (read === undefined) { + const patch = await this.home.forge.diff(ref, signal) + if (typeof patch !== 'string') throw readError(patch) + read = { patch, attributes: await this.attributesAt(ref, headSha, signal) } this.patches.set(key, version, read) - patch = read } - const files = parseDiff(patch) + const files = this.layers.classify(parseDiff(read.patch), read.attributes) let localAhead: number | null = null try { localAhead = await aheadOf( @@ -604,6 +688,33 @@ export class ForgePanelController extends TypertRemoteService { return this.home.workingDirectory.get(session) === directory ? missing : null } + /** The changes of consecutive commits of a change request, from the first one's first parent to the last. */ + private async commitsDiff(ref: ChangeRequestRef, commits: ForgeCommitRange, signal: AbortSignal): Promise { + const list = await this.home.forge.commits(ref, signal) + if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {}) + if ('code' in list) throw readError(list) + const first = list.commits.findIndex(commit => commit.sha === commits.from) + const last = list.commits.findIndex(commit => commit.sha === commits.to) + if (first === -1 || last < first) { + throw new RemoteError('forgePanel/commits-missing', 'The chosen commits are no longer in the change request', {}) + } + const parent = list.commits[first]?.parent ?? null + if (parent === null) throw new RemoteError('forgePanel/diff-failed', 'The first chosen commit has no parent to compare with', {}) + const patch = await this.home.forge.compare(ref, parent, commits.to, signal) + if (typeof patch !== 'string') throw readError(patch) + const files = this.layers.classify(parseDiff(patch), await this.attributesAt(ref, commits.to, signal)) + const fileUrls = Object.fromEntries(files.map(file => [file.path, this.home.forge.fileUrl(ref, commits.to, file.path)])) + return { headSha: commits.to, files, localAhead: null, fileUrls } + } + + /** The root `.gitattributes` of a change request's repository at a commit, empty when the commit has none. */ + private async attributesAt(ref: ChangeRequestRef, commit: string, signal: AbortSignal): Promise { + const attributes = await this.home.forge.fileText(ref, commit, ATTRIBUTES_PATH, signal) + if (typeof attributes === 'string') return attributes + if (attributes.code === 'not-found') return '' + throw readError(attributes) + } + /** Inspect the checkout of the Session's current directory, which local diffs read. */ private async checkoutOf(session: Session, signal: AbortSignal): Promise { const inspection = await inspectCheckout(this.home, this.config, session, this.home.workingDirectory.get(session), signal) @@ -726,7 +837,8 @@ function readError(failure: ForgeFailure): RemoteError { } /** - * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, and a missing base branch as Remote errors. + * Settle a diff read, reporting its size limit, its filter configuration, a missing fork point, a missing base branch, and chosen + * commits that are not on the branch as Remote errors. * @param reading - the read. * @returns what the read returned. */ @@ -738,6 +850,7 @@ async function diffing(reading: Promise): Promise { if (error instanceof DiffTooLarge) throw new RemoteError('forgePanel/diff-too-large', error.message, {}, { cause: error }) if (error instanceof NoForkPoint) throw new RemoteError('forgePanel/no-fork-point', error.message, {}, { cause: error }) if (error instanceof BaseMissing) throw new RemoteError('forgePanel/base-missing', error.message, {}, { cause: error }) + if (error instanceof CommitsMissing) throw new RemoteError('forgePanel/commits-missing', error.message, {}, { cause: error }) throw error } } diff --git a/packages/experimental/client-ui-forge/src/layers.ts b/packages/experimental/client-ui-forge/src/layers.ts new file mode 100644 index 0000000000..827bbf4269 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/layers.ts @@ -0,0 +1,87 @@ +/** + * Review layers of changed files: the `testPaths` and `interfacePaths` globs of the panel's configuration, and the + * `linguist-generated` attribute of a repository's root `.gitattributes`, which also places a file in the `test` layer. + */ + +import picomatch from 'picomatch' +import type { ParsedDiffFile } from './diff.ts' +import type { ForgeDiffFile, ForgeFileLayer } from './types.ts' + +/** Path of the attributes file read beside each diff, relative to the repository root. */ +export const ATTRIBUTES_PATH = '.gitattributes' + +/** The attribute GitHub Linguist reads to treat a file as generated. */ +const GENERATED = 'linguist-generated' + +type Matcher = (path: string) => boolean + +/** + * Compile globs into one matcher; `*` matches dot files and never crosses `/`. + * @param globs - picomatch globs. + * @returns whether a repository-relative path matches any glob. + */ +function matcherOf(globs: readonly string[]): Matcher { + return globs.length === 0 ? () => false : picomatch([...globs], { dot: true }) +} + +/** + * Read which paths a `.gitattributes` text marks `linguist-generated`. Lines apply in order, so a later line overrides + * an earlier one; `linguist-generated` and `=true` set the attribute, `-linguist-generated` and `=false` unset it, and + * `!linguist-generated` returns it to unspecified. A pattern without `/` matches a file name at any depth, and one with + * `/` matches from the repository root. Macro definitions, quoted patterns, and patterns ending in `/`, which name + * directories and so never match a file, are skipped. + * @param attributes - the text of the root `.gitattributes`, empty without one. + * @returns whether a repository-relative path is generated. + */ +export function generatedMatcher(attributes: string): Matcher { + const rules: { readonly match: Matcher; readonly generated: boolean | undefined }[] = [] + for (const raw of attributes.split(/\r?\n/)) { + const [pattern, ...fields] = raw.trim().split(/\s+/) + if (pattern === undefined || pattern === '' || pattern.startsWith('#') || pattern.startsWith('[attr]') + || pattern.startsWith('"') || pattern.endsWith('/')) continue + let generated: boolean | null | undefined = null + for (const field of fields) { + if (field === GENERATED || field === `${GENERATED}=true`) generated = true + else if (field === `-${GENERATED}` || field === `${GENERATED}=false`) generated = false + else if (field === `!${GENERATED}`) generated = undefined + } + if (generated === null) continue + const anchored = pattern.replace(/^\//, '') + rules.push({ match: picomatch(anchored, { dot: true, basename: !pattern.includes('/') }), generated }) + } + return (path) => { + let generated: boolean | undefined + for (const rule of rules) if (rule.match(path)) generated = rule.generated + return generated === true + } +} + +/** Classifies changed files into review layers by the panel's path globs and a repository's attributes. */ +export class FileLayers { + private readonly test: Matcher + private readonly interface: Matcher + + /** + * @param testPaths - globs of the `test` layer. + * @param interfacePaths - globs of the `interface` layer. + */ + constructor(testPaths: readonly string[], interfacePaths: readonly string[]) { + this.test = matcherOf(testPaths) + this.interface = matcherOf(interfacePaths) + } + + /** + * Place each file in its layer: `test` first, then `interface`, else `implementation`. + * @param files - parsed files. + * @param attributes - the text of the repository's root `.gitattributes`, empty without one. + * @returns the files in the same order with their layers. + */ + classify(files: readonly ParsedDiffFile[], attributes: string): ForgeDiffFile[] { + const generated = generatedMatcher(attributes) + return files.map((file) => { + const layer: ForgeFileLayer = this.test(file.path) || generated(file.path) ? 'test' + : this.interface(file.path) ? 'interface' : 'implementation' + return { ...file, layer } + }) + } +} diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index 34c6ac6114..c17c443d13 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -10,13 +10,17 @@ import type { Context } from '@deepseek-ai/cordis' import { FsError } from '@deepseek-ai/dsh-fs' import type { Session } from '@deepseek-ai/dsh-session' import { assertNever } from '@deepseek-ai/dsh-util-values' -import { decodeText, parseDiff, parseNumstat, untrackedFile } from './diff.ts' +import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from './diff.ts' +import type { ParsedDiffFile } from './diff.ts' import { gitIn, GitOutputTooLarge } from './git.ts' import type { Git, GitConfig, GitOutput, Inspection } from './git.ts' +import { ATTRIBUTES_PATH } from './layers.ts' +import type { FileLayers } from './layers.ts' import { BASE_REF_PREFIXES, parseBaseBranches, parseName, remoteOrder } from './parse.ts' import type { - ForgeBaseBranches, ForgeDiffFile, ForgeLocalChanges, ForgeLocalDiff, ForgeLocalScope, ForgeSessionWorktree, + ForgeCommitRange, ForgeLocalChanges, ForgeLocalCommits, ForgeLocalDiff, ForgeLocalScope, ForgeBaseBranches, ForgeSessionWorktree, } from './types.ts' +import type { ForgeCommit } from '@deepseek-ai/dsh-experimental-forge/types' /** Git limits plus the size limits of local diffs. */ export interface DiffConfig extends GitConfig { @@ -56,6 +60,17 @@ export class BaseMissing extends Error { override name = 'BaseMissing' } +/** Thrown when chosen commits are not among the commits of the `branch` scope, or are out of order. */ +export class CommitsMissing extends Error { + override name = 'CommitsMissing' +} + +/** A full SHA-1 or SHA-256 object name, the only form of a chosen commit Git receives. */ +const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ + +/** One commit per record: object name, first parent, author, author date, and subject, separated by NUL. */ +const LOG_FORMAT = '--format=%H%x00%P%x00%an%x00%aI%x00%s%x1e' + /** No executable diff helpers or submodule working-tree inspection; preserve recorded submodule commit changes. */ const DIFF = ['-c', 'core.quotePath=false', 'diff', '--no-ext-diff', '--no-textconv', '--submodule=short', '--ignore-submodules=dirty', '--no-color', '-M', '--src-prefix=a/', '--dst-prefix=b/'] as const @@ -155,16 +170,20 @@ export async function baseBranches( /** * Read changes at `root` with command-local clean/process filter overrides and without * submodule working-tree inspection. Git's built-in newline, ident, and encoding conversions still apply. + * Each file's layer follows `layers` and the root `.gitattributes` of the new side: the index for `staged`, + * else the working tree. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. * @param config - Git and size limits. * @param session - Session whose sandbox policy and execution world apply. * @param root - top-level directory of the checkout. * @param fork - fork point of the `branch` scope, or null without one. * @param scope - which changes to read. + * @param layers - classifier of each file's review layer. * @param signal - cancellation of every command and read. * @returns tracked files in Git's order, then untracked files unless the scope is `staged`. * @throws NoForkPoint for the `branch` scope without `fork`; FilterConfigError when filter configuration - * cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output; an Error when Git fails. + * cannot be read within `maxDiffBytes`; DiffTooLarge for oversized comparison output or `.gitattributes`; + * an Error when Git or the `.gitattributes` read fails. */ export async function localDiff( ctx: Context, @@ -173,6 +192,7 @@ export async function localDiff( root: string, fork: ForkPoint | null, scope: ForgeLocalScope, + layers: FileLayers, signal: AbortSignal, ): Promise { const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) @@ -180,6 +200,7 @@ export async function localDiff( switch (scope.kind) { case 'branch': if (fork === null) throw new NoForkPoint('The checkout has no fork point to compare its branch with') + if (scope.commits !== null) return await commitsDiff(git, fork, scope.commits, layers) range = [fork.commit] break case 'uncommitted': range = [await headOrEmptyTree(git)]; break @@ -190,14 +211,28 @@ export async function localDiff( } const overrides = await diffFilterOverrides(git) const tracked = parseDiff((await bounded(git('diff', [...DIFF, ...range, '--'], undefined, overrides))).stdout) - if (scope.kind === 'staged') return { base: null, files: tracked, omitted: 0 } + if (scope.kind === 'staged') { + const shown = await bounded(git('attributes', ['show', `:${ATTRIBUTES_PATH}`], [0, 128])) + return { base: null, files: layers.classify(tracked, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 } + } const untracked = await untrackedFiles(ctx, config, git, root, signal) - return { base: fork === null || scope.kind !== 'branch' ? null : fork.label, files: [...tracked, ...untracked.files], omitted: untracked.omitted } + let attributes = '' + try { + attributes = decodeText(await readFile(ctx, config, root, ATTRIBUTES_PATH, signal)) ?? '' + } catch (error) { + if (!(error instanceof FsError && error.code === 'FS_NOT_FOUND')) throw error + } + return { + base: fork === null || scope.kind !== 'branch' ? null : fork.label, + files: layers.classify([...tracked, ...untracked.files], attributes), + omitted: untracked.omitted, + } } /** * Read the new side of one file in a scope, which supplies the unchanged - * lines between hunks: the index for `staged`, else the working tree. + * lines between hunks: the index for `staged`, the last chosen commit for + * chosen commits of the `branch` scope, else the working tree. * @param ctx - context that provides `fs`, `subprocess`, `sandbox`, and `sandboxPolicy`. * @param config - Git and size limits. * @param session - Session whose sandbox policy and execution world apply. @@ -219,9 +254,11 @@ export async function localText( ): Promise { if (!insideCheckout(path)) throw new Error(`forge-panel: ${JSON.stringify(path)} is not a path inside the checkout`) let text: string | undefined - if (scope.kind === 'staged') { + const commit = scope.kind === 'staged' ? '' : scope.kind === 'branch' && scope.commits !== null ? scope.commits.to : undefined + if (commit !== undefined) { + if (commit !== '' && !COMMIT.test(commit)) throw new CommitsMissing('The chosen commit is not a full object name') const git = gitIn(ctx, { ...config, maxOutputBytes: config.maxDiffBytes }, session, root, signal) - const shown = (await bounded(git('show', ['show', `:${path}`]))).stdout + const shown = (await bounded(git('show', ['show', `${commit}:${path}`]))).stdout text = shown.slice(0, BINARY_PROBE).includes('\0') ? undefined : shown } else { text = decodeText(await readFile(ctx, config, root, path, signal)) @@ -283,10 +320,57 @@ export async function aheadOf(git: Git, branch: string, commit: string): Promise return Number((await git('rev-list', ['rev-list', '--count', `${commit}..HEAD`])).stdout.trim()) } +/** + * List the commits of the `branch` scope: those reachable from HEAD but not from the fork point, parents before children. + * @param git - runner bound to the checkout, whose output limit bounds the listing. + * @param fork - fork point of the `branch` scope. + * @param limit - most commits listed. + * @returns the oldest `limit` commits and HEAD's commit. + * @throws an Error when Git fails or prints more than the runner's output limit. + */ +export async function localCommits(git: Git, fork: ForkPoint, limit: number): Promise { + const head = (await git('head', ['rev-parse', '--verify', 'HEAD'])).stdout.trim() + const all = await branchCommits(git, fork) + return { headSha: head, commits: all.slice(0, limit), truncated: all.length > limit } +} + +/** Every commit between the fork point and HEAD, parents before children. */ +async function branchCommits(git: Git, fork: ForkPoint): Promise { + const output = await git('log', ['log', '--topo-order', '--reverse', LOG_FORMAT, `${fork.commit}..HEAD`, '--']) + return output.stdout.split('\x1e').flatMap((record): ForgeCommit[] => { + const fields = record.replace(/^\n/, '').split('\0') + // The text after the last record holds no fields. + if (fields.length !== 5) return [] + const [sha, parents, author, authoredAt, title] = fields as [string, string, string, string, string] + return [{ sha, parent: /^\S+/.exec(parents)?.[0] ?? null, title, author, authoredAt }] + }) +} + +/** The committed changes of consecutive commits of the `branch` scope, from the first commit's first parent to the last. */ +async function commitsDiff(git: Git, fork: ForkPoint, chosen: ForgeCommitRange, layers: FileLayers): Promise { + if (!COMMIT.test(chosen.from) || !COMMIT.test(chosen.to)) throw new CommitsMissing('The chosen commits are not full object names') + const commits = await branchCommits(git, fork) + const first = commits.findIndex(commit => commit.sha === chosen.from) + const start = commits[first] + if (start === undefined || commits.findIndex(commit => commit.sha === chosen.to) < first) { + throw new CommitsMissing('The chosen commits are no longer on the branch') + } + // A first commit without a parent starts an unrelated history that HEAD merged; it adds every file. + const parent = start.parent ?? await emptyTree(git) + const overrides = await diffFilterOverrides(git) + const files = parseDiff((await bounded(git('diff', [...DIFF, parent, chosen.to, '--'], undefined, overrides))).stdout) + const shown = await bounded(git('attributes', ['show', `${chosen.to}:${ATTRIBUTES_PATH}`], [0, 128])) + return { base: fork.label, files: layers.classify(files, shown.exitCode === 0 ? shown.stdout : ''), omitted: 0 } +} + /** HEAD, or the empty tree while the checked-out branch has no commit. */ async function headOrEmptyTree(git: Git): Promise { const head = await git('head', ['rev-parse', '--verify', '--quiet', 'HEAD'], [0, 1]) - if (head.exitCode === 0) return 'HEAD' + return head.exitCode === 0 ? 'HEAD' : await emptyTree(git) +} + +/** The object name of the empty tree. */ +async function emptyTree(git: Git): Promise { return (await git('empty-tree', ['hash-object', '-t', 'tree', '--stdin'])).stdout.trim() } @@ -297,17 +381,17 @@ async function untrackedFiles( git: Git, root: string, signal: AbortSignal, -): Promise<{ readonly files: ForgeDiffFile[]; readonly omitted: number }> { +): Promise<{ readonly files: ParsedDiffFile[]; readonly omitted: number }> { const listed = await bounded(git('untracked', ['ls-files', '--others', '--exclude-standard', '-z'])) const paths = listed.stdout.split('\0').filter(path => path.length > 0 && !path.endsWith('/')) - const files: ForgeDiffFile[] = [] + const files: ParsedDiffFile[] = [] for (const path of paths.slice(0, config.maxUntrackedFiles)) { let content: Uint8Array try { content = await readFile(ctx, config, root, path, signal) } catch (error) { if (error instanceof DiffTooLarge) { - files.push({ ...untrackedFile(path, new Uint8Array()), oversized: true }) + files.push(oversizedUntrackedFile(path)) continue } if (error instanceof FsError) continue diff --git a/packages/experimental/client-ui-forge/src/patch-cache.ts b/packages/experimental/client-ui-forge/src/patch-cache.ts index 9ccc8d37e9..f331c08c19 100644 --- a/packages/experimental/client-ui-forge/src/patch-cache.ts +++ b/packages/experimental/client-ui-forge/src/patch-cache.ts @@ -1,22 +1,28 @@ /** - * Change request patches kept in memory, so the changes view reads no diff - * from the code host again while a change request keeps its head commit and base branch. + * Change request patches kept in memory with the repository attributes read beside them, so the changes view reads + * neither from the code host again while a change request keeps its head commit and base branch. */ import { Buffer } from 'node:buffer' import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge' +/** One change request's patch and the root `.gitattributes` text at its head commit, empty without one. */ +export interface CachedPatch { + readonly patch: string + readonly attributes: string +} + interface Entry { /** Head commit and base branch the patch was read at. */ readonly version: string - readonly patch: string - /** UTF-8 size of `patch`. */ + readonly value: CachedPatch + /** UTF-8 size of the patch and the attributes. */ readonly bytes: number } /** * One patch per change request, bounded by the total UTF-8 size of the kept - * patches; the least recently read patch leaves first. + * patches and their attributes; the least recently read patch leaves first. */ export class PatchCache { private readonly entries = new Map() @@ -29,14 +35,14 @@ export class PatchCache { * Read the patch kept for a change request at a version, marking it the most recently read. * @param key - the change request. * @param version - head commit and base branch the reader needs. - * @returns the patch, or undefined when none is kept at that version. + * @returns the patch and its attributes, or undefined when none is kept at that version. */ - get(key: ChangeRequestKey, version: string): string | undefined { + get(key: ChangeRequestKey, version: string): CachedPatch | undefined { const entry = this.entries.get(key) if (entry?.version !== version) return undefined this.entries.delete(key) this.entries.set(key, entry) - return entry.patch + return entry.value } /** @@ -44,13 +50,13 @@ export class PatchCache { * least recently read patches until the rest fit within `maxBytes`. * @param key - the change request. * @param version - head commit and base branch the patch was read at. - * @param patch - the patch. + * @param value - the patch and its attributes. */ - set(key: ChangeRequestKey, version: string, patch: string): void { + set(key: ChangeRequestKey, version: string, value: CachedPatch): void { this.remove(key) - const bytes = Buffer.byteLength(patch) + const bytes = Buffer.byteLength(value.patch) + Buffer.byteLength(value.attributes) if (bytes > this.maxBytes) return - this.entries.set(key, { version, patch, bytes }) + this.entries.set(key, { version, value, bytes }) this.bytes += bytes for (const oldest of this.entries.keys()) { if (this.bytes <= this.maxBytes) break diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 2a11e67ac6..64cebb0aa4 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -1,7 +1,7 @@ /** Browser-safe panel state, the worktree request record, Remote error codes, and Host configuration of the forge panel. */ import type {} from '@deepseek-ai/dsh-typert-protocol' -import type { ChangeRequestSnapshot, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ChangeRequestSnapshot, ForgeCommitList, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types' /** Git facts for the checkout that contains the Session's current directory. */ @@ -242,14 +242,26 @@ export interface ForgeBaseBranches { readonly local: readonly ForgeBaseBranch[] } +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +export interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} + /** Which local changes a diff covers; each reads the Session's checkout through Git. */ export type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -274,6 +286,12 @@ export interface ForgeDiffHunk { /** How one file changed. */ export type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +export type ForgeFileLayer = 'interface' | 'implementation' | 'test' + /** One changed file of a diff. */ export interface ForgeDiffFile { /** Path relative to the repository root after the change, or before it for a deleted file. */ @@ -294,6 +312,13 @@ export interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } /** Local changes of the Session's checkout in one scope. */ @@ -306,21 +331,24 @@ export interface ForgeLocalDiff { readonly omitted: number } -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ export interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +export type ForgeLocalCommits = ForgeCommitList + /** One file the `branch` scope changes, without its hunks. */ export interface ForgeChangedFile { /** Path relative to the repository root after the change. */ @@ -366,6 +394,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } declare module '@deepseek-ai/dsh-typert-protocol' { @@ -412,6 +449,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/checks-failed': Record /** The code host did not provide the change request's diff or file, or its status has not been read yet; the message says why. */ 'forgePanel/diff-failed': Record + /** A chosen commit is no longer among the listed commits of the branch or change request, or the commits are out of order. */ + 'forgePanel/commits-missing': Record } } diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index 89f380292c..feb7660187 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -501,7 +501,7 @@ describe('forgePanel local changes', () => { await writeFile(join(repo, 'notes.md'), 'hello\n') const opened = await open(repo) - const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) + const diff = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal) expect(diff.base).toBe('origin/main') expect(diff.files.map(file => [file.path, file.status, file.untracked])).toEqual([['tracked.txt', 'modified', false], ['notes.md', 'added', true]]) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'staged' }, signal)).resolves.toEqual({ base: null, files: [], omitted: 0 }) @@ -519,22 +519,57 @@ describe('forgePanel local changes', () => { const opened = await open(repo) const paths = (diff: ForgeLocalDiff): string[] => diff.files.map(file => file.path) - const automatic = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal) + const automatic = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal) expect([automatic.base, paths(automatic)]).toEqual(['origin/main', ['feature.txt', 'notes.md']]) - const chosen = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/topic' }, signal) + const chosen = await opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/topic', commits: null }, signal) expect([chosen.base, paths(chosen)]).toEqual(['topic', ['notes.md']]) await expect(opened.ctx.forgePanel.diffBases(opened.session, '', signal)).resolves.toEqual({ automatic: { name: 'origin/main', worktree: false }, remote: [{ ref: 'refs/remotes/origin/main', name: 'origin/main' }], local: [{ ref: 'refs/heads/topic', name: 'topic' }], }) - await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/gone' }, signal)) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: 'refs/heads/gone', commits: null }, signal)) .rejects.toMatchObject({ code: 'forgePanel/base-missing' }) const outside = await open(await plain()) await expect(outside.ctx.forgePanel.diffBases(outside.session, '', signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) }) + it('lists the commits of the branch scope and reads chosen ones', async () => { + const { repo } = await project() + await withDefaultBranch(repo) + for (const name of ['one', 'two', 'three']) { + await writeFile(join(repo, `${name}.txt`), `${name}\n`) + await git(repo, 'add', `${name}.txt`) + await git(repo, 'commit', '--quiet', '-m', name) + } + await git(repo, 'branch', 'topic', 'HEAD~1') + await writeFile(join(repo, 'notes.md'), 'hello\n') + const opened = await open(repo, { maxCommits: 2 }) + + const listed = await opened.ctx.forgePanel.localCommits(opened.session, null, signal) + expect(listed).toMatchObject({ truncated: true, headSha: await git(repo, 'rev-parse', 'HEAD') }) + expect(listed.commits.map(commit => commit.title)).toEqual(['one', 'two']) + await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/topic', signal)) + .resolves.toMatchObject({ truncated: false, commits: [{ title: 'three' }] }) + const [one, two] = listed.commits.map(commit => commit.sha) + const chosen = await opened.ctx.forgePanel.localDiff(opened.session, + { kind: 'branch', base: null, commits: { from: one ?? '', to: two ?? '' } }, signal) + expect(chosen.files.map(file => file.path)).toEqual(['one.txt', 'two.txt']) + await expect(opened.ctx.forgePanel.localText(opened.session, + { kind: 'branch', base: null, commits: { from: one ?? '', to: one ?? '' } }, 'one.txt', signal)).resolves.toBe('one\n') + await expect(opened.ctx.forgePanel.localDiff(opened.session, + { kind: 'branch', base: 'refs/heads/topic', commits: { from: one ?? '', to: two ?? '' } }, signal)) + .rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/gone', signal)).rejects.toMatchObject({ code: 'forgePanel/base-missing' }) + + const unrelated = await project() + const lonely = await open(unrelated.repo) + await expect(lonely.ctx.forgePanel.localCommits(lonely.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) + const outside = await open(await plain()) + await expect(outside.ctx.forgePanel.localCommits(outside.session, null, signal)).rejects.toMatchObject({ code: 'forgePanel/not-a-checkout' }) + }) + it('lists more refs than other Git output may print, up to maxDiffBytes', async () => { const { repo } = await project() await withDefaultBranch(repo) @@ -561,7 +596,7 @@ describe('forgePanel local changes', () => { const { repo } = await project() await writeFile(join(repo, 'tracked.txt'), 'x\n'.repeat(2000)) const opened = await open(repo, { maxDiffBytes: 1024 }) - await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) + await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'branch', base: null, commits: null }, signal)).rejects.toMatchObject({ code: 'forgePanel/no-fork-point' }) await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'unstaged' }, signal)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) @@ -607,7 +642,7 @@ describe('forgePanel change request diffs', () => { shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) await reader(opened).until(state => polled(state, pullUrl(7))) - const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal) + const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) expect(diff).toMatchObject({ headSha: head, localAhead: 1, fileUrls: { 'src/a.ts': `${pullUrl(7)}/files/${head}/src/a.ts` } }) expect(diff.files.map(file => [file.path, file.additions, file.deletions])).toEqual([['src/a.ts', 1, 1]]) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), head, 'src/a.ts', signal)).resolves.toBe('new\n') @@ -621,7 +656,8 @@ describe('forgePanel change request diffs', () => { await reader(opened).until(state => polled(state, pullUrl(7))) opened.sandbox.failure = new Error('sandbox unavailable') - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)).resolves.toMatchObject({ localAhead: null }) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) + .resolves.toMatchObject({ localAhead: null }) }) it('downloads a diff once per head commit and base branch for every Session, keeping no failed read', async () => { @@ -631,7 +667,7 @@ describe('forgePanel change request diffs', () => { const follower = reader(opened) await follower.until(state => polled(state, pullUrl(7))) const paths = async (session: Session = opened.session): Promise => - (await opened.ctx.forgePanel.changeRequestDiff(session, pullUrl(7), signal)).files.map(file => file.path) + (await opened.ctx.forgePanel.changeRequestDiff(session, pullUrl(7), null, signal)).files.map(file => file.path) const moved = async (snapshot: { headSha: string; baseBranch: string }): Promise => { opened.provider.overrides.set(7, snapshot) await opened.ctx.forgePanel.refresh(opened.session, signal) @@ -657,6 +693,63 @@ describe('forgePanel change request diffs', () => { expect(opened.provider.diffs).toEqual([7, 7, 7, 7]) }) + it('classifies files by the root .gitattributes at the head and refuses attributes the host does not provide', async () => { + const { repo } = await project() + const opened = await open(repo) + const head = 'a'.repeat(40) + opened.provider.patches.set(7, `${PATCH}${PATCH.replaceAll('src/a.ts', 'gen/b.ts')}${PATCH.replaceAll('src/a.ts', 'src/a.spec.ts')}`) + opened.provider.texts.set(`${head}:.gitattributes`, 'gen/** linguist-generated\n') + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => polled(state, pullUrl(7))) + + const diff = await opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal) + expect(diff.files.map(file => [file.path, file.layer])).toEqual([['src/a.ts', 'implementation'], ['gen/b.ts', 'test'], ['src/a.spec.ts', 'test']]) + + const other = await open(repo) + other.provider.patches.set(7, PATCH) + other.provider.texts.set(`${head}:.gitattributes`, { code: 'unavailable', message: 'down' }) + shellTurn(other.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(other).until(state => polled(state, pullUrl(7))) + await expect(other.ctx.forgePanel.changeRequestDiff(other.session, pullUrl(7), null, signal)) + .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'down' }) + }) + + it('lists the commits of a change request and reads consecutive ones from the first one\'s parent', async () => { + const { repo } = await project() + const opened = await open(repo) + const sha = (n: number): string => String(n).repeat(40) + const commit = (n: number, parent: string | null) => ({ sha: sha(n), parent, title: `c${n}`, author: 'octo', authoredAt: '2026-10-09T00:00:00Z' }) + const list = { headSha: sha(3), truncated: false, commits: [commit(1, null), commit(2, sha(1)), commit(3, sha(2))] } + opened.provider.commitLists.set(7, list) + opened.provider.comparisons.set(`${sha(1)}..${sha(3)}`, PATCH) + opened.provider.texts.set(`${sha(3)}:.gitattributes`, 'src/** linguist-generated\n') + shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) + await reader(opened).until(state => polled(state, pullUrl(7))) + const read = (from: number, to: number) => + opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), { from: sha(from), to: sha(to) }, signal) + + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).resolves.toEqual(list) + await expect(read(2, 3)).resolves.toEqual({ + headSha: sha(3), localAhead: null, fileUrls: { 'src/a.ts': `${pullUrl(7)}/files/${sha(3)}/src/a.ts` }, + files: [expect.objectContaining({ path: 'src/a.ts', layer: 'test' })], + }) + expect(opened.provider.diffs).toEqual([]) + await expect(read(1, 1)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The first chosen commit has no parent to compare with' }) + await expect(read(3, 2)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(read(4, 3)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: `no comparison ${sha(2)}..${sha(3)}` }) + opened.provider.comparisons.set(`${sha(2)}..${sha(3)}`, { code: 'too-large', message: 'too many files' }) + await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) + + opened.provider.commitLists.set(7, { code: 'unavailable', message: 'down' }) + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).rejects.toMatchObject({ code: 'forgePanel/diff-failed' }) + await expect(read(2, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'down' }) + delete opened.provider.commits + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(7), signal)).resolves.toBeNull() + await expect(read(2, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The code host provider does not read commits' }) + await expect(opened.ctx.forgePanel.changeRequestCommits(opened.session, pullUrl(9), signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + }) + it('reports a diff or file over a size limit as too large', async () => { const { repo } = await project() const opened = await open(repo) @@ -666,7 +759,7 @@ describe('forgePanel change request diffs', () => { shellTurn(opened.session, 1, [{ callId: 'create', command: 'gh pr create --fill', output: `${pullUrl(7)}\n` }]) await reader(opened).until(state => polled(state, pullUrl(7))) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large', message: 'the diff exceeded the maximum number of files (300)' }) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), head, 'big.bin', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-too-large', message: 'big.bin is too large to fetch' }) @@ -682,10 +775,10 @@ describe('forgePanel change request diffs', () => { ]) await reader(opened).until(state => polled(state, pullUrl(7)) && failing(state, pullUrl(8))) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(9), signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(8), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(9), null, signal)).rejects.toMatchObject({ code: 'forgePanel/not-bound' }) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(8), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The change request status has not been read yet' }) - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), signal)) + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(7), null, signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'no diff of #7' }) await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(7), 'a'.repeat(40), 'gone.ts', signal)) .rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: `no gone.ts at ${'a'.repeat(40)}` }) @@ -1713,7 +1806,7 @@ describe('forgePanel actions', () => { await expect(opened.ctx.forgePanel.refresh(opened.session, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.localDiff(opened.session, { kind: 'unstaged' }, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.localText(opened.session, { kind: 'unstaged' }, 'tracked.txt', controller.signal)).rejects.toThrow('closed') - await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') + await expect(opened.ctx.forgePanel.changeRequestDiff(opened.session, pullUrl(1), null, controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.changeRequestText(opened.session, pullUrl(1), 'a'.repeat(40), 'x', controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.markReady(opened.session, pullUrl(1), controller.signal)).rejects.toThrow('closed') await expect(opened.ctx.forgePanel.merge(opened.session, pullUrl(1), 'merge', 'a'.repeat(40), controller.signal)).rejects.toThrow('closed') @@ -1765,6 +1858,9 @@ describe('forgePanel configuration', () => { [{ maxBranches: 0 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxBranches: 2.5 }, 'forge-panel: maxBranches must be a positive integer'], [{ maxCachedDiffBytes: 0 }, 'forge-panel: maxCachedDiffBytes must be a positive integer'], + [{ maxCommits: 0 }, 'forge-panel: maxCommits must be a positive integer'], + [{ testPaths: ['**/*.spec.*', ' '] }, 'forge-panel: testPaths entries must not be empty'], + [{ interfacePaths: [''] }, 'forge-panel: interfacePaths entries must not be empty'], [{ worktreePrefix: '-dsh/' }, prefix], [{ worktreePrefix: 'dsh /' }, prefix], [{ worktreePrefix: 'dsh:' }, prefix], diff --git a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts index 0d8aab0297..598109e93e 100644 --- a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts @@ -1,6 +1,6 @@ /** Patch parsing into the panel's diff model, untracked files as added in full, and numstat records. */ import { describe, expect, it } from 'vitest' -import { decodeText, parseDiff, parseNumstat, untrackedFile } from '../src/diff.ts' +import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from '../src/diff.ts' /** * A `git diff` patch with a binary change, a pure rename, a quoted path, a path @@ -82,6 +82,26 @@ describe('parseDiff', () => { expect(files[7]?.hunks).toEqual([{ oldStart: 1, oldLines: 2, newStart: 1, newLines: 0, lines: ['-q', '-z'] }]) }) + it('digests each change by its paths, status, and hunks, and a binary change by its blob names', () => { + const files = parseDiff(PATCH) + const digests = files.map(file => file.digest) + expect(new Set(digests).size).toBe(files.length) + expect(digests.every(digest => /^[0-9a-f]{32}$/.test(digest))).toBe(true) + expect(parseDiff(PATCH).map(file => file.digest)).toEqual(digests) + const edited = parseDiff(PATCH.replace('+B', '+C')).map(file => file.digest) + expect(edited.filter((digest, index) => digest !== digests[index])).toHaveLength(1) + expect(edited[3]).not.toBe(digests[3]) + expect(parseDiff(PATCH.replace('index bdc955b..8352675', 'index bdc955b..0000001'))[0]?.digest).not.toBe(digests[0]) + }) + + it('digests a binary change without its blob names when a section does not start with a Git header', () => { + const binary = 'diff --git a/x.png b/x.png\nindex 1111111..2222222 100644\nBinary files a/x.png and b/x.png differ\n' + const withLeader = `--- a/y\n+++ b/y\n@@ -1 +1 @@\n-a\n+b\n${binary}` + const other = withLeader.replace('2222222', '3333333') + expect(parseDiff(withLeader)[1]?.digest).toBe(parseDiff(other)[1]?.digest) + expect(parseDiff(binary)[0]?.digest).not.toBe(parseDiff(binary.replace('2222222', '3333333'))[0]?.digest) + }) + it('takes paths without a prefix as they are and skips a section without a path', () => { expect(parseDiff('--- old\n+++ new\n@@ -1 +1 @@\n-a\n+b\n').map(file => [file.path, file.status])).toEqual([['new', 'modified']]) expect(parseDiff('')).toEqual([]) @@ -94,10 +114,20 @@ describe('untrackedFile', () => { ['no final newline', 'one\ntwo', ['+one', '+two', '\\ No newline at end of file']], ['carriage returns', 'one\r\ntwo\r\n', ['+one\r', '+two\r']], ])('adds every line of a text file with %s', (_label, text, lines) => { - expect(untrackedFile('notes/new.md', new TextEncoder().encode(text))).toEqual({ + const { digest, ...added } = untrackedFile('notes/new.md', new TextEncoder().encode(text)) + expect(added).toEqual({ path: 'notes/new.md', previousPath: null, status: 'added', binary: false, oversized: false, untracked: true, additions: 2, deletions: 0, hunks: [{ oldStart: 1, oldLines: 0, newStart: 1, newLines: 2, lines }], }) + expect(digest).toMatch(/^[0-9a-f]{32}$/) + }) + + it('digests binary content by its bytes and an oversized file by its path alone', () => { + const digest = (bytes: number[]): string => untrackedFile('blob', Uint8Array.from(bytes)).digest + expect(digest([0, 1])).toBe(digest([0, 1])) + expect(digest([0, 1])).not.toBe(digest([0, 2])) + expect(oversizedUntrackedFile('big.log')).toMatchObject({ oversized: true, binary: false, hunks: [], untracked: true }) + expect(oversizedUntrackedFile('big.log').digest).not.toBe(untrackedFile('big.log', new Uint8Array()).digest) }) it('describes an empty file without a hunk', () => { diff --git a/packages/experimental/client-ui-forge/tests/harness.ts b/packages/experimental/client-ui-forge/tests/harness.ts index 652de1a153..6dd6e7dc18 100644 --- a/packages/experimental/client-ui-forge/tests/harness.ts +++ b/packages/experimental/client-ui-forge/tests/harness.ts @@ -12,8 +12,8 @@ import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import { createInboxStub, unsupportedModel } from '@deepseek-ai/dsh-agent-loop-testkit' import ForgeService, { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { - ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeFailure, ForgeProvider, ForgeReadiness, - ForgeRepository, MergeRequest, + ChangeRequestKey, ChangeRequestRef, ChangeRequestSnapshot, ForgeActionFailure, ForgeCommitList, ForgeFailure, ForgeProvider, + ForgeReadiness, ForgeRepository, MergeRequest, } from '@deepseek-ai/dsh-experimental-forge' import ForgeSessionService from '@deepseek-ai/dsh-experimental-forge-session' import WorktreeService from '@deepseek-ai/dsh-experimental-worktree' @@ -291,6 +291,17 @@ export class FakeProvider implements ForgeProvider { readonly heads = new Map() /** Head lookups in call order, as `/ `. */ readonly lookups: string[] = [] + /** Commit lists or failures by change request number; others return a not-found failure. */ + readonly commitLists = new Map() + /** Patches or failures between two commits by `..`; others return a not-found failure. */ + readonly comparisons = new Map() + /** Commit listing; a test deletes it to stand for a provider that does not read commits. */ + commits?: (ref: ChangeRequestRef, signal: AbortSignal) => Promise = (ref: ChangeRequestRef) => + Promise.resolve(this.commitLists.get(ref.number) ?? { code: 'not-found', message: `no commits of #${ref.number}` }) + /** Comparison of two commits. */ + compare?: (ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal) => Promise = + (_ref: ChangeRequestRef, base: string, head: string) => + Promise.resolve(this.comparisons.get(`${base}..${head}`) ?? { code: 'not-found', message: `no comparison ${base}..${head}` }) repositoryFromRemote(url: string): ForgeRepository | undefined { const [, host = '', owner = '', name = ''] = /^https:\/\/([a-z.]+\.test)\/([^/]+)\/([^/]+?)\.git$/.exec(url) ?? [] diff --git a/packages/experimental/client-ui-forge/tests/layers.host.spec.ts b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts new file mode 100644 index 0000000000..172ebc57d6 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts @@ -0,0 +1,65 @@ +/** Review layers of changed files: path globs and the `linguist-generated` attribute of a root `.gitattributes`. */ +import { describe, expect, it } from 'vitest' +import { untrackedFile } from '../src/diff.ts' +import { FileLayers, generatedMatcher } from '../src/layers.ts' + +describe('generatedMatcher', () => { + it('applies lines in order, with unset and unspecified values overriding an earlier set', () => { + const generated = generatedMatcher([ + '# comment', + '', + '[attr]binary -diff -merge -text', + '"quoted name.json" linguist-generated', + 'build/ linguist-generated', + '*.schema.json linguist-generated=true', + 'docs/kept.schema.json -linguist-generated', + 'docs/reset.schema.json !linguist-generated', + 'docs/off.schema.json linguist-generated=false', + '/root.gen.ts linguist-generated', + 'gen/*.ts text linguist-generated', + 'other.txt text', + ].join('\r\n')) + + expect(generated('a.schema.json')).toBe(true) + expect(generated('docs/deep/a.schema.json')).toBe(true) + expect(generated('docs/kept.schema.json')).toBe(false) + expect(generated('docs/reset.schema.json')).toBe(false) + expect(generated('docs/off.schema.json')).toBe(false) + expect(generated('root.gen.ts')).toBe(true) + expect(generated('nested/root.gen.ts')).toBe(false) + expect(generated('gen/a.ts')).toBe(true) + expect(generated('src/gen/a.ts')).toBe(false) + expect(generated('build/out.js')).toBe(false) + expect(generated('quoted name.json')).toBe(false) + expect(generated('other.txt')).toBe(false) + }) + + it('marks nothing without attributes', () => { + expect(generatedMatcher('')('a.ts')).toBe(false) + }) +}) + +describe('FileLayers', () => { + const file = (path: string) => untrackedFile(path, new Uint8Array()) + + it('places a file in the test layer first, then the interface layer, else the implementation layer', () => { + const layers = new FileLayers(['**/*.spec.*', '**/locale/*.json'], ['**/package.json', '**/*.json']) + const classified = layers.classify( + ['src/a.ts', 'src/a.spec.ts', 'package.json', 'locale/en.json', 'docs/schema.json', '.github/x.json'].map(file), + 'docs/schema.json linguist-generated\n', + ) + + expect(classified.map(item => [item.path, item.layer])).toEqual([ + ['src/a.ts', 'implementation'], + ['src/a.spec.ts', 'test'], + ['package.json', 'interface'], + ['locale/en.json', 'test'], + ['docs/schema.json', 'test'], + ['.github/x.json', 'interface'], + ]) + }) + + it('places every file in the implementation layer without globs or attributes', () => { + expect(new FileLayers([], []).classify([file('a.spec.ts')], '')).toMatchObject([{ layer: 'implementation' }]) + }) +}) diff --git a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts index 0a2d95cdfc..1019374d67 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff-safety.host.spec.ts @@ -8,8 +8,11 @@ import { setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' import { inspectCheckout } from '../src/git.ts' import { FilterConfigError, localChanges, localDiff } from '../src/local-diff.ts' import type { DiffConfig } from '../src/local-diff.ts' +import { FileLayers } from '../src/layers.ts' import { git, gitContext, plainSession, repository, sandboxRecord, scratch } from './harness.ts' +const LAYERS = new FileLayers([], []) + const CONFIG: DiffConfig = { gitCommand: 'git', gitTimeoutMs: 10_000, graceMs: 500, maxOutputBytes: 1_048_576, maxDiffBytes: 1_048_576, maxUntrackedFiles: 100, } @@ -54,7 +57,7 @@ describe('diff helper restrictions', () => { const spawn = vi.spyOn(b.ctx.subprocess, 'spawn') try { - await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) const diffs = spawn.mock.calls.map(([spec]) => spec).filter(spec => spec.argv.includes('diff')) expect(diffs).toHaveLength(2) @@ -90,7 +93,7 @@ describe('diff helper restrictions', () => { expect(await readFile(marker, 'utf8')).toBe('ran') await rm(marker) - await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(marker)).rejects.toThrow() }) @@ -103,7 +106,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', 'filter.demo.clean', `${b.command} clean`) await writeFile(join(b.repo, 'tracked.txt'), 'initial\r\n') - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) const changes = await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) expect(diff.files).toEqual([]) expect(changes?.files.some(file => file.path === 'tracked.txt')).toBe(false) @@ -124,7 +127,7 @@ describe('diff helper restrictions', () => { const index = await readFile(join(b.repo, '.git', 'index')) const indexStat = await stat(join(b.repo, '.git', 'index')) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) const changes = await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) expect(diff.files.find(file => file.path === 'tracked.txt')?.hunks.flatMap(hunk => hunk.lines)).toEqual(['-initial', '+changed']) @@ -145,7 +148,7 @@ describe('diff helper restrictions', () => { expect(await readFile(b.marker, 'utf8')).toBe('ran') await rm(b.marker) - await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(b.marker)).rejects.toThrow() }) @@ -156,7 +159,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', key, b.command) await writeFile(join(b.repo, 'tracked.txt'), 'changed\n') - await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, b.signal) + await localDiff(b.ctx, CONFIG, b.session, b.repo, b.fork, { kind: 'unstaged' }, LAYERS, b.signal) await localChanges(b.ctx, CONFIG, b.session, b.inspection, null, b.signal) await expect(access(b.marker)).rejects.toThrow() }) @@ -170,7 +173,7 @@ describe('diff helper restrictions', () => { await writeFile(join(nested, 'tracked.txt'), 'dirty\n') await git(nested, 'config', 'core.fsmonitor', b.command) await git(b.repo, 'config', 'diff.submodule', 'diff') - const clean = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const clean = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(clean.files).toEqual([]) await expect(access(b.marker)).rejects.toThrow() @@ -179,7 +182,7 @@ describe('diff helper restrictions', () => { await git(nested, 'config', 'user.email', 'forge@example.invalid') await git(nested, '-c', 'commit.gpgSign=false', 'commit', '-am', 'nested change') await git(nested, 'config', 'core.fsmonitor', b.command) - const changed = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const changed = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(changed.files.map(file => file.path)).toEqual(['nested']) expect(changed.files[0]?.hunks.flatMap(hunk => hunk.lines).join('\n')).toContain('Subproject commit') await expect(access(b.marker)).rejects.toThrow() @@ -190,7 +193,7 @@ describe('diff helper restrictions', () => { await git(b.repo, 'config', `filter.${'long'.repeat(200)}.clean`, b.command) await writeFile(join(b.repo, '.gitattributes'), `tracked.txt filter=${'long'.repeat(200)}\n`) await writeFile(join(b.repo, 'tracked.txt'), 'changed\n') - await expect(localDiff(b.ctx, { ...CONFIG, maxDiffBytes: 128 }, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)) + await expect(localDiff(b.ctx, { ...CONFIG, maxDiffBytes: 128 }, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)) .rejects.toBeInstanceOf(FilterConfigError) await expect(localChanges(b.ctx, { ...CONFIG, maxOutputBytes: 128 }, b.session, b.inspection, null, b.signal)) .rejects.toBeInstanceOf(FilterConfigError) @@ -203,7 +206,7 @@ describe('diff helper restrictions', () => { const resolve = vi.spyOn(b.ctx.subprocess, 'resolveExecutable').mockRejectedValue(failure) const spawn = vi.spyOn(b.ctx.subprocess, 'spawn') try { - await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)) + await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)) .rejects.toMatchObject({ name: 'FilterConfigError', cause: failure }) expect(spawn).not.toHaveBeenCalled() } finally { resolve.mockRestore(); spawn.mockRestore() } @@ -218,9 +221,9 @@ describe('diff helper restrictions', () => { await git(b.repo, 'commit', '-m', 'pointer') await git(b.repo, 'config', 'filter.lfs.process', b.command) await git(b.repo, 'config', 'filter.lfs.required', 'true') - await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal)).resolves.toMatchObject({ files: [] }) + await expect(localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal)).resolves.toMatchObject({ files: [] }) await writeFile(join(b.repo, 'asset.bin'), Uint8Array.from([0, 1, 2, 3])) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(diff.files).toMatchObject([{ path: 'asset.bin', binary: true, hunks: [] }]) await expect(access(b.marker)).rejects.toThrow() }) @@ -241,7 +244,7 @@ describe('diff helper restrictions', () => { expect(await readFile(b.marker, 'utf8')).toBe('ran') await rm(b.marker) - const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, b.signal) + const diff = await localDiff(b.ctx, CONFIG, b.session, b.repo, null, { kind: 'unstaged' }, LAYERS, b.signal) expect(diff.files).toMatchObject([{ path: 'asset.txt', additions: 1, deletions: 3 }]) await expect(access(b.marker)).rejects.toThrow() }) diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index 53e1a4a925..7c7f74b9c6 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -7,9 +7,11 @@ import { FsError } from '@deepseek-ai/dsh-fs' import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, DiffTooLarge, forkPoint, localChanges, localDiff, localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, forkPoint, localChanges, localCommits, localDiff, + localText, NoForkPoint, } from '../src/local-diff.ts' -import type { DiffConfig } from '../src/local-diff.ts' +import type { DiffConfig, ForkPoint } from '../src/local-diff.ts' +import { FileLayers } from '../src/layers.ts' import type { ForgeLocalScope, ForgeSessionWorktree } from '../src/types.ts' import { git, gitContext, plainSession, repository, sandboxRecord, scratch } from './harness.ts' @@ -17,6 +19,9 @@ const CONFIG: DiffConfig = { gitCommand: 'git', gitTimeoutMs: 10_000, graceMs: 500, maxOutputBytes: 1_048_576, maxDiffBytes: 1_048_576, maxUntrackedFiles: 100, } +/** Text files form the `test` layer and JSON files the `interface` layer. */ +const LAYERS = new FileLayers(['**/untracked.txt'], ['**/*.json']) + const cleanups: (() => Promise)[] = [] afterEach(async () => { @@ -203,14 +208,14 @@ describe('baseBranches', () => { describe('localDiff', () => { it.each([ - [{ kind: 'branch', base: null }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], + [{ kind: 'branch', base: null, commits: null }, 'origin/main', ['committed.txt added', 'staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'uncommitted' }, null, ['staged.txt added', 'tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'unstaged' }, null, ['tracked.txt modified', 'untracked.txt added untracked']], [{ kind: 'staged' }, null, ['staged.txt added']], ] as const)('reads the %o scope with untracked files last, leaving out ignored files and nested repositories', async (scope, base, files) => { const { repo, fork } = await forked(await directory()) const ctx = await context(repo) - const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, scope, signal) + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, scope, LAYERS, signal) expect(diff.base).toBe(base) expect(diff.omitted).toBe(0) @@ -219,7 +224,7 @@ describe('localDiff', () => { it('carries the hunks of tracked and untracked files', async () => { const { repo, fork } = await forked(await directory()) - const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, { kind: 'unstaged' }, signal) + const diff = await localDiff(await context(repo), CONFIG, plainSession(repo), repo, { commit: fork, label: 'origin/main', worktree: false }, { kind: 'unstaged' }, LAYERS, signal) expect(diff.files.map(file => [file.additions, file.deletions, file.hunks.flatMap(hunk => hunk.lines)])).toEqual([ [1, 0, [' initial', '+changed']], @@ -230,7 +235,7 @@ describe('localDiff', () => { it('refuses the branch scope without a fork point', async () => { const { repo } = await forked(await directory()) - await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch', base: null }, signal)).rejects.toBeInstanceOf(NoForkPoint) + await expect(localDiff(await context(repo), CONFIG, plainSession(repo), repo, null, { kind: 'branch', base: null, commits: null }, LAYERS, signal)).rejects.toBeInstanceOf(NoForkPoint) }) it('compares a branch without commits with the empty tree', async () => { @@ -242,7 +247,7 @@ describe('localDiff', () => { const ctx = await context(repo) for (const kind of ['staged', 'uncommitted'] as const) { - const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, null, { kind }, signal) + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, null, { kind }, LAYERS, signal) expect(diff.files.map(file => [file.path, file.status])).toEqual([['first.txt', 'added']]) } }) @@ -251,7 +256,7 @@ describe('localDiff', () => { const { repo, fork } = await forked(await directory()) await writeFile(join(repo, 'tracked.txt'), 'line\n'.repeat(400)) - await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) + await expect(localDiff(await context(repo), { ...CONFIG, maxDiffBytes: 512 }, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal)) .rejects.toBeInstanceOf(DiffTooLarge) }) @@ -269,7 +274,7 @@ describe('localDiff', () => { return await read(target, readSignal, maxBytes) }) const config = { ...CONFIG, maxDiffBytes: 2048, maxUntrackedFiles: 4 } - const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal) + const diff = await localDiff(ctx, config, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal) expect(diff.files.filter(file => file.untracked).map(file => [file.path, file.binary, file.oversized, file.additions])).toEqual([ ['more/big.txt', false, true, 0], @@ -284,13 +289,137 @@ describe('localDiff', () => { const ctx = await context(repo) vi.spyOn(ctx.fs, 'readBytes').mockRejectedValue(new Error('disk on fire')) - await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, signal)) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, { commit: fork, label: 'x', worktree: false }, { kind: 'unstaged' }, LAYERS, signal)) .rejects.toThrow('disk on fire') }) }) +describe('review layers', () => { + it('classifies files by the globs and the root .gitattributes of the working tree, or of the index for the staged scope', async () => { + const { repo, fork } = await forked(await directory()) + const point = { commit: fork, label: 'origin/main', worktree: false } + await writeFile(join(repo, 'config.json'), '{}\n') + await writeFile(join(repo, '.gitattributes'), 'tracked.txt linguist-generated\n') + const ctx = await context(repo) + const layers = async (scope: ForgeLocalScope): Promise => + (await localDiff(ctx, CONFIG, plainSession(repo), repo, point, scope, LAYERS, signal)).files.map(file => `${file.path} ${file.layer}`) + + expect(await layers({ kind: 'unstaged' })).toEqual([ + 'tracked.txt test', '.gitattributes implementation', 'config.json interface', 'untracked.txt test', + ]) + await writeFile(join(repo, '.gitattributes'), 'staged.txt linguist-generated\n') + await git(repo, 'add', '.gitattributes') + await writeFile(join(repo, '.gitattributes'), '') + expect(await layers({ kind: 'staged' })).toEqual(['.gitattributes implementation', 'staged.txt test']) + expect(await layers({ kind: 'uncommitted' })).toEqual([ + '.gitattributes implementation', 'staged.txt implementation', 'tracked.txt implementation', 'config.json interface', 'untracked.txt test', + ]) + }) + + it('reads no attributes for a staged scope without .gitattributes and stops at an unreadable working tree file', async () => { + const { repo, fork } = await forked(await directory()) + const ctx = await context(repo) + const point = { commit: fork, label: 'origin/main', worktree: false } + + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'staged' }, LAYERS, signal)) + .resolves.toMatchObject({ files: [{ path: 'staged.txt', layer: 'implementation' }] }) + await writeFile(join(repo, '.gitattributes'), Uint8Array.from([0x74, 0, 0x74])) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'unstaged' }, LAYERS, signal)) + .resolves.toMatchObject({ files: [{ path: 'tracked.txt', layer: 'implementation' }, { path: '.gitattributes' }, { path: 'untracked.txt' }] }) + const read = ctx.fs.readBytes.bind(ctx.fs) + vi.spyOn(ctx.fs, 'readBytes').mockImplementation(async (target, readSignal, maxBytes) => { + if (ctx.fs.processPath(target).endsWith('.gitattributes')) throw new FsError('denied', 'FS_PERMISSION_DENIED') + return await read(target, readSignal, maxBytes) + }) + await expect(localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'unstaged' }, LAYERS, signal)).rejects.toThrow('denied') + }) +}) + +describe('commits of the branch scope', () => { + /** {@link forked} with two more commits on `feat`, `second.txt` and then `.gitattributes` with a generated `third.json`. */ + async function committed(): Promise<{ readonly repo: string; readonly point: ForkPoint; readonly shas: readonly string[] }> { + const { repo, fork } = await forked(await directory()) + await git(repo, 'commit', '--quiet', '-m', 'staged') + await writeFile(join(repo, 'second.txt'), 'two\n') + await git(repo, 'add', 'second.txt') + await git(repo, 'commit', '--quiet', '-m', 'second') + await writeFile(join(repo, '.gitattributes'), 'third.json linguist-generated\n') + await writeFile(join(repo, 'third.json'), '{}\n') + await git(repo, 'add', '.gitattributes', 'third.json') + await git(repo, 'commit', '--quiet', '-m', 'third') + const shas = (await git(repo, 'rev-list', '--reverse', `${fork}..HEAD`)).split('\n') + return { repo, point: { commit: fork, label: 'origin/main', worktree: false }, shas } + } + + it('lists the commits between the fork point and HEAD oldest first, bounded by the limit', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const runner = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) + + const listed = await localCommits(runner, point, 10) + expect(listed).toMatchObject({ headSha: shas.at(-1), truncated: false }) + expect(listed.commits.map(commit => [commit.title, commit.author])).toEqual([ + ['committed', 'Forge fixture'], ['staged', 'Forge fixture'], ['second', 'Forge fixture'], ['third', 'Forge fixture'], + ]) + expect(listed.commits.map(commit => commit.sha)).toEqual(shas) + expect(listed.commits.map(commit => commit.parent)).toEqual([point.commit, ...shas.slice(0, -1)]) + expect(Date.parse(listed.commits[0]?.authoredAt ?? '')).not.toBeNaN() + await expect(localCommits(runner, point, 2)).resolves.toMatchObject({ truncated: true, commits: [{ title: 'committed' }, { title: 'staged' }] }) + }) + + it('reads the committed changes of consecutive commits with the attributes of the last one, without working tree changes', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const range = async (from: number, to: number): Promise => { + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, point, + { kind: 'branch', base: null, commits: { from: shas[from] ?? '', to: shas[to] ?? '' } }, LAYERS, signal) + expect(diff).toMatchObject({ base: 'origin/main', omitted: 0 }) + return diff.files.map(file => `${file.path} ${file.layer}`) + } + + expect(await range(2, 2)).toEqual(['second.txt implementation']) + expect(await range(1, 3)).toEqual(['.gitattributes implementation', 'second.txt implementation', 'staged.txt implementation', 'third.json test']) + await expect(localText(ctx, CONFIG, plainSession(repo), repo, + { kind: 'branch', base: null, commits: { from: shas[2] ?? '', to: shas[2] ?? '' } }, 'second.txt', signal)).resolves.toBe('two\n') + }) + + it('compares a first commit without a parent with the empty tree', async () => { + const { repo, point } = await committed() + await git(repo, 'checkout', '--quiet', '--orphan', 'other') + await git(repo, 'rm', '--quiet', '-r', '-f', '--cached', '.') + await writeFile(join(repo, 'orphan.txt'), 'root\n') + await git(repo, 'add', 'orphan.txt') + await git(repo, 'commit', '--quiet', '-m', 'orphan') + const orphan = await git(repo, 'rev-parse', 'HEAD') + await git(repo, 'checkout', '--quiet', '--force', 'feat') + await git(repo, 'merge', '--quiet', '--allow-unrelated-histories', '--no-edit', 'other') + const ctx = await context(repo) + + const listed = await localCommits(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), point, 10) + expect(listed.commits.find(commit => commit.sha === orphan)?.parent).toBeNull() + const diff = await localDiff(ctx, CONFIG, plainSession(repo), repo, point, + { kind: 'branch', base: null, commits: { from: orphan, to: orphan } }, LAYERS, signal) + expect(diff.files.map(file => [file.path, file.status])).toEqual([['orphan.txt', 'added']]) + }) + + it('refuses commits that are not full object names, not on the branch, or out of order', async () => { + const { repo, point, shas } = await committed() + const ctx = await context(repo) + const read = (from: string, to: string): Promise => + localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'branch', base: null, commits: { from, to } }, LAYERS, signal) + const [first = '', second = ''] = shas + + await expect(read('HEAD', second)).rejects.toBeInstanceOf(CommitsMissing) + await expect(read(first, '--output=x')).rejects.toBeInstanceOf(CommitsMissing) + await expect(read(point.commit, second)).rejects.toThrow('The chosen commits are no longer on the branch') + await expect(read(second, first)).rejects.toThrow('The chosen commits are no longer on the branch') + await expect(localText(ctx, CONFIG, plainSession(repo), repo, + { kind: 'branch', base: null, commits: { from: first, to: 'HEAD' } }, 'second.txt', signal)).rejects.toBeInstanceOf(CommitsMissing) + }) +}) + describe('localText', () => { - const branch: ForgeLocalScope = { kind: 'branch', base: null } + const branch: ForgeLocalScope = { kind: 'branch', base: null, commits: null } it('reads the working tree, or the index for the staged scope', async () => { const { repo } = await forked(await directory()) diff --git a/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts b/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts index ab0d6ff28c..b66cc97290 100644 --- a/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/patch-cache.host.spec.ts @@ -5,6 +5,11 @@ import { changeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import type { ChangeRequestKey } from '@deepseek-ai/dsh-experimental-forge' import { PatchCache } from '../src/patch-cache.ts' +/** A patch without attributes. */ +function entry(patch: string): { readonly patch: string; readonly attributes: string } { + return { patch, attributes: '' } +} + function key(number: number): ChangeRequestKey { return changeRequestKey({ repository: { forge: 'fake', host: 'fake.test', owner: 'octo', name: 'demo' }, number }) } @@ -14,35 +19,43 @@ describe('PatchCache', () => { const cache = new PatchCache(100) expect(cache.get(key(1), 'v1')).toBeUndefined() - cache.set(key(1), 'v1', 'one') - expect(cache.get(key(1), 'v1')).toBe('one') + cache.set(key(1), 'v1', entry('one')) + expect(cache.get(key(1), 'v1')).toEqual(entry('one')) expect(cache.get(key(1), 'v2')).toBeUndefined() - cache.set(key(1), 'v2', 'two') + cache.set(key(1), 'v2', entry('two')) expect(cache.get(key(1), 'v1')).toBeUndefined() - expect(cache.get(key(1), 'v2')).toBe('two') + expect(cache.get(key(1), 'v2')).toEqual(entry('two')) }) it('drops the least recently read patches once the kept patches exceed the bound in UTF-8 bytes', () => { const cache = new PatchCache(10) - cache.set(key(1), 'v', 'aaaa') - cache.set(key(2), 'v', 'bbb') - expect(cache.get(key(1), 'v')).toBe('aaaa') + cache.set(key(1), 'v', entry('aaaa')) + cache.set(key(2), 'v', entry('bbb')) + expect(cache.get(key(1), 'v')).toEqual(entry('aaaa')) // Two three-byte characters bring the total to 13 bytes, so #2, read least recently, leaves. - cache.set(key(3), 'v', '变更') + cache.set(key(3), 'v', entry('变更')) expect(cache.get(key(2), 'v')).toBeUndefined() - expect(cache.get(key(1), 'v')).toBe('aaaa') - expect(cache.get(key(3), 'v')).toBe('变更') + expect(cache.get(key(1), 'v')).toEqual(entry('aaaa')) + expect(cache.get(key(3), 'v')).toEqual(entry('变更')) + }) + + it('counts the attributes kept beside a patch toward the bound', () => { + const cache = new PatchCache(6) + cache.set(key(1), 'v', { patch: 'aaa', attributes: 'bbbb' }) + expect(cache.get(key(1), 'v')).toBeUndefined() + cache.set(key(1), 'v', { patch: 'aaa', attributes: 'bbb' }) + expect(cache.get(key(1), 'v')).toEqual({ patch: 'aaa', attributes: 'bbb' }) }) it('keeps no patch over the bound, dropping the earlier version all the same', () => { const cache = new PatchCache(4) - cache.set(key(1), 'v1', 'one') - cache.set(key(1), 'v2', 'large') + cache.set(key(1), 'v1', entry('one')) + cache.set(key(1), 'v2', entry('large')) expect(cache.get(key(1), 'v1')).toBeUndefined() expect(cache.get(key(1), 'v2')).toBeUndefined() - cache.set(key(1), 'v3', 'four') - expect(cache.get(key(1), 'v3')).toBe('four') + cache.set(key(1), 'v3', entry('four')) + expect(cache.get(key(1), 'v3')).toEqual(entry('four')) }) }) diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index 13474f6353..65f55fefac 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -10,6 +10,7 @@ "src/diff.ts", "src/git.ts", "src/local-diff.ts", + "src/layers.ts", "src/panel.ts", "src/parse.ts", "src/patch-cache.ts", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca94685474..8633c2464e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -9246,6 +9246,9 @@ importers: diff: specifier: ^9.0.0 version: 9.0.0 + picomatch: + specifier: ^4.0.7 + version: 4.0.7 zod: specifier: 4.6.6 version: 4.6.6 @@ -9367,6 +9370,9 @@ importers: '@testing-library/react': specifier: ^16.3.3 version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@18.3.7(@types/react@18.3.31))(@types/react@18.3.31)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) + '@types/picomatch': + specifier: ^4.0.3 + version: 4.0.3 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -31306,6 +31312,10 @@ snapshots: optionalDependencies: picomatch: 4.0.4 + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + fetch-blob@3.2.0: dependencies: node-domexception: 1.0.0 @@ -34001,8 +34011,8 @@ snapshots: tinyglobby@0.2.17: dependencies: - fdir: 6.5.0(picomatch@4.0.4) - picomatch: 4.0.4 + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 tinyrainbow@3.1.0: {} From c313392bf822d0e1c75e461970be58b0fd8c583f Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 17:51:22 +0800 Subject: [PATCH 060/103] feat(forge-panel): review changes by layer, mark files viewed, and view chosen commits The changes view gains a lens of All, Interface, Implementation, and Tests that spans the file tree above it, a switch that hides test files from the tree and the diff, and a viewed checkbox on each file header that collapses the file. The toolbar counts viewed files and V toggles the file being read. Marks are kept per Session, source, path, and change digest in browser storage, so a file that changes again reads as changed since viewed. All commits beside Submit review, and beside the base branch of the Branch scope, shows one commit or a Shift run of commits. --- .../forge-panel/changes-view.expected.md | 6 + .../forge-panel/file-tree-toggle.expected.md | 10 + .../filter-config-failed.expected.md | 1 + .../forge-panel/review-layers.expected.md | 42 +++ apps/web/tests/forge-panel.e2e.ts | 201 +++++++++- docs/config-catalog.md | 15 +- docs/config-catalog.zh.md | 15 +- docs/subsystems/forge.i18n.yaml | 8 +- docs/subsystems/forge.md | 164 ++++++++- docs/subsystems/forge.zh.md | 164 ++++++++- .../client-ui-forge/README.i18n.yaml | 16 +- .../experimental/client-ui-forge/README.md | 21 +- .../experimental/client-ui-forge/README.zh.md | 21 +- .../src/client/ChangesTab.module.css | 142 ++++++- .../client-ui-forge/src/client/ChangesTab.tsx | 346 +++++++++++++----- .../src/client/CommitMenu.module.css | 130 +++++++ .../client-ui-forge/src/client/CommitMenu.tsx | 162 ++++++++ .../client-ui-forge/src/client/DiffFile.tsx | 18 +- .../src/client/FileTreePane.tsx | 7 +- .../src/client/ReviewControls.module.css | 147 ++++++++ .../src/client/ReviewControls.tsx | 148 ++++++++ .../src/client/changes-store.ts | 67 +++- .../client-ui-forge/src/client/locales.ts | 216 +++++++++++ .../client-ui-forge/src/client/mount.ts | 12 +- .../src/client/review-queue.ts | 18 +- .../client-ui-forge/src/client/review.ts | 24 +- .../src/client/viewed-files.ts | 145 ++++++++ .../tests/changes-address.client.spec.ts | 31 +- .../tests/changes-tab.client.spec.tsx | 242 +++++++++++- .../tests/diff-review.client.spec.tsx | 6 +- .../tests/diff-rows.client.spec.ts | 2 +- .../tests/file-tree.client.spec.tsx | 6 +- .../tests/mount.client.spec.ts | 34 +- .../tests/review-controls.client.spec.tsx | 229 ++++++++++++ .../tests/review.client.spec.tsx | 54 ++- .../tests/viewed-files.client.spec.ts | 92 +++++ .../extensions/tool-cordis/src/api-catalog.ts | 68 +++- scripts/gen-cordis-catalog.ts | 5 + scripts/type-equiv.manifest.json | 25 ++ 39 files changed, 2801 insertions(+), 259 deletions(-) create mode 100644 apps/web/tests/expected/forge-panel/review-layers.expected.md create mode 100644 packages/experimental/client-ui-forge/src/client/CommitMenu.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/CommitMenu.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewControls.module.css create mode 100644 packages/experimental/client-ui-forge/src/client/ReviewControls.tsx create mode 100644 packages/experimental/client-ui-forge/src/client/viewed-files.ts create mode 100644 packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx create mode 100644 packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts diff --git a/apps/web/tests/expected/forge-panel/changes-view.expected.md b/apps/web/tests/expected/forge-panel/changes-view.expected.md index b4f0445c07..1e3111ba0c 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -1,8 +1,12 @@ - img "变更请求状态:需要处理" - text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 - button "提交评审" - button "在浏览器中打开" - button "全部 2 个文件" +- button "分层透镜:全部": 全部 +- switch "隐藏测试文件" +- progressbar "已审阅的文件": 已审阅 0 / 2 - text: +4 −2 - button "刷新变更" - button "全部折叠" @@ -11,6 +15,7 @@ - region "全部 2 个文件": - button "收起 panel.md" [expanded] - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" - button "panel.md 的更多操作" - button "选择第 R1 行": "1" - text: "+ # Panel" @@ -18,6 +23,7 @@ - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" - button "panel.ts 的更多操作" - button "选择第 L1 行": "1" - text: export const n1 = 1 diff --git a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md index 72d7382c18..e7f09431a2 100644 --- a/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -1,8 +1,16 @@ - img "变更请求状态:需要处理" - text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 - button "提交评审" - button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 2" [checked] + - radio "接口 0" + - radio "实现 2" + - radio "测试 0" - button "全部 2 个文件" +- switch "隐藏测试文件" +- progressbar "已审阅的文件": 已审阅 0 / 2 - text: +4 −2 - button "刷新变更" - button "全部折叠" @@ -12,6 +20,7 @@ - region "全部 2 个文件": - button "收起 panel.md" [expanded] - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" - button "panel.md 的更多操作" - button "选择第 R1 行": "1" - text: "+ # Panel" @@ -19,6 +28,7 @@ - text: + Shows the change requests of a Session. - button "收起 panel.ts" [expanded] - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" - button "panel.ts 的更多操作" - button "选择第 L1 行": "1" - text: export const n1 = 1 diff --git a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md index 114cf607bf..d5e6cce057 100644 --- a/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md +++ b/apps/web/tests/expected/forge-panel/filter-config-failed.expected.md @@ -1,6 +1,7 @@ - text: main - button "基准分支:origin/main": origin/main - text: 包含未提交的修改 +- button "查看的提交:全部提交": 全部提交 - button "创建变更请求" - button "分支" - button "全部 0 个文件" [disabled] diff --git a/apps/web/tests/expected/forge-panel/review-layers.expected.md b/apps/web/tests/expected/forge-panel/review-layers.expected.md new file mode 100644 index 0000000000..e160dbbd40 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-layers.expected.md @@ -0,0 +1,42 @@ +- img "变更请求状态:需要处理" +- text: "Add the pull request panel #7" +- button "查看的提交:全部提交": 全部提交 +- button "提交评审" +- button "在浏览器中打开" +- radiogroup "分层透镜": + - radio "全部 3" [checked] + - radio "接口 1" + - radio "实现 2" + - radio "测试" [disabled] +- button "全部 3 个文件" +- switch "隐藏测试文件" [checked] +- progressbar "已审阅的文件": 已审阅 2 / 3 +- text: +5 −2 +- button "刷新变更" +- button "全部折叠" +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- button "将文件树移到右侧" [expanded] +- region "全部 3 个文件": + - button "展开 panel.md" + - text: docs/panel.md 新文件 +2 −0 + - checkbox "将 panel.md 标记为已审阅" [checked] + - button "panel.md 的更多操作" + - button "展开 panel.ts" + - text: src/panel.ts +2 −2 + - checkbox "将 panel.ts 标记为已审阅" [checked] + - button "panel.ts 的更多操作" + - button "收起 package.json" [expanded] + - text: package.json 新文件 +1 −0 + - checkbox "将 package.json 标记为已审阅" + - button "package.json 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ { \"name\": \"demo\" }" +- separator "调整文件树宽度" +- navigation "全部 3 个文件": + - textbox "筛选文件…" + - button "docs" [expanded] + - button "docs/panel.md": panel.md +2 −0 + - button "src" [expanded] + - button "src/panel.ts": panel.ts +2 −2 + - button "package.json": package.json +1 −0 diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 44f24a6a58..9335003dc1 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -45,8 +45,9 @@ const run = promisify(execFile) * `gh pr ready 9` and the REST merge of pull request 9 change what later * queries report, through `state.json`. `gh pr diff N` prints `pr-N.diff`, or * fails with `pr-N.refused` on standard error when that file exists, and the raw - * contents API serves `contents.json`, keyed by `path@commit`. Every invocation - * is appended to `calls.jsonl`. + * contents API serves `contents.json`, keyed by `path@commit`. The commit listing of + * pull request 7 serves `commits.json`, oldest first, and the compare API serves + * `compare.json`, keyed by `base...head`. Every invocation is appended to `calls.jsonl`. */ const GH = `#!/usr/bin/env node import { appendFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs' @@ -96,6 +97,16 @@ if (args[0] === 'pr' && args[1] === 'diff') { await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve)) process.exit(0) } +if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.diff') { + const range = args[5].slice('repos/octo/demo/compare/'.length) + const patch = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined + if (patch === undefined) { + process.stderr.write('gh: Not Found (HTTP 404)\\n') + process.exit(1) + } + process.stdout.write(patch) + process.exit(0) +} if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.raw+json') { const [resource, query] = args[5].split('?') const path = decodeURIComponent(resource.slice('repos/octo/demo/contents/'.length)) @@ -139,6 +150,17 @@ if (args[0] === 'api' && args[1] === 'graphql') { } } } }] }, }, } + if (query.includes('commits(first: $first')) { + const commits = existsSync(join(here, 'commits.json')) ? JSON.parse(readFileSync(join(here, 'commits.json'), 'utf8')) : [] + process.stdout.write(JSON.stringify({ data: { repository: { pullRequest: { headRefOid: 'a'.repeat(40), commits: { + totalCount: commits.length, pageInfo: { hasNextPage: false, endCursor: null }, + nodes: commits.map(commit => ({ commit: { + oid: commit.sha, messageHeadline: commit.title, authoredDate: '2026-10-08T00:00:00Z', + author: { name: 'Octo', user: { login: 'octo' } }, parents: { nodes: [{ oid: commit.parent }] }, + } })), + } } } } })) + process.exit(0) + } if (query.includes('node(id: $id)')) { process.stdout.write(JSON.stringify({ data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, @@ -204,6 +226,50 @@ const PR7_DIFF = [ '', ].join('\n') +/** A patch section that adds `lines` as the new file `path`. */ +function addedSection(path: string, lines: readonly string[]): string[] { + return [`diff --git a/${path} b/${path}`, 'new file mode 100644', 'index 0000000..4444444', '--- /dev/null', `+++ b/${path}`, + `@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)] +} + +/** Commits of pull request 7 in the review fixture, oldest first; the last is its head. */ +const REVIEW_COMMITS = [ + { sha: '1'.repeat(40), parent: 'f'.repeat(40), title: 'Add the pull request panel' }, + { sha: '2'.repeat(40), parent: '1'.repeat(40), title: 'Test the panel and translate it' }, + { sha: HEAD7, parent: '2'.repeat(40), title: 'Publish the panel schema' }, +] as const + +/** New files of each review fixture commit after the first, which changes `src/panel.ts` and adds `docs/panel.md`. */ +const REVIEW_SECTIONS = { + test: [ + ...addedSection('src/panel.spec.ts', ['it(\'shows the panel\', () => {})']), + ...addedSection('locale/zh.json', ['{ "title": "面板" }']), + ], + schema: [ + ...addedSection('package.json', ['{ "name": "demo" }']), + ...addedSection('docs/schema.json', ['{ "type": "object" }']), + ], +} + +/** + * Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is + * interface, and the spec, the locale dictionary, and `docs/schema.json`, which `.gitattributes` marks generated, are tests. + */ +const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n') + +/** Write the review fixture of pull request 7: its patch, commits, commit ranges, and root `.gitattributes`. */ +async function writeReviewFixture(root: string): Promise { + await writeFile(join(root, 'pr-7.diff'), REVIEW_DIFF) + await writeFile(join(root, 'commits.json'), JSON.stringify(REVIEW_COMMITS)) + await writeFile(join(root, 'compare.json'), JSON.stringify({ + [`${'1'.repeat(40)}...${'2'.repeat(40)}`]: [...REVIEW_SECTIONS.test, ''].join('\n'), + [`${'1'.repeat(40)}...${HEAD7}`]: [...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n'), + })) + const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record + for (const commit of ['2'.repeat(40), HEAD7]) contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\n' + await writeFile(join(root, 'contents.json'), JSON.stringify(contents)) +} + async function git(cwd: string, ...args: string[]): Promise { const { stdout } = await run('git', args, { cwd, env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_TERMINAL_PROMPT: '0' } }) return stdout.trim() @@ -1604,3 +1670,134 @@ it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor() expect(tripwire.pageErrors).toEqual([]) }) + +/** Open the change request view of pull request 7 in full screen, its tree on the left. */ +async function openReview(page: Page, scaffold: WebScaffold): Promise<{ readonly view: ReturnType; readonly sessionId: SessionId }> { + const { settled } = await sendPrompt(page, scaffold) + const sessionId = await settled + const session = scaffold.ctx.sessions.get(sessionId) + if (session === undefined) throw new Error('Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() + await page.getByRole('button', { name: '全屏', exact: true }).click() + const view = page.locator('[data-forge-changes="change"]') + await view.locator('[data-forge-diff-file="src/panel.ts"]').waitFor({ timeout: 20_000 }) + return { view, sessionId } +} + +/** Paths of the diff sections a changes view shows, in order. */ +async function shownPaths(view: ReturnType): Promise<(string | null)[]> { + return await view.locator('[data-forge-diff-file]').evaluateAll(sections => sections.map(section => section.getAttribute('data-forge-diff-file'))) +} + +it.skipIf(MODE === 'record')('reviews a change request by layer, hides test files, marks files viewed, and views chosen commits', async () => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-layers') + await writeReviewFixture(root) + const { view } = await openReview(page, scaffold) + const lens = view.getByRole('radiogroup', { name: '分层透镜', exact: true }) + const tree = view.getByRole('navigation') + await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部6', '接口1', '实现2', '测试3']) + // The lens spans the file tree with the filter field's insets, and its divider continues the tree's border. + const [lensBox, fieldBox, cellBox, treeBox] = await Promise.all([ + lens.boundingBox(), tree.locator('input').locator('xpath=..').boundingBox(), lens.locator('xpath=..').boundingBox(), tree.locator('xpath=..').boundingBox(), + ]) + if (lensBox === null || fieldBox === null || cellBox === null || treeBox === null) throw new Error('Lens and tree must be visible') + expect([lensBox.x, lensBox.x + lensBox.width]).toEqual([fieldBox.x, fieldBox.x + fieldBox.width]) + expect(cellBox.x + cellBox.width).toBe(treeBox.x + treeBox.width) + + await lens.getByRole('radio', { name: /^接口/ }).click() + await expect.poll(() => shownPaths(view)).toEqual(['package.json']) + await lens.getByRole('radio', { name: /^测试/ }).click() + await expect.poll(() => shownPaths(view)).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts']) + await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click() + await expect.poll(() => shownPaths(view)).toEqual(['docs/panel.md', 'src/panel.ts', 'package.json']) + expect(await tree.getByRole('button', { name: 'src/panel.spec.ts', exact: true }).count()).toBe(0) + expect(await lens.getByRole('radio', { name: /^测试/ }).isDisabled()).toBe(true) + + const progress = view.getByRole('progressbar', { name: '已审阅的文件', exact: true }) + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 0 / 3') + const docs = view.locator('[data-forge-diff-file="docs/panel.md"]') + await docs.getByRole('checkbox', { name: '将 panel.md 标记为已审阅', exact: true }).check() + await expect.poll(() => docs.getAttribute('data-expanded')).toBe(null) + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 1 / 3') + const panel = view.locator('[data-forge-diff-file="src/panel.ts"]') + await panel.getByText('export const n2 = \'two\'', { exact: true }).first().click() + await page.keyboard.press('v') + await expect.poll(() => panel.getAttribute('data-viewed')).toBe('viewed') + await expect.poll(() => progress.getAttribute('aria-valuetext')).toBe('已审阅 2 / 3') + await compareOrRefreshGolden(join(EXPECTED, 'review-layers.expected.md'), + await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + + await view.getByRole('switch', { name: '隐藏测试文件', exact: true }).click() + const commits = view.getByRole('button', { name: '查看的提交:全部提交', exact: true }) + await commits.click() + const menu = page.locator('[data-forge-commit-menu]') + await expect.poll(() => menu.getByRole('menuitem').evaluateAll(rows => rows.map(row => row.querySelector('[data-forge-commit]')?.getAttribute('data-forge-commit') ?? 'all'))) + .toEqual(['all', '1'.repeat(40), '2'.repeat(40), HEAD7]) + await menu.locator(`[data-forge-commit="${'2'.repeat(40)}"]`).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['locale/zh.json', 'src/panel.spec.ts']) + expect(await view.getByRole('button', { name: '提交评审', exact: true }).isDisabled()).toBe(true) + await view.getByRole('button', { name: '查看的提交:2222222', exact: true }).click() + await page.locator(`[data-forge-commit="${HEAD7}"]`).click({ modifiers: ['Shift'] }) + await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).waitFor() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json']) + await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3']) + const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) + expect(calls.filter(args => args[0] === 'api' && args[4] === 'Accept: application/vnd.github.diff').map(args => args[5])).toEqual([ + `repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`, + ]) + await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click() + await page.locator('[data-forge-commit-menu]').getByRole('menuitem', { name: /^全部提交/ }).click() + await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toHaveLength(6) + await expect.poll(() => docs.getAttribute('data-viewed')).toBe('viewed') + expect(tripwire.pageErrors).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a mark when the file changes again, and views branch commits', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-review-local', 'normal', { branch: 'feat' }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'main') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await mkdir(join(project, 'src')) + for (const [path, text, message] of [ + ['src/app.ts', 'export const app = 1\n', 'Add the app'], + ['src/app.spec.ts', 'it(\'runs\', () => {})\n', 'Test the app'], + ] as const) { + await writeFile(join(project, path), text) + await git(project, 'add', path) + await git(project, 'commit', '--quiet', '-m', message) + } + await writeFile(join(project, 'notes.md'), 'note\n') + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click() + await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + const card = page.locator('[data-forge-local]') + await card.getByRole('button', { name: /^查看本会话的变更:3 个文件/ }).click({ timeout: 20_000 }) + const local = page.locator('[data-forge-changes="local"]') + const app = local.locator('[data-forge-diff-file="src/app.ts"]') + await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).check({ timeout: 20_000 }) + await expect.poll(() => app.getAttribute('data-expanded')).toBe(null) + + await page.reload() + await page.locator('[data-forge-changes="local"] [data-forge-diff-file="src/app.ts"]').waitFor({ timeout: 20_000 }) + await expect.poll(() => app.getAttribute('data-viewed')).toBe('viewed') + expect(await app.getAttribute('data-expanded')).toBe(null) + await writeFile(join(project, 'src', 'app.ts'), 'export const app = 2\n') + await local.getByRole('button', { name: '刷新变更', exact: true }).click() + await expect.poll(() => app.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed') + await app.getByText('有新改动', { exact: true }).waitFor() + await expect.poll(() => app.getAttribute('data-expanded')).toBe('') + expect(await app.getByRole('checkbox', { name: '将 app.ts 标记为已审阅', exact: true }).isChecked()).toBe(false) + + await local.getByRole('button', { name: '查看的提交:全部提交', exact: true }).click() + const menu = page.locator('[data-forge-commit-menu]') + await menu.getByRole('menuitem', { name: /Test the app/ }).click() + await expect.poll(() => shownPaths(local), { timeout: 20_000 }).toEqual(['src/app.spec.ts']) + // Without the file tree beside the diff, the toolbar offers the lens as a menu. + await local.getByRole('button', { name: '分层透镜:全部', exact: true }).click() + await expect.poll(() => page.getByRole('menu').getByRole('menuitem').allTextContents()).toEqual(['全部1', '接口0', '实现0', '测试1']) + await page.keyboard.press('Escape') + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 7562c8bf96..eb88c30e25 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1049,7 +1049,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1077,6 +1077,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } ``` @@ -1142,7 +1151,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:266`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1178,6 +1187,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 0d75b6e523..3188fdb42d 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1051,7 +1051,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:345`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1079,6 +1079,15 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number + /** Most commits of the `branch` scope listed, oldest first. */ + maxCommits?: number + /** + * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with + * dot files included; their files form the `test` layer, which the changes view can hide. + */ + testPaths?: string[] + /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + interfacePaths?: string[] } ``` @@ -1144,7 +1153,7 @@ export type SourceSigning = 'ad-hoc' | { ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:232`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:266`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -1180,6 +1189,8 @@ export interface Config { timeoutMs?: number /** Maximum captured bytes per `gh` output stream and combined JSON bytes of one complete check read. */ maxOutputBytes?: number + /** Most commits one pull request commit listing returns; GitHub lists at most 250 commits of a pull request. */ + maxCommits?: number } ``` diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 3f4994aa39..5c531ea679 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -6,8 +6,8 @@ en: 3990a17e12c66a23 zh: 4170c33e49248f8f /forges/providers-and-change-requests: - en: 4ec7d1892b4067db - zh: 6bb70d21ae3d7a89 + en: e5d807b29f553751 + zh: e0b25d9e964f988e /forges/status-polling: en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 @@ -18,5 +18,5 @@ en: 13dfd36f2166bba0 zh: a369434f52f04d57 /forges/panel: - en: dbc28e731f357edf - zh: a1977fafc0651427 + en: 5fcac3740f59ffc0 + zh: a95a881cd06a59d8 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index f36141ea1b..4f4febadfe 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -74,9 +74,49 @@ interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } ``` +```ts type-equiv +/** One commit of a change request. */ +interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} +``` + +```ts type-equiv +/** The commits of a change request at one head commit. */ +interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} +``` + +`ctx.forge.commits` and `ctx.forge.compare` delegate to a provider that implements both; otherwise `commits` resolves to undefined and `compare` to an `unavailable` failure, so the forge panel offers its commit picker only where the provider reads commits. + ```ts type-equiv /** Whether a provider can reach one host with the current credentials. */ interface ForgeReadiness { @@ -568,7 +608,20 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`; both return files that the Host parsed into `ForgeDiffFile` hunks. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. +The changes view reads through the same Remote. `localDiff` reads one `ForgeLocalScope` of the Session's checkout, and `changeRequestDiff` reads a bound change request at the head of its latest status through the provider's `diff`, or the `ForgeCommitRange` it names through the provider's `compare`; both return files that the Host parsed into `ForgeDiffFile` hunks, each with its review layer and change digest. `localCommits` and `changeRequestCommits` list the commits a range can name, the latter as null when the provider does not read commits. `localText` and `changeRequestText` read the new side of one file, which supplies the unchanged lines between hunks. Each inspection also sizes the `branch` scope as `ForgePanelState.local` for the panel's local changes card, always against the automatic fork point. A `branch` scope whose `base` names a ref compares with the merge base of HEAD and that branch instead; `diffBases` lists the branches the view offers, with the automatic fork point. + +```ts type-equiv +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} +``` ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -576,9 +629,10 @@ type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -640,6 +694,14 @@ interface ForgeDiffHunk { type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ``` +```ts type-equiv +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +type ForgeFileLayer = 'interface' | 'implementation' | 'test' +``` + ```ts type-equiv /** One changed file of a diff. */ interface ForgeDiffFile { @@ -661,6 +723,13 @@ interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } ``` @@ -677,22 +746,27 @@ interface ForgeLocalDiff { ``` ```ts type-equiv -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } ``` +```ts type-equiv +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +type ForgeLocalCommits = ForgeCommitList +``` + ```ts type-equiv /** One file the `branch` scope changes, without its hunks. */ interface ForgeChangedFile { @@ -822,6 +896,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. @@ -975,21 +1070,36 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise +/** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ +@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise + /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise @@ -1006,19 +1116,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ -@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ +@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise /** * Read one file of a change request's repository at a commit, which diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 61c53fbd6c..e731e65c23 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -74,9 +74,49 @@ interface ForgeProvider { fileText(ref: ChangeRequestRef, commit: string, path: string, signal: AbortSignal): Promise /** Build the web page of `path` at `commit` in the change request's repository. */ fileUrl(ref: ChangeRequestRef, commit: string, path: string): string + /** + * List the commits of a change request at its current head. A provider implements `commits` and `compare` + * together; omitting either declares that the change request can be read only as a whole. + */ + commits?(ref: ChangeRequestRef, signal: AbortSignal): Promise + /** + * Read the changes from commit `base` to commit `head` in the change request's repository, as one unified patch + * with `a/` and `b/` path prefixes. Both are full object names; `head` descends from `base`. + */ + compare?(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise } ``` +```ts type-equiv +/** One commit of a change request. */ +interface ForgeCommit { + /** Full commit object name. */ + readonly sha: string + /** Full object name of the first parent, or null for a root commit. */ + readonly parent: string | null + /** First line of the commit message. */ + readonly title: string + /** Author name or login as the host reports it, or null when it reports none. */ + readonly author: string | null + /** ISO 8601 time the commit was authored. */ + readonly authoredAt: string +} +``` + +```ts type-equiv +/** The commits of a change request at one head commit. */ +interface ForgeCommitList { + /** Head commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with the head commit unless `truncated`. */ + readonly commits: readonly ForgeCommit[] + /** Whether the change request has more commits than the provider lists; the listed ones are the oldest. */ + readonly truncated: boolean +} +``` + +`ctx.forge.commits` 与 `ctx.forge.compare` 委托给同时实现两者的提供方;否则 `commits` 返回 undefined,`compare` 返回 `unavailable` 失败,因此 forge 面板只在提供方能读取提交时提供提交选择器。 + ```ts type-equiv /** Whether a provider can reach one host with the current credentials. */ interface ForgeReadiness { @@ -568,7 +608,20 @@ type ForgeChangeRequestStatesFrame = | { readonly type: 'changed'; readonly states: readonly ForgeChangeRequestListState[] } ``` -变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 +变更视图经同一个 Remote 读取。`localDiff` 读取 Session 检出的某个 `ForgeLocalScope`;`changeRequestDiff` 经提供方的 `diff` 读取已绑定变更请求在其最新状态 head 处的变更,或经提供方的 `compare` 读取它指定的 `ForgeCommitRange`;两者返回的文件都已在宿主上解析为 `ForgeDiffFile` 的 hunk,并带有分层与改动摘要。`localCommits` 与 `changeRequestCommits` 列出范围可以指定的提交,提供方不读取提交时后者返回 null。`localText` 与 `changeRequestText` 读取一个文件的新版本,用来补出 hunk 之间未变更的行。每次检查还会把 `branch` 范围的规模统计为 `ForgePanelState.local`,供面板的变更卡片使用,始终以自动分叉点为准。`base` 指定了引用的 `branch` 范围改为与 HEAD 和该分支的合并基准比较;`diffBases` 列出视图可选的分支以及自动分叉点。 + +```ts type-equiv +/** + * Consecutive commits a changes view shows instead of its whole comparison, named by full object names in the order + * the commit list shows them, oldest first; the view shows the changes from the first commit's first parent to the last. + */ +interface ForgeCommitRange { + /** First, oldest commit shown. */ + readonly from: string + /** Last, newest commit shown; equal to `from` for one commit. */ + readonly to: string +} +``` ```ts type-equiv /** Which local changes a diff covers; each reads the Session's checkout through Git. */ @@ -576,9 +629,10 @@ type ForgeLocalScope = /** * The working tree and untracked files against a fork point: the merge base of HEAD with the * `base` ref, or while `base` is null, the base commit of the worktree the Session created, - * else the merge base of HEAD with the default branch of the code host remote. + * else the merge base of HEAD with the default branch of the code host remote. With `commits`, only the changes + * of those commits between the fork point and HEAD, without uncommitted or untracked files. */ - | { readonly kind: 'branch'; readonly base: string | null } + | { readonly kind: 'branch'; readonly base: string | null; readonly commits: ForgeCommitRange | null } /** The working tree and untracked files against HEAD. */ | { readonly kind: 'uncommitted' } /** The working tree and untracked files against the index. */ @@ -640,6 +694,14 @@ interface ForgeDiffHunk { type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ``` +```ts type-equiv +/** + * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root + * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + */ +type ForgeFileLayer = 'interface' | 'implementation' | 'test' +``` + ```ts type-equiv /** One changed file of a diff. */ interface ForgeDiffFile { @@ -661,6 +723,13 @@ interface ForgeDiffFile { readonly deletions: number /** Hunks in file order; none for a binary file or a change of mode or name only. */ readonly hunks: readonly ForgeDiffHunk[] + /** Review layer the path falls in. */ + readonly layer: ForgeFileLayer + /** + * Digest of the file's change: its paths, status, and hunks, plus the blob names of a binary change, or the content + * of an untracked binary file. Equal digests describe the same change; reading the same comparison again keeps it. + */ + readonly digest: string } ``` @@ -677,22 +746,27 @@ interface ForgeLocalDiff { ``` ```ts type-equiv -/** Changes of a change request as its code host computes them. */ +/** Changes of a change request, or of consecutive commits of it, as its code host computes them. */ interface ForgeChangeRequestDiff { - /** Head commit the diff describes. */ + /** Commit whose new side the diff describes: the head, or the last chosen commit. */ readonly headSha: string /** Changed files in the host's order. */ readonly files: readonly ForgeDiffFile[] /** * Commits the checkout's branch has beyond the head when that branch is the change request's head - * branch and the head commit is present locally; null otherwise. + * branch and the head commit is present locally; null otherwise and for chosen commits. */ readonly localAhead: number | null - /** Web page of each changed file at the head commit, by path. */ + /** Web page of each changed file at `headSha`, by path. */ readonly fileUrls: Readonly> } ``` +```ts type-equiv +/** Commits of the `branch` scope, which the changes view can show one or several of. */ +type ForgeLocalCommits = ForgeCommitList +``` + ```ts type-equiv /** One file the `branch` scope changes, without its hunks. */ interface ForgeChangedFile { @@ -822,6 +896,27 @@ async fetchChecks(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * List the commits of a change request at its current head. + * @param ref - change request served by a registered provider. + * @param signal - cancellation of the read. + * @returns the commits, why the host did not provide them, or undefined when the provider does not read commits. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise + +/** + * Read the changes between two commits of a change request's repository. + * @param ref - change request served by a registered provider. + * @param base - full object name of the commit compared from. + * @param head - full object name of a commit that descends from `base`. + * @param signal - cancellation of the read. + * @returns one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it; a provider that + * does not read commits returns `unavailable`. + * @throws when no provider serves the change request's forge, or with `signal.reason` when it aborts. + */ +async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise + /** * Publish one comment or a completed review, then refresh the watched status. * @param ref - change request served by a registered provider. @@ -975,21 +1070,36 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the base of the `branch` scope, and the untracked files left out. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without - * a fork point; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before + * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @Remote async localDiff(session: Session, scope: ForgeLocalScope, signal: AbortSignal): Promise +/** + * List the commits of the `branch` scope of the Session's current checkout, which the changes view can show one or + * several of instead of the whole scope. + * @param session - Session whose checkout is read. + * @param base - the base ref of the `branch` scope, or null for its automatic fork point. + * @param signal - request cancellation. + * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not + * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. + */ +@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise + /** * Read the new side of one changed file in a scope, which supplies the - * unchanged lines between its hunks: the index for `staged`, else the working tree. + * unchanged lines between its hunks: the index for `staged`, the last chosen commit for chosen commits of + * the `branch` scope, else the working tree. * @param session - Session whose checkout is read. * @param scope - the scope the diff was read in. * @param path - path relative to the checkout's top-level directory, as the diff names it. * @param signal - request cancellation. * @returns the text. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/diff-too-large` over `maxDiffBytes`; - * an error for a path outside the checkout, binary content, or a failed read. + * `forgePanel/commits-missing` for a chosen commit that is not a full object name; an error for a path outside + * the checkout, binary content, or a failed read. */ @Remote async localText(session: Session, scope: ForgeLocalScope, path: string, signal: AbortSignal): Promise @@ -1006,19 +1116,37 @@ Serves the forge panel. Following a Session inspects the checkout of its current @Remote async changeRequestChecks(session: Session, url: string, headSha: string, signal: AbortSignal): Promise /** - * Read the changes of a change request of a Session as its code host - * computes them, at the head commit of its latest status. A patch already - * read at the same head commit and base branch is reused from memory, for - * any Session, until `maxCachedDiffBytes` evicts it. + * List the commits of a change request of a Session at its current head, which the changes view can show one or + * several of instead of the whole change request. * @param session - Session the change request is bound to. * @param url - binding URL of the change request. * @param signal - request cancellation. - * @returns the files, the head commit, each file's web page, and the commits the checkout has beyond the head. + * @returns the commits oldest first with the head they were read at, or null when the provider does not read commits. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; - * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; - * `forgePanel/diff-failed` before its status was read and when the host does not provide the diff otherwise. + * `forgePanel/diff-failed` when the host does not list them. */ -@Remote async changeRequestDiff(session: Session, url: string, signal: AbortSignal): Promise +@Remote async changeRequestCommits(session: Session, url: string, signal: AbortSignal): Promise + +/** + * Read the changes of a change request of a Session as its code host + * computes them, with each file's layer following the root `.gitattributes` + * of the commit the diff ends at. Without `commits` the diff covers the change + * request at the head commit of its latest status; a patch already read at the + * same head commit and base branch is reused from memory with its attributes, for + * any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those + * commits, from the first one's first parent to the last, and is read every time. + * @param session - Session the change request is bound to. + * @param url - binding URL of the change request. + * @param commits - consecutive commits of the change request, or null for all of it. + * @param signal - request cancellation. + * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. + * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; + * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; + * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host + * does not provide the commits, the diff, or an existing `.gitattributes` otherwise. + */ +@Remote async changeRequestDiff( session: Session, url: string, commits: ForgeCommitRange | null, signal: AbortSignal, ): Promise /** * Read one file of a change request's repository at a commit, which diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 203cd3e907..445e3f73db 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,23 +15,23 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 1101418b5621ba9d - zh: 4d66052d4708d02c + en: dcde9f0c7c82ab08 + zh: 77a570133b45dbd9 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 0c2dd86b5f6b489d - zh: 2f0fce0affa48f59 + en: 1c8c6cfa6ad4b906 + zh: 15a0beb677f6e0fd /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: d62a9841cc34dfdd - zh: 5aa4ffb331c5bb93 + en: 10101427d1e0589b + zh: c981cec12f64eb75 /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 0f795ca1c607af01 - zh: a05ac28fb2313d6e + en: 51f6e22d3f2b7d03 + zh: 252f1ba8b2941b60 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 29afc7d4e6..a24de40f12 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -40,11 +40,13 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. - **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. A file is in Tests when its path matches `testPaths` or the repository's root `.gitattributes` marks it `linguist-generated`, else in Interface when its path matches `interfacePaths`, such as package manifests, configuration, and type declarations, else in Implementation. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first; a click shows one commit and a Shift click the commits from the last one clicked; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and a chosen commit that is gone offers Show all commits. + The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. The diff follows the file tree’s depth-first order: directories before files, with each group sorted by displayed name in case-sensitive UTF-16 code-unit order. Compacted directory chains are compared as one complete name. Filtering or folding the tree does not reorder the diff. Click the diff content to focus it. Left and Right move to the previous and next file in diff order and expand it; navigation stops at the first and last file. Up and Down keep their normal scrolling behavior. After manual scrolling, file navigation starts from the file at the top of the viewport. Text editing, non-collapsed text selections, modified keys, menus, and file-tree controls keep their own keyboard behavior. -`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, and `maxCachedDiffBytes` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). +`gitCommand`, `gitTimeoutMs`, `graceMs`, `maxOutputBytes`, `readinessTimeoutMs`, `maxBranches`, `worktreePrefix`, `maxDiffBytes`, `maxUntrackedFiles`, `maxCachedDiffBytes`, `maxCommits`, `testPaths`, and `interfacePaths` are listed in the [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-client-ui-forge). All files opens a searchable directory tree with the selected file scrolled to its middle. Single-child directories share a row, and renamed files also match their old path. A wide changes pane shows the same tree beside the diff; its File tree toolbar button cycles through left, right, and hidden, starting on the left. Its accessible name describes the next action, and focus stays on the button when it moves or hides the tree. The search, folds, selection, and width survive moving or hiding the tree and switching tabs or Sessions. Drag the divider or use its arrow keys to resize the tree. Files and folders reserve the same disclosure column so each child is indented from its parent. Local changes and each PR retain separate tabs. Select code text or use line numbers to select a range within one displayed hunk and side; text selection and copying stay on the starting side. The plus button opens the plain-text comment editor. With a mouse, hovering a line also shows a plus beside its line number, which stays clickable, on the hovered side in two columns and on the line's own side in one column; pressing it selects that line, dragging extends the range on that side, and releasing opens the editor. It accepts newlines and IME composition; only its action buttons submit the comment. Drag its lower edge to adjust the height. Add to input inserts a removable quote into the main composer that shows the file name, side and lines, and comment, and on hover the file path; multiple quotes are sent together only when the user sends that composer. The GitHub split button starts or adds to a pending review; its menu publishes a single comment immediately. Comments remain beside their code after quoting, queueing, or publishing. Pending comments are edited or removed there. Request changes requires a review summary; the dialog explains this beside the summary field and announces the requirement when the decision changes. Submit review in the PR title bar opens a centered dialog showing only the pending count, summary, and Comment, Approve, or Request changes. Added and deleted files show only their populated line-number column. Pending reviews and comment records are stored in this browser per Session and tab, including the original PR head commit. Switching Sessions or hiding the pane retains them; closing the tab clears its comments, summary, and decision, and reopening starts an empty review. Published GitHub comments and references already added to the main composer are unaffected. Records whose code changed remain visible below their file, or after the diff when the file is absent. A changed head requires fresh line selections. While the tab remains open, an uncertain write stays blocked across reloads until the user checks GitHub and explicitly permits another submission. @@ -67,11 +69,11 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, and hunks, plus the blob names of a binary change or the content of an untracked binary file, and a layer from picomatch matches of `testPaths` and `interfacePaths`, with dot files included, and from the `linguist-generated` lines of the root `.gitattributes`: the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point with `log --topo-order --reverse`, at most `maxCommits`. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. -The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, and layout choices of each tab in a slot store, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. +The browser entry mounts the Remote, then the UI. One stream per Session feeds the tab, the header button, the New Session option, and the creation card; it opens with the first subscriber, closes with the last, reopens after a transport reset, and keeps the last state while the Session scope is retained. Releasing that scope closes the stream and removes its cached state. The New Session option fills `conversation.hero.options` and the worktree card `conversation.input.dock`. The worktree card shows a running creation, with Cancel calling `stopCreation` while a message waits for it, or the failed or stopped attempt a message waits after, with Retry calling `retryWorktree` and Continue without a worktree calling `cancelWorktree`. The tab shortens paths with the Host home from the Remote's Host facts, read again after each transport reset. The tab reports its visibility to the header button's pressed state. The header button collapses a docked tab or closes its floating tab. The toast lives in a `shell.overlay` entry so it outlives the tab. One stream of change request states feeds the Session row icons in `sidebar.session.row.trailing` and the hover card section in `sidebar.session.row.hover` while any of them is mounted; both take a Session's worktree and bindings from its Session list summary values. The change request card takes a change request, its snapshot, and optional actions, so another surface can reuse it. The changes view is the `forge-changes` resource tab type: its addresses, `dsh-resource://forge-changes//local` and `dsh-resource://forge-changes//change/`, name the source, and a navigation may name a file to scroll to. The tab type enables `keepMounted`, retaining visited bodies and their owning Session references until their tab records end. Its keyed panel hook subscribes only for the visible body; other panel surfaces may keep the shared Session stream open. Its body keeps the scope, base branch, chosen commits, lens, test file switch, and layout choices of each tab in a slot store, keeps viewed marks per Session in `localStorage` under `dsh.forge-viewed.v1.`, at most 20 sources per Session and 50 Sessions, reads through the Remote, and highlights lines with the shared code highlighter; a chip title shows its name with the changes icon. | Source | Responsibility | |---|---| @@ -82,13 +84,17 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t | [`src/git.ts`](src/git.ts) | Git queries under Session permissions | | [`src/parse.ts`](src/parse.ts) | Git output parsing and remote order | | [`src/diff.ts`](src/diff.ts) | Patch parsing, untracked files as additions, and numstat records | -| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, new-side text, and the `branch` scope summary | +| [`src/local-diff.ts`](src/local-diff.ts) | Fork point, local scopes, branch commits, new-side text, and the `branch` scope summary | +| [`src/layers.ts`](src/layers.ts) | Review layers from path globs and `linguist-generated` attributes | | [`src/client/mount.ts`](src/client/mount.ts) | Remote mount, slot entries, and action outcome mapping | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | Reusable change request card | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | Local changes card | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | Changes view | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | Base branch menu of the Branch scope | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | One file of the changes view | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | Lens, test file switch, and viewed progress | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | Commit picker | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | Viewed marks kept in the browser | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | Changed file label: name, then directory | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | New Session worktree option | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | Worktree creation and removed-worktree card | @@ -111,7 +117,7 @@ The browser entry mounts the Remote, then the UI. One stream per Session feeds t ## Model Experience -Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, and local Branch quotes the base the view compared with. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. +Indirectly, through the working-directory service and the Session's conversation: the notice about a Session's new worktree joins the first request's messages, Continue in the project queues the same kind of notice for the next request, and Create change request sends a user message that asks the Agent for a change request. Add to input contributes a frozen `## User Comment N` quote containing File, Side, Lines, Source, the diff hunk, and Comment; PR quotes also name the reviewed commit, local Branch quotes the base the view compared with, and quotes from chosen commits name them. These quotes enter the normal logged user message only when the composer is sent. Inspection, status, restoring, the Session list, and GitHub review submission add no model context. #### KV Cache effect @@ -130,9 +136,12 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Waiting messages** — while a message waits, the Agent stays idle in maintenance and the composer offers no stop; the card's actions, the Agent's cancellation, or the Remote's stop release it, and callers that wait for the Agent to become idle wait as well. - **Restoring** — restoring recreates the checkout from the branch, or from the commit the branch started from when the branch is gone; changes that were never committed are lost with the removed directory. The [worktree service](../worktree/README.md#use-this-package) validates the recorded target and removes only its missing, unlocked registration. An existing or incomplete directory stays blocked; preserve its files and remove the directory before retrying, or continue in the source project. - **Linked-worktree projects** — the option is unavailable when the project is itself a linked worktree: under workspace-write its Git directory lies outside the writable root, so neither the new branch nor later commits could be written. -- **Changes scopes** — deferred: scopes for one commit and for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. +- **Changes scopes** — deferred: a scope for the last turn. The Branch scope's Default needs a remote whose default branch HEAD shares history with, or a worktree the Session created; otherwise a base branch must be chosen. - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. +- **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. +- **Review layers** — the Interface layer follows path globs only and keeps whole files; finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. +- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, 250 for GitHub, and a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index f45d0c2568..cdeaac4ac9 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -40,11 +40,13 @@ kind: "package-reference" - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。路径匹配 `testPaths` 或被仓库根目录 `.gitattributes` 标为 `linguist-generated` 的文件属于“测试”;否则路径匹配 `interfacePaths`(例如包清单、配置与类型声明)的文件属于“接口”;其余属于“实现”。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在时提供“查看全部提交”。 + 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 diff 按文件树的深度优先顺序排列:同层目录在前、文件在后,各组按显示名称以区分大小写的 UTF-16 码元顺序排序。压缩目录链作为一个完整名称参与比较。筛选或折叠文件树不会改变 diff 的顺序。点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 -`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles` 与 `maxCachedDiffBytes` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 +`gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles`、`maxCachedDiffBytes`、`maxCommits`、`testPaths` 与 `interfacePaths` 列在[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-client-ui-forge)中。 “全部文件”打开可搜索的目录树,并把选中文件滚动到中间;只有一个子目录的路径会合并显示,重命名文件也可以按旧路径搜索。较宽的变更面板会在 diff 旁显示同一棵树,工具栏的“文件树”按钮按“左侧 → 右侧 → 隐藏”循环切换,默认显示在左侧。按钮的无障碍名称说明下一步操作,移动或隐藏文件树时焦点仍留在按钮上。移动或隐藏文件树,以及切换标签页与 Session 时保留搜索、折叠状态、选中文件和宽度。拖动分隔线,或聚焦分隔线后使用方向键,可以调整文件树宽度。文件与文件夹预留相同的展开箭头列,子项相对父目录向内缩进。本地变更与每个 PR 保留独立标签页。划选代码文字或通过行号选择同一已显示 hunk、同一侧的连续行,文字划选与复制都限定在起始侧。点击“+”打开纯文本评论框。使用鼠标时,悬停在某一行上也会在其行号旁显示“+”,行号仍可点击:两栏时显示在悬停的一侧,单栏时显示在该行所属的一侧;按下即选中这一行,拖动可在同一侧扩展范围,松开即打开评论框。评论框支持换行和输入法组合输入,只有点击操作按钮才提交。可拖动底边调整高度。“添加到输入框”将评论作为可移除的引用加入主输入框,引用显示文件名、侧与行号以及评论,悬停时显示文件路径;多条引用只会在用户发送主输入框时一起发送。GitHub 分段按钮用于开始或加入待提交评审,下拉菜单可以立即发布单条评论。评论在引用、暂存或发布后保留在对应代码旁,暂存评论可在那里编辑或删除。“请求更改”需要填写评审总结,弹窗在总结输入框旁说明此要求,并在切换评审决定时播报。PR 标题栏中的“提交评审”打开居中弹窗,只显示待提交数量、总结以及“评论”“批准”“请求更改”选项。新建和删除文件只显示有内容的一侧行号。待提交评审与评论记录按 Session 和页签保存在当前浏览器,包括最初评审的 head。切换 Session 或隐藏面板时保留;关闭页签会清空该页签的评论、总结与评审决定,重新打开从空评审开始。已发布到 GitHub 的评论与已加入主输入框的引用不受影响。head 变化后需要重新选择评论行。代码变化后的记录保留在文件末尾;文件已不在 diff 中时,记录显示在 diff 之后。页签保持打开时,结果不明的提交在重新加载后仍会阻止重复发送,直到用户检查 GitHub 并明确允许再次提交。 @@ -67,11 +69,11 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态与 hunk 组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并用 picomatch(包含点文件)匹配 `testPaths` 与 `interfacePaths`、读取根目录 `.gitattributes` 中的 `linguist-generated` 行来确定分层:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --topo-order --reverse` 列出分叉点之后的提交,最多 `maxCommits` 个。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 -浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支与布局选择,经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 +浏览器入口先挂载 Remote,再挂载界面。每个 Session 一条流,同时供给标签页、标题栏按钮、新会话选项与创建卡片;第一个订阅方出现时打开,最后一个离开时关闭,传输重置后重新打开,在 Session scope 保留期间保存最后的状态。释放该 scope 时关闭流并移除缓存状态。新会话选项填入 `conversation.hero.options`,worktree 卡片填入 `conversation.input.dock`。worktree 卡片显示正在进行的创建,有消息在等待时“取消”调用 `stopCreation`;或显示消息等待时失败或被停止的那次尝试,“重试”调用 `retryWorktree`,“不使用工作树”调用 `cancelWorktree`。标签页用 Remote 宿主信息中的宿主主目录缩短路径,每次传输重置后重新读取。标签页把自己是否可见报告给标题栏按钮的按下状态。标题栏按钮收起停靠的标签页,或关闭其浮动标签页。toast 位于 `shell.overlay` 条目中,因此比标签页存在得更久。只要 `sidebar.session.row.trailing` 中的会话行图标或 `sidebar.session.row.hover` 中的悬浮卡片部分有一个已挂载,就由同一条变更请求状态流供给它们;两者都从会话列表的摘要值中读取 Session 的 worktree 与绑定。变更请求卡片接收变更请求、它的快照与可选操作,其他界面可以复用。变更视图是 `forge-changes` 资源标签页类型:它的地址 `dsh-resource://forge-changes//local` 与 `dsh-resource://forge-changes//change/` 指明来源,导航参数可以指定要滚动到的文件。标签页类型启用 `keepMounted`,将访问过的正文及其所属 Session 引用保留至标签页记录结束。它的 keyed panel hook 仅为可见正文订阅;其他面板界面仍可能保持共享 Session 流开启。它的正文用 slot store 按标签页保存范围、基准分支、所选提交、透镜、测试文件开关与布局选择,按 Session 把已审阅标记保存在 `localStorage` 的 `dsh.forge-viewed.v1.` 下(每个 Session 最多 20 个来源,最多 50 个 Session),经 Remote 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 | 源码 | 职责 | |---|---| @@ -82,13 +84,17 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/git.ts`](src/git.ts) | 按 Session 权限执行 Git 查询 | | [`src/parse.ts`](src/parse.ts) | Git 输出解析与远端顺序 | | [`src/diff.ts`](src/diff.ts) | 补丁解析、把未跟踪文件表示为新增,以及 numstat 记录 | -| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、新版本文本与 `branch` 范围摘要 | +| [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、分支提交、新版本文本与 `branch` 范围摘要 | +| [`src/layers.ts`](src/layers.ts) | 按路径 glob 与 `linguist-generated` 属性分层 | | [`src/client/mount.ts`](src/client/mount.ts) | Remote 挂载、slot 条目与操作结果映射 | | [`src/client/ChangeRequestCard.tsx`](src/client/ChangeRequestCard.tsx) | 可复用的变更请求卡片 | | [`src/client/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/BaseMenu.tsx`](src/client/BaseMenu.tsx) | “分支”范围的基准分支菜单 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | +| [`src/client/ReviewControls.tsx`](src/client/ReviewControls.tsx) | 分层透镜、测试文件开关与已审阅进度 | +| [`src/client/CommitMenu.tsx`](src/client/CommitMenu.tsx) | 提交选择器 | +| [`src/client/viewed-files.ts`](src/client/viewed-files.ts) | 保存在浏览器中的已审阅标记 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | | [`src/client/WorktreeToggle.tsx`](src/client/WorktreeToggle.tsx) | 新会话的工作树选项 | | [`src/client/WorktreeProgress.tsx`](src/client/WorktreeProgress.tsx) | worktree 创建卡片与 worktree 缺失卡片 | @@ -111,7 +117,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交,本地“分支”引用还包含视图比较的基准,来自所选提交的引用还会注明这些提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 #### KV Cache 影响 @@ -130,9 +136,12 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **等待中的消息**——消息等待期间,Agent 以空闲状态处于维护任务中,输入框不提供停止;只有卡片上的操作、Agent 的取消或 Remote 的停止能放行它,等待 Agent 空闲的调用方也会一并等待。 - **恢复**——恢复会从分支重新检出;分支也已删除时,从它开始时的提交重新创建。从未提交的修改随被删除的目录一起丢失。[worktree 服务](../worktree/README.zh.md#use-this-package)校验记录的目标,只移除该目标缺失且未锁定的登记。已有或未恢复完成的目录仍会阻止恢复;请先保存其中的文件并移除目录再重试,或在源项目继续。 - **链接 worktree 项目**——项目本身是链接 worktree 时该选项不可用:在 workspace-write 下它的 Git 目录位于可写根之外,新分支与之后的提交都无法写入。 -- **变更范围**——待办:单个提交与上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 +- **变更范围**——待办:上一轮的范围。“分支”范围的“默认”需要一个默认分支与 HEAD 有共同历史的远端,或 Session 创建的 worktree;否则必须选择基准分支。 - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 +- **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 +- **分层**——“接口”层只按路径 glob 划分并保留整个文件;找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 +- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为 250 个),每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index 47193f0887..f664c4b2fa 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -91,21 +91,96 @@ } .headerEnd { - flex: none; + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + min-width: 0; margin-left: auto; } + .toolbar { display: flex; flex: none; - align-items: center; - gap: 4px; + align-items: stretch; box-sizing: border-box; - min-height: 38px; - padding: 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); } +/* Spans the file tree's width with the tree's search inset, and its divider continues the tree's border. */ +.lensCell { + display: none; + flex: none; + align-items: center; + box-sizing: border-box; + width: var(--forge-tree-width); + padding: 0 8px; + border-inline-end: 0.5px solid var(--dsw-alias-border-l3); +} + +.toolbar[data-tree='right'] .lensCell { + order: 1; + border-inline-start: 0.5px solid var(--dsw-alias-border-l3); + border-inline-end: 0; +} + +.toolbarMain { + display: flex; + flex: 1; + flex-wrap: wrap; + align-items: center; + gap: 0 4px; + box-sizing: border-box; + min-width: 0; + min-height: 38px; + padding: 5px 8px; +} + +.lensMenu { + display: inline-flex; +} + +@container forge-changes (min-width: 760px) { + .toolbar:not([data-tree='hidden']) .lensCell { + display: flex; + } + + .toolbar:not([data-tree='hidden']) .lensMenu { + display: none; + } +} + +.spacer { + flex: 1; +} + +.progressSlot { + display: inline-flex; +} + +/* Breaks the toolbar's review controls onto a second row where one row is too narrow for them. */ +.rowBreak { + display: none; +} + +@container forge-changes (max-width: 640px) { + .reviewRow { + order: 2; + } + + .rowBreak { + display: block; + flex-basis: 100%; + order: 1; + height: 4px; + } + + .progressSlot { + margin-left: auto; + } +} + .select { display: inline-flex; flex: 0 1 auto; @@ -173,7 +248,6 @@ flex: none; align-items: center; gap: 2px; - margin-left: auto; } .tool { @@ -371,6 +445,62 @@ transform: rotate(-90deg); } +.changedTag { + flex: none; +} + +/* The viewed mark: a native checkbox with its label as one bordered chip, peer to the file menu button. */ +.viewed { + display: inline-flex; + flex: none; + align-items: center; + gap: 6px; + box-sizing: border-box; + height: 24px; + padding: 0 8px 0 6px; + border: 0.5px solid var(--dsw-alias-border-l2); + border-radius: var(--dsw-radius-sm); + color: var(--dsw-alias-label-secondary); + white-space: nowrap; + cursor: pointer; + user-select: none; +} + +.viewed input { + margin: 0; + accent-color: var(--dsw-alias-state-business-primary); + cursor: pointer; +} + +.viewed:has(input:checked) { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .viewed:hover { + color: var(--dsw-alias-label-primary); + } +} + +.viewed:has(input:focus-visible) { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -1px; +} + +.viewed input:focus-visible { + outline: none; +} + +@container forge-changes (max-width: 520px) { + .viewed { + padding: 0 6px; + } + + .viewedLabel { + display: none; + } +} + .badge { flex: none; max-width: 50%; diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 983c6b58a3..833585a83a 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -7,7 +7,10 @@ * scope summary changes; a read keeps the previous changes on screen until it settles. */ -import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' +import { + useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type KeyboardEvent, + type ReactNode, +} from 'react' import clsx from 'clsx' import { Button, IconBranchOutlineRegular, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, @@ -21,10 +24,10 @@ import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-rig import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, - ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeCommitRange, ForgeDiffFile, ForgeLocalCommits, ForgeLocalDiff, + ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' -import type { ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeCommitList, ForgeReviewRequest, ForgeReviewResult } from '@deepseek-ai/dsh-experimental-forge/types' import { sameReviewSource, type ReviewQueue } from './review-queue.ts' import { ReviewThread, useFileReview } from './ReviewThread.tsx' import type { ReviewActions } from './ReviewComposer.tsx' @@ -32,7 +35,10 @@ import { SubmitReview } from './SubmitReview.tsx' import type { ReviewSelection, ReviewSource } from './review.ts' import { BaseMenu } from './BaseMenu.tsx' import { parseChangesAddress, type ChangesSource } from './changes-address.ts' -import type { createChangesStore } from './changes-store.ts' +import type { ChangesLens, createChangesStore } from './changes-store.ts' +import { CommitMenu } from './CommitMenu.tsx' +import { HideTestsSwitch, LensControl, LensMenu, LENSES, ViewedProgress } from './ReviewControls.tsx' +import { viewedStateOf, type ViewedFiles, type ViewedMarks } from './viewed-files.ts' import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx' import { FileTreePane, type FileTreePosition } from './FileTreePane.tsx' import { changedFileTree, filesInTreeOrder } from './file-tree.ts' @@ -68,8 +74,16 @@ export interface ChangesTabInjected { readonly diffBases: (query: string, signal: AbortSignal) => Promise> /** Read the new side of one file in a local scope. */ readonly localText: (scope: ForgeLocalScope, path: string) => Promise> - /** Read the changes of a change request by its binding URL; `signal` aborts the read. */ - readonly changeRequestDiff: (url: string, signal: AbortSignal) => Promise> + /** List the commits of the `branch` scope compared with `base`, or with the automatic fork point for null; `signal` aborts the read. */ + readonly localCommits: (base: string | null, signal: AbortSignal) => Promise> + /** Read the changes of a change request, or of consecutive commits of it, by its binding URL; `signal` aborts the read. */ + readonly changeRequestDiff: ( + url: string, commits: ForgeCommitRange | null, signal: AbortSignal, + ) => Promise> + /** List the commits of a change request, or null when its provider does not read commits; `signal` aborts the read. */ + readonly changeRequestCommits: (url: string, signal: AbortSignal) => Promise> + /** The Session's viewed marks, kept in the browser. */ + readonly viewedFiles: ViewedFiles /** Read one file of a change request at a commit. */ readonly changeRequestText: (url: string, commit: string, path: string) => Promise> /** Open a URL outside the app. */ @@ -106,8 +120,10 @@ type ChangesData = readonly files: readonly ForgeDiffFile[] /** Binding URL of the change request. */ readonly url: string - /** Head commit the files describe, which supplies unchanged lines. */ + /** Commit the files end at, the head or the last chosen commit, which supplies unchanged lines. */ readonly headSha: string + /** Commits the files cover, or null for the whole change request. */ + readonly commits: ForgeCommitRange | null /** Commits the checkout's branch has beyond the head, or null. */ readonly localAhead: number | null /** Web page of each file at the head. */ @@ -148,6 +164,7 @@ const FAILURE: Partial> = { 'forgePanel/no-fork-point': 'diff.noForkPoint', 'forgePanel/diff-too-large': 'diff.tooLarge', 'forgePanel/filter-config-failed': 'diff.filterConfigFailed', + 'forgePanel/commits-missing': 'commits.missing', } /** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */ @@ -171,6 +188,7 @@ function baseFailureOf(failed: string | null, base: ForgeBaseBranch | null, t: T async function readChanges( source: ChangesSource, scope: ForgeLocalScope, + commits: ForgeCommitRange | null, reads: Pick, signal: AbortSignal, ): Promise> { @@ -180,10 +198,10 @@ async function readChanges( const { files, base, omitted } = result.value return { ok: true, value: { kind: 'local', files, scope, base, omitted } } } - const result = await reads.changeRequestDiff(source.url, signal) + const result = await reads.changeRequestDiff(source.url, commits, signal) if (!result.ok) return result const { files, headSha, localAhead, fileUrls } = result.value - return { ok: true, value: { kind: 'change', files, url: source.url, headSha, localAhead, fileUrls } } + return { ok: true, value: { kind: 'change', files, url: source.url, headSha, commits, localAhead, fileUrls } } } /** The ref that identifies a comparison: the chosen base branch, or null for the automatic fork point and other scopes. */ @@ -191,25 +209,51 @@ function baseRefOf(scope: ForgeLocalScope): string | null { return scope.kind === 'branch' ? scope.base : null } +/** The commits a local scope shows, or null for all of them and for scopes other than `branch`. */ +function commitsOf(scope: ForgeLocalScope): ForgeCommitRange | null { + return scope.kind === 'branch' ? scope.commits : null +} + /** The source review comments on loaded changes record: the change request head, or the local scope with its base. */ function reviewSourceOf(data: ChangesData): ReviewSource { return data.kind === 'local' - ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope) } - : { kind: 'change', url: data.url, headSha: data.headSha } + ? { kind: 'local', scope: data.scope.kind, base: data.base, baseRef: baseRefOf(data.scope), commits: commitsOf(data.scope) } + : { kind: 'change', url: data.url, headSha: data.headSha, commits: data.commits } } -/** The files that start expanded: every file until those above it change more than {@link OPEN_LINES} lines. */ -function initiallyOpen(files: readonly ForgeDiffFile[]): ReadonlySet { +/** + * Identity of a diff source for viewed marks: the change request or local scope with its base ref and chosen commits. + * A change request's marks stay across head commits, so a file whose change a new push altered reads as changed. + */ +function viewedSourceOf(source: ReviewSource): string { + return JSON.stringify(source.kind === 'local' + ? ['local', source.scope, source.baseRef, source.commits] + : ['change', source.url, source.commits]) +} + +/** + * The files that start expanded: every file not marked viewed until those above it change more than {@link OPEN_LINES} lines. + * @param files - every file in display order. + * @param marks - the viewed marks when the files loaded. + * @returns the paths of the expanded files. + */ +function initiallyOpen(files: readonly ForgeDiffFile[], marks: ViewedMarks): ReadonlySet { const open = new Set() let above = 0 for (const file of files) { if (above > OPEN_LINES) break + if (viewedStateOf(marks, file.path, file.digest) === 'viewed') continue open.add(file.path) above += drawnLines(file) } return open } +/** Whether a file shows under a lens while test files hide or not. */ +function shownBy(file: ForgeDiffFile, lens: ChangesLens, hideTests: boolean): boolean { + return !(hideTests && file.layer === 'test') && (lens === 'all' || file.layer === lens) +} + /** What a rename badge names: the old file name, or the old path when only the directory changed. */ function renamedFrom(previous: string, path: string): string { const name = pathPartsOf(previous).name @@ -231,9 +275,11 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { return parts.join(' · ') } -function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onReview, t }: { +function ChangeHeader({ url, entry, openLink, commitMenu, reviewCount, reviewDisabled, onReview, t }: { readonly url: string readonly entry: ForgePanelChangeRequest | undefined + /** Commit picker left of the review button. */ + readonly commitMenu: ReactNode readonly reviewCount: number readonly reviewDisabled: boolean readonly onReview: () => void @@ -249,9 +295,12 @@ function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onRev {snapshot === null ? url : snapshot.title} {number !== null && {t('change.number', { number })}} - + + {commitMenu} + + - )} + {(scope === 'branch' || creatable) && + {scope === 'branch' && commitMenu} + {creatable && } + }
) } @@ -369,8 +421,8 @@ function OrphanReviews({ path, actions, t }: PropsLocale & { * @returns the view body. */ export function ChangesTab({ - useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, changeRequestDiff, - changeRequestText, + useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, diffBases, localText, localCommits, changeRequestDiff, + changeRequestText, changeRequestCommits, viewedFiles, openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() @@ -423,6 +475,7 @@ export function ChangesTab({ const [wanted, setWanted] = useState(null) const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) const [treePosition, setTreePosition] = useState('left') + const [treeWidth, setTreeWidth] = useState(0) const treeId = useId() const [chosen, setChosen] = useState>>({}) // Each navigation applies once; its file, if it names one, opens and scrolls into view. @@ -447,7 +500,18 @@ export function ChangesTab({ const state = snapshot?.state ?? null const scope = choices?.scope ?? 'branch' const base = choices?.base ?? null - const localScope = useMemo((): ForgeLocalScope => scope === 'branch' ? { kind: 'branch', base: base?.ref ?? null } : { kind: scope }, [scope, base]) + const chosenCommits = choices?.commits ?? null + const lens = choices?.lens ?? 'all' + const hideTests = choices?.hideTests ?? false + const localScope = useMemo((): ForgeLocalScope => scope === 'branch' + ? { kind: 'branch', base: base?.ref ?? null, commits: chosenCommits } : { kind: scope }, [scope, base, chosenCommits]) + const changeCommits = source.kind === 'change' ? chosenCommits : null + const changeUrlOf = source.kind === 'change' ? source.url : '' + const listChangeCommits = useCallback( + (signal: AbortSignal) => changeRequestCommits(changeUrlOf, signal), [changeRequestCommits, changeUrlOf], + ) + const baseRef = base?.ref ?? null + const listLocalCommits = useCallback((signal: AbortSignal) => localCommits(baseRef, signal), [localCommits, baseRef]) const split = choices?.split ?? true const wrap = choices?.wrap ?? true const entry = source.kind === 'change' ? state?.changeRequests.find(item => item.url === source.url) : undefined @@ -456,7 +520,9 @@ export function ChangesTab({ const pending = entry !== undefined && entry.ref !== null && entry.update === null const head = entry?.snapshot?.headSha ?? (pending ? null : '') const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head - const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : 'change' + // The commits change with the head of a change request, and with the local branch or its base. + const commitsVersion = source.kind === 'local' ? `${baseRef ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? '' + const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}` const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null) const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null) // Names the read the inputs ask for; it is in flight until `finished` matches it. @@ -465,7 +531,7 @@ export function ChangesTab({ useEffect(() => { if (!tab.visible || read === null || read === finished) return const controller = new AbortController() - void readChanges(source, localScope, { localDiff, changeRequestDiff }, controller.signal).then((result) => { + void readChanges(source, localScope, changeCommits, { localDiff, changeRequestDiff }, controller.signal).then((result) => { if (controller.signal.aborted) return setFinished(read) if (result.ok) { @@ -476,9 +542,15 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, source, localScope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, source, localScope, changeCommits, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null - const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const allFiles = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) + const files = useMemo(() => allFiles.filter(file => shownBy(file, lens, hideTests)), [allFiles, lens, hideTests]) + const lensCounts = useMemo(() => Object.fromEntries(LENSES.map(item => [item, + allFiles.filter(file => shownBy(file, item, hideTests)).length])) as Record, [allFiles, hideTests]) + const shownSource = data === null ? null : reviewSourceOf(data) + const viewedKey = shownSource === null ? '' : viewedSourceOf(shownSource) + const marks = useSyncExternalStore(viewedFiles.subscribe, () => viewedFiles.marksOf(viewedKey)) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. const rereading = read !== null && finished !== read && data !== null const failed = failure !== null && failure.key === dataKey ? failure.code : null @@ -487,17 +559,29 @@ export function ChangesTab({ const latest = useRef(data) useEffect(() => { latest.current = data }, [data]) const [revealed, setRevealed] = useState>(new Set()) - const initial = useMemo(() => initiallyOpen(files), [files]) + // The line budget counts the files not marked viewed when the diff loads, so later marks leave it unchanged. A file stays + // collapsed while it is marked viewed unless the reader expands it; a file whose change differs from its mark expands + // like an unmarked one. + const initial = useMemo(() => initiallyOpen(allFiles, marks), [allFiles]) + const expandedByDefault = (file: ForgeDiffFile): boolean => initial.has(file.path) && viewedStateOf(marks, file.path, file.digest) !== 'viewed' + const isExpanded = (file: ForgeDiffFile): boolean => chosen[file.path] ?? expandedByDefault(file) const sections = useRef(new Map()) const scrollport = useRef(null) // A short final file cannot align with the viewport top; retain its jump until the reader scrolls away. const jumpPosition = useRef<{ readonly data: ChangesData; readonly top: number } | null>(null) useLayoutEffect(() => { if (!tab.visible || wanted === null || data === null) return + // A file the lens or the test switch hides is shown before the view scrolls to it. + const hidden = allFiles.find(file => file.path === wanted && !shownBy(file, lens, hideTests)) + if (hidden !== undefined) { + if (lens !== 'all') actions.lensed(tab.id, 'all') + if (hideTests && hidden.layer === 'test') actions.toggledTests(tab.id) + return + } sections.current.get(wanted)?.scrollIntoView({ block: 'start' }) if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop } setWanted(null) - }, [tab.visible, wanted, data]) + }, [tab.visible, wanted, data, allFiles, lens, hideTests, actions, tab.id]) const refresh = (): void => { setAttempt(value => value + 1) } const root = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.root : null // A chosen base branch that is gone or shares no history with HEAD offers the automatic fork point instead. @@ -507,8 +591,10 @@ export function ChangesTab({ const failureText = baseFailure ?? t(message ?? 'diff.error') const changeUrl = source.kind === 'change' ? entry?.snapshot?.url ?? source.url : null const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed') - const automaticBase = baseFailure !== undefined && ( + const automaticBase = baseFailure !== undefined ? ( + ) : failed === 'forgePanel/commits-missing' && ( + ) /** Apply a change to the unchanged lines of `owner`, unless newer changes replaced it. */ @@ -553,7 +639,8 @@ export function ChangesTab({ return list } - const reviewForm = tab.visible && data !== null && reviewOpen && data.kind === 'change' && { setReviewOpen(false) }} check={() => { openLink(data.url) }} reconcile={() => { queue.finish(false); setReviewError(null) }} submit={() => { @@ -563,9 +650,9 @@ export function ChangesTab({ }} t={t} /> const recordActions: ReviewActions = { - source: data !== null ? reviewSourceOf(data) : source.kind === 'local' - ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope) } - : { kind: 'change', url: source.url, headSha: '' }, + source: shownSource ?? (source.kind === 'local' + ? { kind: 'local', scope, base: null, baseRef: baseRefOf(localScope), commits: commitsOf(localScope) } + : { kind: 'change', url: source.url, headSha: '', commits: changeCommits }), records: queue, addToInput: addReviewToInput, openLink, } const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] @@ -578,26 +665,35 @@ export function ChangesTab({ setChosen(value => ({ ...value, [path]: true })) setWanted(path) } + /** + * The file being read: the file last jumped to while the scroll stays there, else the last file whose section starts + * above the viewport top. + */ + const currentIndex = (viewport: HTMLElement): number => { + const remembered = jumpPosition.current + const index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop + ? files.findIndex(file => file.path === treeState.selected) : -1 + if (index >= 0) return index + const top = viewport.getBoundingClientRect().top + return Math.max(0, files.findLastIndex((file) => { + const section = sections.current.get(file.path) + return section !== undefined && section.getBoundingClientRect().top <= top + 1 + })) + } + /** Whether a key press belongs to a field, a comment, a menu, or a text selection rather than to the file list. */ + const typing = (container: HTMLElement, origin: EventTarget): boolean => { + const selection = window.getSelection() + return !(origin instanceof HTMLElement) || !container.contains(origin) + || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment], [role="menu"]') !== null + || (selection !== null && !selection.isCollapsed) + } const navigateFiles = (event: KeyboardEvent): void => { if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight')) return const viewport = event.currentTarget - const origin = event.target - const selection = window.getSelection() - if (!(origin instanceof HTMLElement) || !viewport.contains(origin) - || origin.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [data-forge-comment]') !== null - || (selection !== null && !selection.isCollapsed)) return - const remembered = jumpPosition.current - let index = remembered !== null && remembered.data === data && remembered.top === viewport.scrollTop - ? files.findIndex(file => file.path === treeState.selected) : -1 - if (index < 0) { - const top = viewport.getBoundingClientRect().top - index = Math.max(0, files.findLastIndex((file) => { - const section = sections.current.get(file.path) - return section !== undefined && section.getBoundingClientRect().top <= top + 1 - })) - } + if (typing(viewport, event.target)) return + const index = currentIndex(viewport) event.preventDefault() event.stopPropagation() const next = files[index + (event.key === 'ArrowRight' ? 1 : -1)] @@ -605,6 +701,37 @@ export function ChangesTab({ viewport.focus({ preventScroll: true }) jump(next.path) } + /** Mark a file viewed and collapse it, keeping its header in view, or clear its mark and expand it. */ + const markViewed = (owner: ChangesData, file: ForgeDiffFile, viewed: boolean): void => { + if (!viewedFiles.mark(viewedKey, owner.files, file.path, viewed)) { + report('viewed.saveFailed') + return + } + const section = sections.current.get(file.path) + const viewport = scrollport.current + if (viewed && section !== undefined && viewport !== null + && section.getBoundingClientRect().top < viewport.getBoundingClientRect().top) setWanted(file.path) + // A new mark collapses the file through its default; clearing a mark expands it. + setChosen(({ [file.path]: _choice, ...value }) => viewed ? value : { ...value, [file.path]: true }) + } + /** The shown file whose section holds an element or a text node, if any. */ + const fileAt = (target: EventTarget | null | undefined): ForgeDiffFile | undefined => { + const element = target instanceof Element ? target : target instanceof Node ? target.parentElement : null + const path = element?.closest('[data-forge-diff-file]')?.getAttribute('data-forge-diff-file') + return files.find(file => file.path === path) + } + // `V` marks or clears the file being read, from anywhere in the tab except fields, comments, and menus: the file + // holding the focus, else the one holding the text cursor, as after clicking its code, else the file at the top. + const toggleViewed = (event: KeyboardEvent): void => { + const viewport = scrollport.current + if (!tab.visible || event.defaultPrevented || event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey + || event.key.toLowerCase() !== 'v' || viewport === null || data === null || typing(event.currentTarget, event.target)) return + const file = fileAt(event.target) ?? fileAt(window.getSelection()?.anchorNode) ?? files[currentIndex(viewport)] + /* v8 ignore next -- the files region renders only while files show, so its position always names one */ + if (file === undefined) return + event.preventDefault() + markViewed(data, file, viewedStateOf(marks, file.path, file.digest) !== 'viewed') + } let body: ReactNode if (data === null) { @@ -635,10 +762,12 @@ export function ChangesTab({ } } else if (data.files.length === 0) { body =
{orphanRecords}
{t('diff.empty')}
+ } else if (files.length === 0) { + body =
{orphanRecords}
{t('lens.empty')}
} else { body = (
{ if (jumpPosition.current?.top !== event.currentTarget.scrollTop) jumpPosition.current = null }}> @@ -654,7 +783,7 @@ export function ChangesTab({ records: queue, openLink, reviewStarted: reviewState.comments.length > 0, onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, publishingBlocked: reviewState.uncertain !== null, - ...data.kind === 'local' ? {} : { + ...data.kind === 'local' || data.commits !== null ? {} : { queue: selection => queue.add(selection), publish: selection => selection.source.kind === 'change' ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, @@ -662,8 +791,8 @@ export function ChangesTab({ : Promise.resolve(t('review.stale')), }, }} - expanded={chosen[path] ?? initial.has(path)} - onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? initial.has(path)) })) }} + expanded={isExpanded(file)} + onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? expandedByDefault(file)) })) }} large={drawnLines(file) > LARGE_FILE_LINES} revealed={revealed.has(path)} onReveal={() => { setRevealed(value => new Set([...value, path])) }} @@ -675,6 +804,8 @@ export function ChangesTab({ badge={badgeOf(file, data, t)} tooltip={pathTooltipOf(file, t)} actions={fileActions(data, file)} + viewed={viewedStateOf(marks, path, file.digest)} + onViewed={(viewed) => { markViewed(data, file, viewed) }} sectionRef={(element) => { if (element === null) sections.current.delete(path) else sections.current.set(path, element) @@ -694,7 +825,7 @@ export function ChangesTab({ jump, } // The toolbar collapses every file while any is expanded, as the files on screen show, and expands every file otherwise. - const anyExpanded = files.some(file => chosen[file.path] ?? initial.has(file.path)) + const anyExpanded = files.some(isExpanded) const expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll') const treeAction = t(treePosition === 'left' ? 'diff.moveFileTreeRight' : treePosition === 'right' ? 'diff.hideFileTree' : 'diff.showFileTreeLeft') let additions = 0 @@ -703,13 +834,21 @@ export function ChangesTab({ additions += file.additions deletions += file.deletions } + const viewedCount = files.filter(file => viewedStateOf(marks, file.path, file.digest) === 'viewed').length + const treeShown = allFiles.length > 0 && treePosition !== 'hidden' + const lensProps = { lens, counts: lensCounts, hideTests, choose: (next: ChangesLens) => { actions.lensed(tab.id, next) }, t } + const commitMenu = source.kind === 'local' && scope !== 'branch' ? null : { actions.committed(tab.id, next) }} t={t} /> + const toolbarStyle: CSSProperties & { '--forge-tree-width': string } = { '--forge-tree-width': `${treeWidth}px` } return ( -
+
{source.kind === 'local' ? { actions.based(tab.id, next) }} createChangeRequest={createChangeRequest} t={t} /> - : { setReviewOpen(true) }} t={t} />} + diffBases={diffBases} choose={(next) => { actions.based(tab.id, next) }} commitMenu={commitMenu} + createChangeRequest={createChangeRequest} t={t} /> + : { setReviewOpen(true) }} t={t} />} {!reviewOpen && reviewState.error !== null && {t(reviewState.error === 'load' ? 'review.loadFailed' : 'review.saveFailed')}} {!reviewOpen && reviewState.uncertain !== null && !reviewBusy && source.kind === 'change' &&
{t('review.unknown')} @@ -718,45 +857,58 @@ export function ChangesTab({
} {!reviewOpen && reviewError !== null && reviewState.uncertain === null && {reviewError}} -
- {tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && } - {files.length > 0 && } - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + - + {allFiles.length > 0 && } +
{data !== null && failed !== null && ( {body} - {files.length > 0 && } + {allFiles.length > 0 && }
) diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css new file mode 100644 index 0000000000..34159de448 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css @@ -0,0 +1,130 @@ +/* Commit picker trigger in the changes header and its menu of commits, oldest first. */ +.anchor { + flex: 0 1 auto; + min-width: 0; +} + +.trigger { + display: inline-flex; + flex: 0 1 auto; + align-items: center; + gap: 4px; + box-sizing: border-box; + min-width: 0; + max-width: 100%; + height: 28px; + padding: 0 6px 0 8px; + border: 0; + border-radius: var(--dsw-radius-sm); + background: transparent; + color: var(--dsw-alias-label-primary); + font: inherit; + white-space: nowrap; + cursor: pointer; +} + +.chosen .triggerName { + font-family: var(--ds-font-family-code); +} + +.trigger[aria-expanded='true'] { + background: var(--dsw-alias-interactive-bg-hover); +} + +@media (hover: hover) { + .trigger:hover { + background: var(--dsw-alias-interactive-bg-hover); + } +} + +.trigger:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: -2px; +} + +.trigger svg { + flex: none; +} + +.triggerName { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; +} + +.menu { + width: min(400px, calc(100vw - 24px)); +} + +.rows { + max-height: 360px; + overflow: auto; + padding: 4px; + color: var(--dsw-alias-label-primary); + font-size: 12px; +} + +.option { + display: flex; + align-items: center; + gap: 8px; + width: 100%; + min-width: 0; +} + +.allTitle { + flex: 1; + min-width: 0; +} + +.sha { + flex: none; + color: var(--dsw-alias-label-secondary); + font-family: var(--ds-font-family-code); +} + +.title { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.meta { + flex: none; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; +} + +.check { + display: inline-flex; + flex: none; + color: var(--dsw-alias-state-business-primary); +} + +.unchecked { + visibility: hidden; +} + +.label { + padding: 6px 8px 4px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 15px; +} + +.status { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 8px; + color: var(--dsw-alias-label-secondary); +} + +.note { + padding: 8px; + color: var(--dsw-alias-label-tertiary); + font-size: 11px; + line-height: 16px; +} diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx new file mode 100644 index 0000000000..58e7702b75 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx @@ -0,0 +1,162 @@ +/** + * Commit picker of the changes header: every commit, or one commit, or with Shift a run of consecutive commits of a + * change request or of the local `branch` scope, listed oldest first like the code host's commit list. + */ + +import { useEffect, useRef, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { + Button, IconCheckOutlineRegular, IconChevronDownOutlineRegular, Menu, MenuItemButton, StateDot, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types' +import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' +import type { ForgeCommitRange } from '../types.ts' +import { formatAgo } from './format.ts' +import type { NS } from './locales.ts' +import css from './CommitMenu.module.css' + +/** Characters of a commit object name the picker shows. */ +const SHORT = 7 + +/** Props of the commit picker. */ +export interface CommitMenuProps extends PropsLocale { + /** Commits shown, or null for all of them. */ + readonly chosen: ForgeCommitRange | null + /** Whether the owning tab is visible; a hidden tab keeps the menu closed. */ + readonly visible: boolean + /** Read the commits; null means the source cannot show single commits. `signal` aborts the read. */ + readonly list: (signal: AbortSignal) => Promise> + /** Changes when the commits may have changed, such as a new head commit; the next opening reads them again. */ + readonly version: string + /** Show consecutive commits, or every commit for null. */ + readonly choose: (commits: ForgeCommitRange | null) => void +} + +/** + * Name the shown commits on the trigger. + * @param chosen - the shown commits, or null for all of them. + * @param t - forge panel copy. + * @returns the label. + */ +export function commitsLabel(chosen: ForgeCommitRange | null, t: PropsLocale['t']): string { + if (chosen === null) return t('commits.all') + if (chosen.from === chosen.to) return chosen.from.slice(0, SHORT) + return t('commits.range', { from: chosen.from.slice(0, SHORT), to: chosen.to.slice(0, SHORT) }) +} + +/** + * Render the trigger and, while open, the commit list. A click shows one commit; a Shift click shows the commits + * from the last commit clicked without Shift to the clicked one. + * @param props - the shown commits, the listing read, the choose action, and copy. + * @returns the trigger with its portalled menu, or nothing when the source cannot show single commits. + */ +export function CommitMenu({ chosen, visible, list, version, choose, t }: CommitMenuProps): ReactNode { + const [open, setOpen] = useState(false) + const [attempt, setAttempt] = useState(0) + const [listing, setListing] = useState<{ readonly version: string; readonly result: RemoteResult } | null>(null) + const shift = useRef(false) + const anchor = useRef(chosen?.from ?? null) + const loaded = useRef(null) + const shown = visible && open + const current = listing?.version === version ? listing.result : null + // The list is read once per version, which tells whether the source has commits to pick, and again on each opening. + useEffect(() => { + if (!visible || (!shown && loaded.current === version)) return + const controller = new AbortController() + void list(controller.signal).then((result) => { + if (controller.signal.aborted) return + loaded.current = version + setListing({ version, result }) + }) + return () => { controller.abort() } + }, [visible, shown, version, attempt, list]) + if (current?.ok === true && current.value === null) return null + const commits = current?.ok === true && current.value !== null ? current.value : null + const pick = (sha: string | null): void => { + setOpen(false) + if (sha === null || commits === null) { + anchor.current = null + if (chosen !== null) choose(null) + return + } + const order = commits.commits.map(commit => commit.sha) + const start = shift.current && anchor.current !== null && order.includes(anchor.current) ? anchor.current : sha + if (!shift.current || start === sha) anchor.current = sha + const [from, to] = order.indexOf(start) <= order.indexOf(sha) ? [start, sha] : [sha, start] + if (from !== chosen?.from || to !== chosen.to) choose({ from, to }) + } + const inChosen = (index: number): boolean => { + if (chosen === null || commits === null) return false + const order = commits.commits.map(commit => commit.sha) + return index >= order.indexOf(chosen.from) && index <= order.indexOf(chosen.to) && order.includes(chosen.from) + } + + let body: ReactNode + if (current === null) { + body =
{t('commits.loading')}
+ } else if (!current.ok || commits === null) { + body = ( +
+ {t('commits.failed')} + +
+ ) + } else { + const now = Date.now() + body = <> + { pick(null) }}> + + {t('commits.all')} + {t('commits.count', { count: commits.commits.length })} + {chosen === null && } + + + {commits.commits.length > 0 &&
{t('commits.shiftHint')}
} + {commits.commits.map((commit, index) => { + const selected = inChosen(index) + return ( + { pick(commit.sha) }}> + + {commit.sha.slice(0, SHORT)} + {commit.title} + {formatAgo(commit.authoredAt, now, t) ?? ''} + + + + ) + })} + {commits.truncated &&
{t('commits.truncated', { count: commits.commits.length })}
} + + } + + const label = commitsLabel(chosen, t) + return ( + { setOpen(false) }} + anchor={( + + + + )} + > + {/* Rows report activation without the event, so the modifier is read while the click or key travels to them. */} +
{ shift.current = event.shiftKey }} + onKeyDownCapture={(event) => { shift.current = event.shiftKey }}> + {body} +
+
+ ) +} diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index eb7e21e6b0..ad46c66132 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -9,7 +9,7 @@ import clsx from 'clsx' import { flushSync } from 'react-dom' import { FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, - Tooltip, + Tag, Tooltip, languageForPath, Menu, MenuItemButton, useCodeHighlighter, type CodeHighlighter, type HighlightSpan, } from '@deepseek-ai/dsh-client-ui-primitives' import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' @@ -23,6 +23,7 @@ import { ReviewComposer, type ReviewActions } from './ReviewComposer.tsx' import reviewCss from './ReviewComposer.module.css' import { FileLabel } from './FileLabel.tsx' import type { ForgePanelKey, NS } from './locales.ts' +import type { ViewedState } from './viewed-files.ts' import css from './ChangesTab.module.css' type Translate = PropsLocale['t'] @@ -72,6 +73,10 @@ export interface DiffFileProps { readonly tooltip: string /** Rows of the file's menu. */ readonly actions: readonly DiffFileAction[] + /** Whether the reader marked this change viewed, or marked an earlier change of the file. */ + readonly viewed: ViewedState + /** Mark the file viewed, which also collapses it, or clear the mark. */ + readonly onViewed: (viewed: boolean) => void /** Receives the section element, which scrolling to the file targets. */ readonly sectionRef: (element: HTMLElement | null) => void /** Forge panel copy. */ @@ -438,10 +443,11 @@ function FileMenu({ name, actions, t }: { * @returns the file section. */ export function DiffFile(props: DiffFileProps): ReactNode { - const { file, expanded, onToggle, badge, tooltip, actions, sectionRef, t } = props + const { file, expanded, onToggle, badge, tooltip, actions, viewed, onViewed, sectionRef, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) return ( -
+
{expanded && } diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx index b055655814..a4995615f1 100644 --- a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx @@ -15,12 +15,14 @@ export type FileTreePosition = 'right' | 'left' | 'hidden' /** * Render a keyboard- and pointer-resizable tree beside the diff. - * @param props - tree rows, pane position, and the toggle's controlled element id. + * @param props - tree rows, pane position, the toggle's controlled element id, and the receiver of the shown width. * @returns the bounded pane and its resize separator. */ -export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { +export function FileTreePane({ position, id, onWidth, ...props }: ChangedFilesProps & { readonly position: FileTreePosition readonly id: string + /** Receives the pane's width in pixels whenever it changes, so the toolbar can align a cell with it. */ + readonly onWidth: (width: number) => void }): ReactNode { const pane = useRef(null) const drag = useRef<{ pointer: number; x: number; width: number } | null>(null) @@ -41,6 +43,7 @@ export function FileTreePane({ position, id, ...props }: ChangedFilesProps & { return () => { observer.disconnect() } }, []) const shown = Math.min(width, maximum) + useLayoutEffect(() => { onWidth(shown) }, [shown, onWidth]) const direction = position === 'left' ? 1 : -1 const resize = (next: number): void => { setWidth(Math.round(Math.max(MIN_WIDTH, Math.min(maximum, next)))) } return
diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index a65edc8570..7a66da2466 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -462,7 +462,8 @@ export function ChangesTab({ // Names the read the inputs ask for; it is in flight until `finished` matches it. const read = version === null ? null : `${dataKey}\n${navigation.revision}\n${attempt}\n${version}` const [finished, setFinished] = useState(null) - // A change request read refused because the head moved past its status stays in flight until a later status arrives. + // A change request read refused because the head moved past its status stays in flight until a status later than + // the one the read started with arrives; one that arrived during the read starts the next read at once. const statusAt = entry?.update?.fetchedAt ?? null const latestStatusAt = useRef(statusAt) useEffect(() => { latestStatusAt.current = statusAt }, [statusAt]) @@ -488,7 +489,7 @@ export function ChangesTab({ } }) return () => { controller.abort() } - }, [tab.visible, read, waiting, source, localScope, dataKey, localDiff, changeRequestDiff]) + }, [tab.visible, read, refused, waiting, source, localScope, dataKey, localDiff, changeRequestDiff]) const data = loaded !== null && loaded.key === dataKey ? loaded.data : null const files = useMemo(() => filesInTreeOrder(changedFileTree(data?.files ?? [])), [data]) // The centered loader marks a first read; the toolbar's glyph turns only while shown changes are read again. diff --git a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx index e7305ff6d1..8e11e4c0d8 100644 --- a/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/change-request-card.client.spec.tsx @@ -263,6 +263,8 @@ describe('expanded ChangeRequestCard', () => { 'Changes requested · 1 unresolved', 'error'], ['more threads than the provider counted', { reviewDecision: 'review-required', unresolvedThreads: 1200, threadsTruncated: true }, 'Review required · 1,200+ unresolved', null], + ['uncounted threads after resolved ones', { reviewDecision: 'approved', unresolvedThreads: 0, threadsTruncated: true }, + 'Approved · 0+ unresolved', 'success'], ] as const)('states the review of %s', (_label, overrides, text, tone) => { const value = rowValue(card(entry(1, snapshot(1, overrides)), { expanded: true }).item, en['change.row.review']) expect(value.textContent).toBe(text) diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 1abfc93d1a..e6a2912325 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -20,7 +20,7 @@ import type { PanelSnapshot } from '../src/client/source.ts' import css from '../src/client/ChangesTab.module.css' import baseCss from '../src/client/BaseMenu.module.css' import type { - ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelState, + ForgeBaseBranch, ForgeBaseBranches, ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgePanelChangeRequest, ForgePanelState, } from '../src/types.ts' import { entry, ready, snapshot } from './client-fixtures.client.ts' @@ -1119,6 +1119,29 @@ describe('ChangesTab change requests', () => { expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts']) }) + it.each([ + ['a later poll with the same head', (polled: ForgePanelChangeRequest) => polled], + ['a failed poll that keeps the earlier status', (polled: ForgePanelChangeRequest) => ({ + ...polled, update: { key: polled.update!.key, fetchedAt: 2, failure: { code: 'unavailable', message: 'down' } }, + } as const)], + ] as const)('reads again at once when %s arrived while a read the host refused as stale was in flight', async (_label, arrive) => { + const refused = Promise.withResolvers() + const m = mount({ source, setup: (faces) => { faces.changeRequestDiff.mockReturnValueOnce(refused.promise) } }) + await settle() + expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() + + const polled = entry(7, snapshot(7)) + const later = arrive({ ...polled, update: { ...polled.update!, fetchedAt: 2 } }) + act(() => { m.panel.set({ state: ready({ changeRequests: [later] }), disconnected: false }) }) + await settle() + expect(m.faces.changeRequestDiff).toHaveBeenCalledOnce() + refused.resolve(REFUSED.staleHead) + await settle() + + expect(m.faces.changeRequestDiff).toHaveBeenCalledTimes(2) + expect(m.paths()).toEqual(['docs/gone.txt', 'docs/notes.txt', 'src/app.ts']) + }) + it('keeps shown changes while a read waits for a later status, turning the refresh glyph', async () => { const m = mount({ source }) await settle() diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 8859923642..655506d0dc 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: 4f8cd0d3b2df749c - zh: 8d398c088900a535 + en: 4ae3c0d7fd03b0d5 + zh: bb11975bc30b80a8 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: f98e77171cba809f zh: 1b330cb342d69efe @@ -30,8 +30,8 @@ en: 26b946af4b742e17 zh: 00b34f0721ac72f6 /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work: - en: 3dba4fd8b8375b39 - zh: 79190c7cb7b68656 + en: 9f13ae6d928e4ef7 + zh: 09a549b1655f4de3 /deepseek-ai-dsh-experimental-forge-github/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 9b290e605a..37cb8dce5e 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -38,15 +38,15 @@ The provider runs `gh` as a host process, even when Sessions execute commands in The provider serves a remote URL in `https`, `http`, `ssh`, or `git` form, or in scp form such as `git@github.com:owner/name.git`, when its host is configured. HTTP(S) remotes retain custom ports in the host identity; SSH and Git transport ports are excluded. It serves pull request URLs of the form `https://///pull/` with any trailing path, query, or fragment, and builds that form without the suffix as the canonical URL. A readiness probe runs `gh auth status --hostname `: exit status 0 is `ready`, another exit status is `unauthenticated` with the first diagnostic line, and a `gh` that cannot start is `unavailable`. A head lookup returns up to 20 open pull requests whose head is the branch, newest first, excluding pull requests from forks; a lookup of the default branch returns none. -Polling returns the first 100 head-commit check contexts without following pages. An incomplete preview sets `checksTruncated` and keeps GitHub’s aggregate state; its counts do not describe the full list. `fetchChecks(ref, signal)` reads complete details only for the requested PR, pinning continuation pages to the first response’s rollup. The combined UTF-8 JSON responses must fit `maxOutputBytes`; excess returns `too-large`. Failed or non-advancing pages fail only this detail read and leave polling results intact. Runs with the same application, workflow, event, and check name keep only the newest run id; a queued replacement supersedes an older completed run. Runs without a numeric database id are retained by node id because their relative age is unknown. Commit status contexts keep the newest result per context name. Complete lists derive their indicator from these results; unknown context kinds retain GitHub’s aggregate state. +Polling returns the first 100 head-commit check contexts without following pages. An incomplete preview sets `checksTruncated` and keeps GitHub’s aggregate state; its counts do not describe the full list. `fetchChecks(ref, signal)` reads complete details only for the requested PR, pinning continuation pages to the first response’s rollup. The combined UTF-8 JSON responses, review thread pages included, must fit `maxOutputBytes`; excess returns `too-large`. Failed or non-advancing pages fail only this detail read and leave polling results intact. Runs with the same application, workflow, event, and check name keep only the newest run id; a queued replacement supersedes an older completed run. Runs without a numeric database id are retained by node id because their relative age is unknown. Commit status contexts keep the newest result per context name. Complete lists derive their indicator from these results; unknown context kinds retain GitHub’s aggregate state. -Every status read counts review threads in pages of up to 100 until it has counted `maxReviewThreads` (default 1,000) of them; each page after the first is one more GraphQL query. A pull request with more threads sets `threadsTruncated`, and its `unresolvedThreads` counts only the threads read. A thread page that fails or does not advance fails that pull request's status read and leaves the other pull requests of the batch intact. +Every status read counts review threads in pages of up to 100 until it has counted `maxReviewThreads` (default 1,000) of them; each page after the first is one more GraphQL query. A pull request with more threads sets `threadsTruncated`, and its `unresolvedThreads` counts only the threads read. A thread page that fails or does not advance fails that pull request's status read and leaves the other pull requests of the batch intact; a partial count is not published. Unfinished check runs and completed runs with stale, missing, or unrecognized conclusions map to `pending`. Other completed checks map to `success`, `failure` (failure, timed out, startup failure, or action required), `cancelled`, `skipped`, or `neutral`. Cancelled checks keep the rollup non-passing. Check runs keep their start and completion times. Commit status contexts map `SUCCESS` to `success`, `FAILURE` and `ERROR` to `failure`, and every other state to `pending`, and carry no times. A GraphQL `NOT_FOUND` error becomes a `not-found` failure. A response without GraphQL data or errors, including an HTTP error JSON body, uses the first stderr diagnostic or the body's message. Authentication diagnostics become `unauthenticated`; oversized check pages become `too-large`; rate limits and other failures become `unavailable`. Head lookups preserve the same diagnostic in their rejection. A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. @@ -97,6 +97,8 @@ None. Provider output reaches only host-side watchers. - **GitHub CLI on the host** — `gh` must be installed and signed in for each configured host; tokens in environment variables are not forwarded. Hosts missing from `hosts` are never read, including references retained across configuration changes. A status fetch returns `unavailable` for those references; a head lookup rejects before starting `gh`. - **Review thread bound** — a status read counts at most `maxReviewThreads` review threads per pull request; beyond it `unresolvedThreads` is a lower bound that `threadsTruncated` marks. +- **Batch deadline** — continuation pages of a pull request with many review threads lengthen its host's polling batch; a batch that outlives `ctx.forge`'s `fetchTimeoutMs` reports `unavailable` for every pull request in it, not only for the one with many threads. +- **Rewritten base branch** — the diff starts from the merge base of the head and the base commit GitHub recorded at the pull request's last update. After the base branch is force-pushed, that merge base can differ from the one GitHub's pull request view uses, so the patch can include or omit commits until the pull request is updated. - **No fork discovery** — head lookups exclude pull requests whose head is in another repository. - **Rate limits** — every poll costs one GraphQL query per host, plus one query per further page of 100 review threads, and a complete check read one more query per further page of 100 check records; every diff read costs one GraphQL query and one REST request. All count against the signed-in account’s rate limit. - **No merge queue** — a base branch that requires a merge queue refuses a direct merge, and the provider never queues one. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index 291ef3d085..836781e92a 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -38,15 +38,15 @@ kind: "package-reference" 当主机在配置中时,提供方服务 `https`、`http`、`ssh`、`git` 形式的远端 URL,以及 `git@github.com:owner/name.git` 这类 scp 形式。HTTP(S) 远端在主机标识中保留自定义端口;SSH 和 Git 传输端口不计入主机标识。它服务 `https://///pull/` 形式的 pull request URL,允许其后附带任意路径、查询或片段,并以去掉这些后缀的形式作为规范 URL。就绪探测运行 `gh auth status --hostname `:退出码为 0 时为 `ready`,其他退出码为 `unauthenticated` 并带第一行诊断,`gh` 无法启动时为 `unavailable`。按 head 分支查找时,最多返回 20 个以该分支为 head 的打开状态 pull request,按创建时间从新到旧排列,不包含来自 fork 的 pull request;查找默认分支时返回空结果。 -轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。 +轮询只返回 head 提交的前 100 条检查上下文,不追读后续页。预览不完整时设置 `checksTruncated` 并保留 GitHub 的汇总状态,局部计数不代表完整列表。`fetchChecks(ref, signal)` 仅按需读取指定 PR 的完整详情,后续页固定使用首次响应的 rollup。所有 JSON 响应(包括评审讨论分页)的 UTF-8 字节总量受 `maxOutputBytes` 限制,超出时返回 `too-large`。分页失败或游标不前进只使此次详情读取失败,保留轮询结果。同一应用、工作流、触发事件与检查名称的运行只保留运行 id 最新的一条;新的排队运行会替代旧的已完成运行。缺少数字数据库 id 的运行无法确定先后,因此按节点 id 保留。提交状态上下文按名称保留最新结果。完整列表从这些结果计算总体指示;未知上下文类型保留 GitHub 的汇总状态。 -每次状态读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响。 +每次状态读取按每页最多 100 个统计评审讨论,直到已统计 `maxReviewThreads`(默认 1,000)个为止;第一页之后每读一页多一次 GraphQL 查询。讨论更多的 pull request 设置 `threadsTruncated`,其 `unresolvedThreads` 只统计已读取的讨论。讨论分页失败或游标不前进时,该 pull request 的状态读取失败,同批其他 pull request 不受影响;不发布不完整的计数。 未完成的检查运行(check run),以及结论已过期、缺失或无法识别的已完成运行,均映射为 `pending`。其他已完成的检查映射为 `success`、`failure`(失败、超时、启动失败或需要操作)、`cancelled`、`skipped` 或 `neutral`。已取消的检查使汇总保持未通过状态。检查运行保留其开始与完成时间。提交状态上下文把 `SUCCESS` 映射为 `success`,把 `FAILURE` 与 `ERROR` 映射为 `failure`,其余状态均映射为 `pending`,且不带时间。GraphQL 的 `NOT_FOUND` 错误转为 `not-found` 失败。响应不含 GraphQL data 或 errors 时(包括 HTTP 错误 JSON),使用 stderr 的首条诊断或响应体的 message。认证诊断转为 `unauthenticated`;超出输出大小上限的检查分页转为 `too-large`;限流与其他失败转为 `unavailable`。head 查找在拒绝时保留相同诊断。 pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 @@ -97,6 +97,8 @@ pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 - **宿主需要 GitHub CLI**——必须安装 `gh` 并为每个已配置主机登录;环境变量中的令牌不会被转发。不在 `hosts` 中的主机永远不会被读取,包括配置变更后保留的引用。状态读取为这些引用返回 `unavailable`;head 查找会在启动 `gh` 前拒绝。 - **评审讨论上限**——每次状态读取每个 pull request 最多统计 `maxReviewThreads` 个评审讨论;超出时 `unresolvedThreads` 只是下限,由 `threadsTruncated` 标出。 +- **批次时限**——评审讨论很多的 pull request 的续页会拉长其主机的轮询批次;批次超过 `ctx.forge` 的 `fetchTimeoutMs` 时,批次内每个 pull request 都报告 `unavailable`,而不只是讨论很多的那个。 +- **基准分支被改写**——diff 从 head 与 GitHub 在 pull request 最后一次更新时记录的基准提交的合并基准开始。基准分支被强制推送后,该合并基准可能不同于 GitHub pull request 页面使用的合并基准,因此在 pull request 更新前,补丁可能多出或缺少提交。 - **不发现 fork**——按 head 分支查找时,不包含 head 位于其他仓库的 pull request。 - **速率限制**——每次轮询为每个主机消耗一次 GraphQL 查询,评审讨论每多一页(100 个)再消耗一次;完整检查读取时检查记录每多一页(100 条)再消耗一次;每次 diff 读取消耗一次 GraphQL 查询与一次 REST 请求。这些都计入已登录账号的速率配额。 - **不支持合并队列**——要求合并队列的基准分支会拒绝直接合并,提供方也不会把变更请求加入队列。 diff --git a/packages/experimental/forge-github/src/compare.ts b/packages/experimental/forge-github/src/compare.ts index f6c9ef4aec..3598b4f807 100644 --- a/packages/experimental/forge-github/src/compare.ts +++ b/packages/experimental/forge-github/src/compare.ts @@ -6,12 +6,20 @@ import { isCommit } from './urls.ts' /** Runs one reading `gh` command and maps a refusal to a failure, as the provider's reads do. */ export type GhTextReader = (args: readonly string[], signal: AbortSignal) => Promise +/** `gh` option that prints a response containing terminal escape sequences; `gh` 2.97 added it. */ +const ALLOW_ESCAPES = '--allow-escape-sequences' + +/** What a `gh` older than 2.97 reports for {@link ALLOW_ESCAPES}, before it sends any request. */ +const UNKNOWN_ALLOW_ESCAPES = `unknown flag: ${ALLOW_ESCAPES}` + /** * Read the unified patch from the merge base of `base` and `head` to `head`, as * GitHub computes the diff of a pull request with that base and head commit. * Both ends are commit object names, so the answer never follows a moving - * branch. The patch keeps terminal escape sequences that file contents hold; - * `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`. + * branch. The patch keeps terminal escape sequences that file contents hold: + * `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`, + * and an older `gh`, which rejects that option, prints them unchanged, so a + * rejection of the option alone repeats the read without it. * GitHub returns the patch however many files it changes; `read` bounds its size. * @param read - runs `gh` with the provider's output limit and failure mapping. * @param repository - repository that holds both commits, with an owner and name already checked for inlining. @@ -28,8 +36,8 @@ export async function readComparison( if (!isCommit(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) } const { host, owner, name } = repository - return await read([ - 'api', '--hostname', host, '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', - `repos/${owner}/${name}/compare/${base}...${head}`, - ], signal) + const request = ['-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`] + const patch = await read(['api', '--hostname', host, ALLOW_ESCAPES, ...request], signal) + if (typeof patch === 'string' || !patch.message.startsWith(UNKNOWN_ALLOW_ESCAPES)) return patch + return await read(['api', '--hostname', host, ...request], signal) } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index f48f98a07b..1cd66bad30 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -12,7 +12,7 @@ import { CHECKS_QUERY, hasGraphqlFields, HEAD_QUERY, mapCheckPageResponse, mapHeadResponse, mapPullRequestCommitsResponse, mapSnapshotResponse, mapThreadPageResponse, PULL_REQUEST_COMMITS_QUERY, snapshotQuery, THREADS_QUERY, } from './graphql.ts' -import type { SnapshotPages } from './graphql.ts' +import type { PageResult, SnapshotPages } from './graphql.ts' import { checkedRepository, isCommit, parsePullRequestUrl, parseRemoteUrl } from './urls.ts' import { submitGitHubReview } from './review.ts' @@ -262,25 +262,31 @@ export class GitHubProvider implements ForgeProvider { const query = snapshotQuery(refs, this.limits.maxReviewThreads) const output = await this.gh(['api', 'graphql', '--hostname', host, '-f', `query=${query.document}`], signal) const body = parseJson(output.stdout) - const threads: SnapshotPages['threads'] = async (id, cursor, first) => { - const page = await this.continuation(host, - ['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], signal) - if (!('stdout' in page)) return { ok: false, failure: page } - const value = parseJson(page.stdout) - return hasGraphqlFields(value) ? mapThreadPageResponse(value) : { ok: false, failure: responseFailure(page, value) } - } - if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads }) + // A complete check read retains every response it reads, so all of them share one byte budget. let bytes = Buffer.byteLength(output.stdout) const tooLarge: ForgeFailure = { code: 'too-large', message: 'GitHub check details exceed the output size limit' } - if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) - if (hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => { - const page = await this.continuation(host, ['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], signal) - if (!('stdout' in page)) return { ok: false, failure: page } + const overBudget = (page: GhOutput): boolean => { + if (!completeChecks) return false bytes += Buffer.byteLength(page.stdout) - if (bytes > this.limits.maxOutputBytes) return { ok: false, failure: tooLarge } + return bytes > this.limits.maxOutputBytes + } + const continuation = async ( + variables: readonly string[], map: (value: unknown) => PageResult, + ): Promise> => { + const page = await this.continuation(host, variables, signal) + if (!('stdout' in page)) return { ok: false, failure: page } + if (overBudget(page)) return { ok: false, failure: tooLarge } const value = parseJson(page.stdout) - return hasGraphqlFields(value) ? mapCheckPageResponse(value) : { ok: false, failure: responseFailure(page, value) } - } }) + return hasGraphqlFields(value) ? map(value) : { ok: false, failure: responseFailure(page, value) } + } + const threads: SnapshotPages['threads'] = async (id, cursor, first) => await continuation( + ['-f', `query=${THREADS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`, '-F', `first=${first}`], mapThreadPageResponse) + if (!completeChecks && hasGraphqlFields(body)) return await mapSnapshotResponse(body, query, { threads }) + if (bytes > this.limits.maxOutputBytes) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), tooLarge])) + if (hasGraphqlFields(body)) { + return await mapSnapshotResponse(body, query, { threads, checks: async (id, cursor) => await continuation( + ['-f', `query=${CHECKS_QUERY}`, '-f', `id=${id}`, '-f', `cursor=${cursor}`], mapCheckPageResponse) }) + } const failure = responseFailure(output, body) return new Map([...query.targets.values()].map(ref => [changeRequestKey(ref), failure] as const)) } diff --git a/packages/experimental/forge-github/tests/compare.spec.ts b/packages/experimental/forge-github/tests/compare.spec.ts index 878de35501..271a898715 100644 --- a/packages/experimental/forge-github/tests/compare.spec.ts +++ b/packages/experimental/forge-github/tests/compare.spec.ts @@ -21,6 +21,20 @@ describe('compare read', () => { ]) }) + it('repeats a read that an older gh rejects for the escape option without that option, and no other failure', async () => { + const calls: (readonly string[])[] = [] + const answers: (string | ForgeFailure)[] = [ + { code: 'unavailable', message: 'unknown flag: --allow-escape-sequences' }, 'diff --git a/x b/x\n', + { code: 'unavailable', message: 'Server Error' }, + ] + const read = async (args: readonly string[]) => { calls.push(args); return answers.shift()! } + + await expect(readComparison(read, demo, base, head, signal)).resolves.toBe('diff --git a/x b/x\n') + expect(calls[1]).toEqual(['api', '--hostname', 'github.com', '-H', 'Accept: application/vnd.github.diff', `repos/octo/demo/compare/${base}...${head}`]) + await expect(readComparison(read, demo, base, head, signal)).resolves.toEqual({ code: 'unavailable', message: 'Server Error' }) + expect(calls).toHaveLength(3) + }) + it.each([['base', 'main', head], ['head', base, 'HEAD']])('refuses a %s that is not a full commit object name before reading', async (_label, from, to) => { const calls: (readonly string[])[] = [] await expect(readComparison(async (args) => { calls.push(args); return '' }, demo, from, to, signal)) diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index 4ffe4e411f..38fa865e7e 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -144,6 +144,20 @@ describe('GitHub provider fetch', () => { } }) + it('counts review thread pages toward the byte budget of a complete detail read, but not of polling', async () => { + const first = output({ data: { r0: { p0: pullRequestNode(1, { reviewThreads: threadPage([true], 'threads-1') }) } } }) + const page = output({ data: { node: { reviewThreads: threadPage([false, false]) } } }) + const total = Buffer.byteLength(first.stdout) + Buffer.byteLength(page.stdout) + for (const limit of [total, total - 1]) { + const gh = fakeGh(args => args.includes(`query=${THREADS_QUERY}`) ? page : first) + const subject = new GitHubProvider(gh.run, ['github.com'], { ...limits, maxOutputBytes: limit }) + const result = await subject.fetchChecks(pull(1), signal) + if (limit === total) expect(result).toMatchObject({ unresolvedThreads: 2, threadsTruncated: false }) + else expect(result).toEqual({ code: 'too-large', message: 'GitHub check details exceed the output size limit' }) + expect((await subject.fetch([pull(1)], signal)).get(changeRequestKey(pull(1)))).toMatchObject({ unresolvedThreads: 2 }) + } + }) + it('reads past 100 historical runs from the pinned rollup and counts only the latest run', async () => { const gh = fakeGh(args => output(args.includes('id=fixed-rollup') ? { data: { node: { contexts: { pageInfo: { hasNextPage: false, endCursor: null }, nodes: [ @@ -456,6 +470,16 @@ describe('GitHub provider reads', () => { expect(gh.calls).toHaveLength(1) }) + it('reads the diff with a gh older than 2.97, which rejects the escape option, by repeating the read without it', async () => { + // What gh 2.96.0 prints for an option it does not know. + const gh = pinned(undefined, args => args.includes('--allow-escape-sequences') + ? output('', 1, 'unknown flag: --allow-escape-sequences\n\nUsage: gh api [flags]\n') + : output('diff --git a/x b/x\n')) + + await expect(provider(gh.run).diff(pull(7), head, signal)).resolves.toBe('diff --git a/x b/x\n') + expect(gh.calls.map(call => call.includes('--allow-escape-sequences'))).toEqual([false, true, false]) + }) + it('refuses a head that is not a full commit object name before starting gh', async () => { const gh = pinned() diff --git a/packages/experimental/forge/README.i18n.yaml b/packages/experimental/forge/README.i18n.yaml index a60d0a4d78..7e6bbba230 100644 --- a/packages/experimental/forge/README.i18n.yaml +++ b/packages/experimental/forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge/use-this-package: - en: 897de781e679f5f2 - zh: 3d0c589742a4dac0 + en: e51a2f965613ecaf + zh: 609baadb4bb090e4 /deepseek-ai-dsh-experimental-forge/understand-the-implementation: en: e193cb547c47069b zh: faa517522402ea41 diff --git a/packages/experimental/forge/README.md b/packages/experimental/forge/README.md index e04f46a256..368eab3c2f 100644 --- a/packages/experimental/forge/README.md +++ b/packages/experimental/forge/README.md @@ -36,7 +36,7 @@ Mount the registry with at least one provider package, such as the GitHub provid `markReady(ref, signal)` marks a draft ready for review, and `merge(ref, { method, headSha }, signal)` merges a change request only while its head is still `headSha`. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to undefined once the host accepted the change or to a `ForgeActionFailure`: `unauthenticated`, `stale` when the head moved past `headSha`, or `failed` with the host's reason. After either settles, a watched change request is polled at once. Snapshots carry `mergeReady`, whether the host would merge the change request now for the signed-in user, and `mergeMethods`, the methods the repository accepts with that user's usual one first. -`diff(ref, headSha, signal)` reads the change request's unified patch at head commit `headSha` as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. A provider returns a patch only when it describes `headSha`; once the head is another commit, `diff` resolves to `stale`, and a watched change request is polled at once so its next status names the current head. Snapshots carry `unresolvedThreads` with `threadsTruncated`, which marks the count as a lower bound when the provider counted only some review threads. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. +`diff(ref, headSha, signal)` reads the change request's unified patch at head commit `headSha` as the host computes it, with `a/` and `b/` path prefixes, and `fileText(ref, commit, path, signal)` reads one file of its repository at a commit. Both delegate to the provider of the reference's forge, throw when none is registered, and resolve to the text or to a `ForgeFailure`, which is `too-large` when the host or the provider refuses an answer over its size limit. A provider returns a patch only when it describes `headSha`; once the head is another commit, `diff` resolves to `stale`. The first stale read at a head commit polls a watched change request at once so its next status names the current head; later stale reads at that commit wait for the regular poll, which bounds reads while the host's answers briefly disagree. Snapshots carry `unresolvedThreads` with `threadsTruncated`, which marks the count as a lower bound when the provider counted only some review threads. `fileUrl(ref, commit, path)` returns the web page of that file at that commit. `fetchChecks(ref, signal)` reads one change request’s complete checks on demand. It has its own `fetchTimeoutMs` deadline and does not occupy the polling batch or publish to its watchers. Failure leaves previously polled snapshots intact. A provider without `fetchChecks` returns `unavailable`. Caller cancellation and provider or service disposal abort the read; disposal waits for it to settle. diff --git a/packages/experimental/forge/README.zh.md b/packages/experimental/forge/README.zh.md index 9e61402f5b..b992ef1f4d 100644 --- a/packages/experimental/forge/README.zh.md +++ b/packages/experimental/forge/README.zh.md @@ -36,7 +36,7 @@ kind: "package-reference" `markReady(ref, signal)` 把草稿标记为可评审;`merge(ref, { method, headSha }, signal)` 只在 head 仍是 `headSha` 时合并变更请求。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错;主机接受时 resolve 为 undefined,否则为 `ForgeActionFailure`:`unauthenticated`、head 已越过 `headSha` 时的 `stale`,或带主机原因的 `failed`。两者结束后,被监听的变更请求会立即重新轮询。快照带有 `mergeReady`(主机现在是否会为已登录用户合并该变更请求)与 `mergeMethods`(仓库接受的合并方式,该用户常用的方式排在最前)。 -`diff(ref, headSha, signal)` 读取托管平台计算出的变更请求在 head 提交 `headSha` 处的统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。提供方只在补丁描述 `headSha` 时返回补丁;head 已是其他提交时,`diff` resolve 为 `stale`,被 watch 的变更请求随即重新轮询,使下一次状态给出当前 head。快照携带 `unresolvedThreads` 与 `threadsTruncated`;提供方只统计了部分评审讨论时,后者表示该计数只是下限。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 +`diff(ref, headSha, signal)` 读取托管平台计算出的变更请求在 head 提交 `headSha` 处的统一补丁,路径带 `a/` 与 `b/` 前缀;`fileText(ref, commit, path, signal)` 读取其仓库中某个提交下的一个文件。两者都委托给引用所属 forge 的提供方,没有注册提供方时抛错,resolve 为文本或 `ForgeFailure`;托管平台或提供方因结果超过其大小上限而拒绝时,失败为 `too-large`。提供方只在补丁描述 `headSha` 时返回补丁;head 已是其他提交时,`diff` resolve 为 `stale`。同一 head 提交的第一次 stale 读取会让被 watch 的变更请求立即重新轮询,使下一次状态给出当前 head;之后在该提交上的 stale 读取等待常规轮询,从而在托管平台的应答短暂不一致时限制读取次数。快照携带 `unresolvedThreads` 与 `threadsTruncated`;提供方只统计了部分评审讨论时,后者表示该计数只是下限。`fileUrl(ref, commit, path)` 返回该文件在该提交下的网页地址。 `fetchChecks(ref, signal)` 按需读取单个变更请求的完整检查,使用独立的 `fetchTimeoutMs` 时限,不占用轮询批次,也不向其监听方发布结果。读取失败时保留已有轮询快照。提供方未实现 `fetchChecks` 时返回 `unavailable`。调用方取消、提供方或服务销毁都会中止读取;销毁会等待读取结束。 diff --git a/packages/experimental/forge/src/index.ts b/packages/experimental/forge/src/index.ts index df05ef9796..24e403b460 100644 --- a/packages/experimental/forge/src/index.ts +++ b/packages/experimental/forge/src/index.ts @@ -44,6 +44,8 @@ interface Watch { /** Epoch milliseconds of the next poll; undefined while in flight or after a terminal state. */ dueAt: number | undefined failures: number + /** Head commit whose `stale` diff read last polled at once, so further stale reads at it wait for the regular poll. */ + staleHead: string | undefined } /** @@ -237,8 +239,10 @@ export class ForgeService extends Service { /** * Read the changes of a change request at one head commit as its host - * computes them. A `stale` failure polls the change request again at once - * when it is watched, so its next status names the current head. + * computes them. The first `stale` failure at a head commit polls a watched + * change request again at once, so its next status names the current head; + * later stale reads at the same commit wait for the regular poll, which + * bounds the reads while the host's answers disagree. * @param ref - change request served by a registered provider. * @param headSha - head commit the patch must describe, usually the head of the latest status. * @param signal - cancellation of the read. @@ -248,7 +252,11 @@ export class ForgeService extends Service { async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise { const result = await this.invoke(this.registration(ref.repository.forge), signal, (provider, operation) => provider.diff(ref, headSha, operation)) - if (typeof result !== 'string' && result.code === 'stale') this.refresh(ref) + const watch = this.watches.get(changeRequestKey(ref)) + if (typeof result !== 'string' && result.code === 'stale' && watch !== undefined && watch.staleHead !== headSha) { + watch.staleHead = headSha + this.refresh(ref) + } return result } @@ -307,7 +315,7 @@ export class ForgeService extends Service { const dispose = this.ctx.effect(() => { let watch = this.watches.get(key) if (watch === undefined) { - watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0 } + watch = { key, ref, listeners: new Set(), latest: undefined, dueAt: Date.now(), failures: 0, staleHead: undefined } this.watches.set(key, watch) this.schedule() } diff --git a/packages/experimental/forge/tests/watch.spec.ts b/packages/experimental/forge/tests/watch.spec.ts index 2685e0d904..4537d82670 100644 --- a/packages/experimental/forge/tests/watch.spec.ts +++ b/packages/experimental/forge/tests/watch.spec.ts @@ -244,6 +244,28 @@ describe('forge watch', () => { expect(provider.fetches).toHaveLength(2) }) + it('polls at once only for the first stale diff read at a head, leaving later ones to the regular cadence', async () => { + const provider = new FakeProvider() + provider.results.set(key, snapshot(ref(1))) + const context = await setup(provider) + collect(context) + await vi.advanceTimersByTimeAsync(0) + const signal = new AbortController().signal + provider.readResult = { code: 'stale', message: 'the head moved' } + + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + await context.forge.diff(ref(1), 'a'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(2) + await vi.advanceTimersByTimeAsync(config.idleIntervalMs) + expect(provider.fetches).toHaveLength(3) + + await context.forge.diff(ref(1), 'b'.repeat(40), signal) + await vi.advanceTimersByTimeAsync(0) + expect(provider.fetches).toHaveLength(4) + }) + it('coalesces refreshes during a fetch into one immediate subsequent fetch', async () => { const provider = new FakeProvider() const release = held(provider, target => snapshot(target)) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index f5771a8141..3d3e0ff983 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1247,7 +1247,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, { signature: 'async diff(ref: ChangeRequestRef, headSha: string, signal: AbortSignal): Promise', - description: 'Read the changes of a change request at one head commit as its host computes them. A `stale` failure polls the change request again at once when it is watched, so its next status names the current head.', + description: 'Read the changes of a change request at one head commit as its host computes them. The first `stale` failure at a head commit polls a watched change request again at once, so its next status names the current head; later stale reads at the same commit wait for the regular poll, which bounds the reads while the host\'s answers disagree.', parameters: [{ name: 'ref', description: 'change request served by a registered provider.' }, { name: 'headSha', description: 'head commit the patch must describe, usually the head of the latest status.' }, { name: 'signal', description: 'cancellation of the read.' }], returns: 'one unified patch with `a/` and `b/` path prefixes, or why the host did not provide it at `headSha`.', throws: ['when no provider serves the change request\'s forge, or with `signal.reason` when it aborts.'], From c9997e03c7131c1e38c5f6bd94992ebfcd6a428a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 18:18:51 +0800 Subject: [PATCH 064/103] fix(forge): read commit ranges like the pinned pull request diff The compare read now takes the same arguments as the comparison helper of the pinned-diff change: explicit commits, the diff media type, and --allow-escape-sequences, which gh 2.97 and newer requires to print a patch whose files hold terminal escape sequences. HTTP 406, GitHub's refusal to render a diff over its limits, reads as too-large. --- apps/web/tests/forge-panel.e2e.ts | 6 +-- .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 2 +- .../experimental/forge-github/README.zh.md | 2 +- .../experimental/forge-github/src/provider.ts | 43 +++++++++++++++---- .../forge-github/tests/provider.spec.ts | 6 ++- 6 files changed, 46 insertions(+), 17 deletions(-) diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 9335003dc1..185dadb433 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -97,8 +97,8 @@ if (args[0] === 'pr' && args[1] === 'diff') { await new Promise(resolve => process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8'), resolve)) process.exit(0) } -if (args[0] === 'api' && args[3] === '-H' && args[4] === 'Accept: application/vnd.github.diff') { - const range = args[5].slice('repos/octo/demo/compare/'.length) +if (args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')) { + const range = args.at(-1).slice('repos/octo/demo/compare/'.length) const patch = existsSync(join(here, 'compare.json')) ? JSON.parse(readFileSync(join(here, 'compare.json'), 'utf8'))[range] : undefined if (patch === undefined) { process.stderr.write('gh: Not Found (HTTP 404)\\n') @@ -1744,7 +1744,7 @@ it.skipIf(MODE === 'record')('reviews a change request by layer, hides test file await expect.poll(() => shownPaths(view), { timeout: 20_000 }).toEqual(['docs/schema.json', 'locale/zh.json', 'src/panel.spec.ts', 'package.json']) await expect.poll(() => lens.getByRole('radio').allTextContents()).toEqual(['全部4', '接口1', '实现0', '测试3']) const calls = (await readFile(join(root, 'calls.jsonl'), 'utf8')).split('\n').filter(line => line.length > 0).map(line => JSON.parse(line) as string[]) - expect(calls.filter(args => args[0] === 'api' && args[4] === 'Accept: application/vnd.github.diff').map(args => args[5])).toEqual([ + expect(calls.filter(args => args[0] === 'api' && args.includes('Accept: application/vnd.github.diff')).map(args => args.at(-1))).toEqual([ `repos/octo/demo/compare/${'1'.repeat(40)}...${'2'.repeat(40)}`, `repos/octo/demo/compare/${'1'.repeat(40)}...${HEAD7}`, ]) await view.getByRole('button', { name: `查看的提交:2222222…${HEAD7.slice(0, 7)}`, exact: true }).click() diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index fec538644d..1924431ee6 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: 282129be7093ee26 - zh: ff1eeeb907a46245 + en: 63285a5e2f7b6085 + zh: c5114f7c5d06879f /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: 90f3c10096be642a zh: 4e1b663c52019ac2 diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index f392b899a0..56913f0c24 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -44,7 +44,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos///compare/...` with the diff media type, accepting only full commits, and fails like `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` runs `gh pr diff --repo // --color never`. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads `repos///compare/...` with the diff media type and `--allow-escape-sequences`, which `gh` 2.97 and newer requires to print a patch whose files hold terminal escape sequences; it accepts only full commits and fails like `diff`, with HTTP 406, GitHub's refusal to render a diff over its limits, as `too-large`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's `too_large` error, which a diff over its own size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index da6995e916..c908a24423 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -44,7 +44,7 @@ kind: "package-reference" pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型读取 `repos///compare/...`,只接受完整提交,失败时与 `diff` 相同。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 运行 `gh pr diff --repo // --color never`。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 以 diff 媒体类型并带 `--allow-escape-sequences` 读取 `repos///compare/...`(文件中含终端转义序列时,`gh` 2.97 及更新版本需要该参数才会输出补丁);只接受完整提交,失败时与 `diff` 相同,其中 HTTP 406(GitHub 拒绝渲染超出上限的 diff)返回 `too-large`。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 报告 `too_large` 错误时(diff 超过其自身大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index c73a174f72..0ce13c9923 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -24,6 +24,9 @@ const HTTP_STATUS = /\(HTTP (\d{3})\)/ */ const TOO_LARGE = /\btoo_large\b/ +/** HTTP status GitHub answers when it refuses to render a diff over its limits. */ +const NOT_ACCEPTABLE = '406' + /** A full SHA-1 or SHA-256 object name. */ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i @@ -177,15 +180,9 @@ export class GitHubProvider implements ForgeProvider { /** Read the changes between two commits through the compare API in its diff form. */ async compare(ref: ChangeRequestRef, base: string, head: string, signal: AbortSignal): Promise { - const { host, owner, name } = checkedRepository(ref) - const failure = this.hostFailure(host) + const failure = this.hostFailure(checkedRepository(ref).host) if (failure !== undefined) return failure - for (const commit of [base, head]) { - if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) - } - return await this.read([ - 'api', '--hostname', host, '-H', 'Accept: application/vnd.github.diff', `repos/${owner}/${name}/compare/${base}...${head}`, - ], signal) + return await readComparison(async (args, operation) => await this.read(args, operation), ref.repository, base, head, signal) } fileUrl(ref: ChangeRequestRef, commit: string, path: string): string { @@ -223,7 +220,7 @@ export class GitHubProvider implements ForgeProvider { if (output.exitCode === 0) return output.stdout const { message, status } = refusal(output) if (AUTHENTICATION.test(output.stderr)) return { code: 'unauthenticated', message } - if (TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message } + if (status === NOT_ACCEPTABLE || TOO_LARGE.test(output.stderr) || TOO_LARGE.test(output.stdout)) return { code: 'too-large', message } return { code: status === '404' || /could not resolve to a pullrequest/i.test(output.stderr) ? 'not-found' : 'unavailable', message } } @@ -343,3 +340,31 @@ function parseJson(text: string): unknown { function firstLine(text: string): string | undefined { return text.split('\n').map(line => line.trim()).find(line => line.length > 0) } + +/** Runs one reading `gh` command and maps a refusal to a failure, as the provider's reads do. */ +type GhTextReader = (args: readonly string[], signal: AbortSignal) => Promise + +/** + * Read the unified patch from the merge base of `base` and `head` to `head` through the REST compare endpoint. + * Both ends are commit object names, so the answer never follows a moving branch. The patch keeps terminal escape + * sequences that file contents hold; `gh` 2.97 and newer refuses to print them without `--allow-escape-sequences`. + * @param read - runs `gh` with the provider's output limit and failure mapping. + * @param repository - repository that holds both commits, with an owner and name already checked for inlining. + * @param base - commit whose merge base with `head` starts the patch. + * @param head - commit the patch ends at. + * @param signal - cancellation of the read. + * @returns the patch with `a/` and `b/` path prefixes, or why GitHub did not provide it. + * @throws when `base` or `head` is not a full commit object name. + */ +async function readComparison( + read: GhTextReader, repository: ForgeRepository, base: string, head: string, signal: AbortSignal, +): Promise { + for (const commit of [base, head]) { + if (!COMMIT.test(commit)) throw new Error(`forge-github: invalid commit ${JSON.stringify(commit)}`) + } + const { host, owner, name } = repository + return await read([ + 'api', '--hostname', host, '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', + `repos/${owner}/${name}/compare/${base}...${head}`, + ], signal) +} diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index 2433e580f7..2bce7cf2b8 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -478,8 +478,12 @@ describe('GitHub provider commits', () => { await expect(provider(gh.run).compare(pull(7, enterprise), sha(1), sha(3), signal)).resolves.toBe('diff --git a/x b/x\n') expect(gh.calls).toEqual([[ - 'api', '--hostname', 'ghe.corp.example', '-H', 'Accept: application/vnd.github.diff', `repos/team/svc/compare/${sha(1)}...${sha(3)}`, + 'api', '--hostname', 'ghe.corp.example', '--allow-escape-sequences', '-H', 'Accept: application/vnd.github.diff', + `repos/team/svc/compare/${sha(1)}...${sha(3)}`, ]]) + const refused = 'gh: Sorry, this diff is taking too long to generate. (HTTP 406)' + await expect(provider(fakeGh(() => output({ message: 'Sorry, this diff is taking too long to generate.' }, 1, refused)).run) + .compare(pull(7), sha(1), sha(3), signal)).resolves.toEqual({ code: 'too-large', message: 'Sorry, this diff is taking too long to generate.' }) await expect(provider(gh.run).compare(pull(7), 'main', sha(3), signal)).rejects.toThrow('forge-github: invalid commit "main"') await expect(provider(gh.run).compare(pull(7), sha(1), 'HEAD~1', signal)).rejects.toThrow('forge-github: invalid commit "HEAD~1"') }) From 0e971200c4769fde1e9dcfdec3df1f2845e50be8 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Fri, 6 Nov 2026 18:47:22 +0800 Subject: [PATCH 065/103] feat(forge-panel): let repositories declare review layers in .gitattributes A repository's root .gitattributes now decides a file's review layer first: dsh-review-layer names test, interface, or implementation, and linguist-generated still places a file in the test layer. The testPaths and interfacePaths settings add globs before the built-in rules and are empty by default. The built-in rules follow the default conventions of common languages and tools instead of treating every JSON or YAML file and every name containing config as interface. This repository declares its own locale dictionaries, snapshot tree, pairing records, and types modules. --- .gitattributes | 9 ++ apps/web/tests/forge-panel.e2e.ts | 7 +- docs/config-catalog.md | 11 +- docs/config-catalog.zh.md | 11 +- docs/subsystems/forge.md | 5 +- docs/subsystems/forge.zh.md | 5 +- .../client-ui-forge/README.i18n.yaml | 12 +- .../experimental/client-ui-forge/README.md | 6 +- .../experimental/client-ui-forge/README.zh.md | 6 +- .../experimental/client-ui-forge/src/index.ts | 24 +--- .../client-ui-forge/src/layers.ts | 131 ++++++++++++++---- .../experimental/client-ui-forge/src/types.ts | 14 +- .../client-ui-forge/tests/layers.host.spec.ts | 124 ++++++++++++----- 13 files changed, 246 insertions(+), 119 deletions(-) diff --git a/.gitattributes b/.gitattributes index 2bead994d2..f6b77ce2c7 100644 --- a/.gitattributes +++ b/.gitattributes @@ -16,3 +16,12 @@ docs/persistence-changes/historical-formats/*.schema.json linguist-generated=tru # Unified patch blank context lines require their leading space. patches/*.patch whitespace=-blank-at-eol + +# Review layers of the forge changes view (dsh-review-layer), for this repository's own conventions: +# plugin locale dictionaries and the session snapshot tree hide with test files, generated bilingual +# pairing records join them, and a package's types-only module is part of its interface. +packages/*/*/locale/*.json dsh-review-layer=test +locales.ts dsh-review-layer=test +snapshots/** dsh-review-layer=test +*.i18n.yaml dsh-review-layer=test +packages/*/*/src/types.ts dsh-review-layer=interface diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 185dadb433..b93d450439 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -253,7 +253,8 @@ const REVIEW_SECTIONS = { /** * Pull request 7 with review layers: `src/panel.ts` and `docs/panel.md` are implementation, `package.json` is - * interface, and the spec, the locale dictionary, and `docs/schema.json`, which `.gitattributes` marks generated, are tests. + * interface, and the spec, the locale dictionary, which `.gitattributes` places in the test layer, and + * `docs/schema.json`, which it marks generated, are tests. */ const REVIEW_DIFF = [PR7_DIFF.trimEnd(), ...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n') @@ -266,7 +267,9 @@ async function writeReviewFixture(root: string): Promise { [`${'1'.repeat(40)}...${HEAD7}`]: [...REVIEW_SECTIONS.test, ...REVIEW_SECTIONS.schema, ''].join('\n'), })) const contents = JSON.parse(await readFile(join(root, 'contents.json'), 'utf8')) as Record - for (const commit of ['2'.repeat(40), HEAD7]) contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\n' + for (const commit of ['2'.repeat(40), HEAD7]) { + contents[`.gitattributes@${commit}`] = 'docs/schema.json linguist-generated\nlocale/*.json dsh-review-layer=test\n' + } await writeFile(join(root, 'contents.json'), JSON.stringify(contents)) } diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f704600604..5ab8b1ec10 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1065,7 +1065,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:374`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1096,11 +1096,14 @@ export interface Config { /** Most commits of the `branch` scope listed, oldest first. */ maxCommits?: number /** - * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with - * dot files included; their files form the `test` layer, which the changes view can hide. + * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before + * them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both. */ testPaths?: string[] - /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + /** + * Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after + * `testPaths` and before the built-in rules. + */ interfacePaths?: string[] } ``` diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index d9153f34fe..7bbff56f64 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1067,7 +1067,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:373`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:374`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1098,11 +1098,14 @@ export interface Config { /** Most commits of the `branch` scope listed, oldest first. */ maxCommits?: number /** - * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with - * dot files included; their files form the `test` layer, which the changes view can hide. + * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before + * them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both. */ testPaths?: string[] - /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + /** + * Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after + * `testPaths` and before the built-in rules. + */ interfacePaths?: string[] } ``` diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 4f4febadfe..281e069484 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -696,8 +696,9 @@ type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ```ts type-equiv /** - * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root - * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + * Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else + * `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in + * test and interface rules that the path matches, else `implementation`. */ type ForgeFileLayer = 'interface' | 'implementation' | 'test' ``` diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index e731e65c23..a6e9407bbc 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -696,8 +696,9 @@ type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' ```ts type-equiv /** - * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root - * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + * Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else + * `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in + * test and interface rules that the path matches, else `implementation`. */ type ForgeFileLayer = 'interface' | 'implementation' | 'test' ``` diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 445e3f73db..1c9d1c7079 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: dcde9f0c7c82ab08 - zh: 77a570133b45dbd9 + en: 670c60932708dbb1 + zh: 794bc60f93042c3f /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 1c8c6cfa6ad4b906 - zh: 15a0beb677f6e0fd + en: f255ad3fc3316e7b + zh: 1c4960a92141d6db /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 51f6e22d3f2b7d03 - zh: 252f1ba8b2941b60 + en: 2f96a33996a89344 + zh: a3ed868a4c2747c9 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index a24de40f12..a005301d81 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -40,7 +40,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. - **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff over 300 files, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. -- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. A file is in Tests when its path matches `testPaths` or the repository's root `.gitattributes` marks it `linguist-generated`, else in Interface when its path matches `interfacePaths`, such as package manifests, configuration, and type declarations, else in Implementation. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first; a click shows one commit and a Shift click the commits from the last one clicked; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and a chosen commit that is gone offers Show all commits. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first; a click shows one commit and a Shift click the commits from the last one clicked; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and a chosen commit that is gone offers Show all commits. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. @@ -69,7 +69,7 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, and hunks, plus the blob names of a binary change or the content of an untracked binary file, and a layer from picomatch matches of `testPaths` and `interfacePaths`, with dot files included, and from the `linguist-generated` lines of the root `.gitattributes`: the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point with `log --topo-order --reverse`, at most `maxCommits`. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, and hunks, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point with `log --topo-order --reverse`, at most `maxCommits`. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. @@ -140,7 +140,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Very many branches** — the base branch menu reads every ref before it filters, so a search can reach any branch. Refs over `maxDiffBytes`, about 165,000 at the default, or a listing over `gitTimeoutMs`, leave the menu saying that branches could not be read; Default keeps working. - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. -- **Review layers** — the Interface layer follows path globs only and keeps whole files; finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. +- **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. - **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, 250 for GitHub, and a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index cdeaac4ac9..dcfef23609 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -40,7 +40,7 @@ kind: "package-reference" - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 -- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。路径匹配 `testPaths` 或被仓库根目录 `.gitattributes` 标为 `linguist-generated` 的文件属于“测试”;否则路径匹配 `interfacePaths`(例如包清单、配置与类型声明)的文件属于“接口”;其余属于“实现”。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在时提供“查看全部提交”。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在时提供“查看全部提交”。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -69,7 +69,7 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态与 hunk 组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并用 picomatch(包含点文件)匹配 `testPaths` 与 `interfacePaths`、读取根目录 `.gitattributes` 中的 `linguist-generated` 行来确定分层:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --topo-order --reverse` 列出分叉点之后的提交,最多 `maxCommits` 个。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态与 hunk 组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --topo-order --reverse` 列出分叉点之后的提交,最多 `maxCommits` 个。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 @@ -140,7 +140,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **分支极多**——基准分支菜单在筛选前读取全部引用,这样搜索才能找到任意分支。引用超过 `maxDiffBytes`(默认约 165,000 个)或列出时间超过 `gitTimeoutMs` 时,菜单提示无法读取分支;“默认”仍可使用。 - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 -- **分层**——“接口”层只按路径 glob 划分并保留整个文件;找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 +- **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 - **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为 250 个),每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index c1679818d2..27e1621b84 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -49,26 +49,6 @@ declare module '@deepseek-ai/cordis' { /** Panel limits plus the branch and commit listing limits and the worktree branch prefix. */ type ControllerConfig = PanelConfig & { readonly maxBranches: number; readonly maxCommits: number; readonly worktreePrefix: string } -/** - * Tests, test data, snapshots, locale dictionaries, and lockfiles, after the review plugin's collapsed and - * non-interface paths; `locales.ts` is the typed dictionary module of a DSH Client plugin. - */ -const TEST_PATHS = [ - '**/test/**', '**/tests/**', '**/__tests__/**', '**/__mocks__/**', '**/__fixtures__/**', '**/e2e/**', - '**/*.spec.*', '**/*.test.*', '**/*.e2e.*', - '**/__snapshots__/**', 'snapshots/**', '**/*.snap', - '**/locale/*.json', '**/locales/**', '**/locales.ts', - '**/pnpm-lock.yaml', '**/package-lock.json', '**/npm-shrinkwrap.json', '**/yarn.lock', -] as const - -/** Package manifests, type declarations, and configuration by extension, name, or directory, after the review plugin's scanner. */ -const INTERFACE_PATHS = [ - '**/package.json', '**/*.d.ts', '**/*.d.mts', '**/*.d.cts', '**/types.ts', - '**/*.{json,jsonc,yaml,yml,toml,ini,conf,cfg,properties,xml,plist}', - '**/.env', '**/.env.*', '**/.*rc', '**/.*rc.*', '**/*{config,settings,preferences,options}*', - '**/{config,configs,settings,profiles}/**', -] as const - /** * Serves the forge panel. Following a Session inspects the checkout of its * current directory using the Session's permissions and execution world, recognizes the @@ -101,8 +81,8 @@ export class ForgePanelController extends TypertRemoteService { maxUntrackedFiles: z.number().default(100), maxCachedDiffBytes: z.number().default(16_777_216), maxCommits: z.number().default(250), - testPaths: z.array(z.string()).default([...TEST_PATHS]), - interfacePaths: z.array(z.string()).default([...INTERFACE_PATHS]), + testPaths: z.array(z.string()).default([]), + interfacePaths: z.array(z.string()).default([]), }) private readonly home: Context diff --git a/packages/experimental/client-ui-forge/src/layers.ts b/packages/experimental/client-ui-forge/src/layers.ts index 827bbf4269..c7ea40940e 100644 --- a/packages/experimental/client-ui-forge/src/layers.ts +++ b/packages/experimental/client-ui-forge/src/layers.ts @@ -1,6 +1,8 @@ /** - * Review layers of changed files: the `testPaths` and `interfacePaths` globs of the panel's configuration, and the - * `linguist-generated` attribute of a repository's root `.gitattributes`, which also places a file in the `test` layer. + * Review layers of changed files. A repository's root `.gitattributes` decides first: its `dsh-review-layer` + * attribute names a layer, and `linguist-generated` places a file in the `test` layer. The panel's `testPaths` and + * `interfacePaths` configuration comes next, then the built-in rules, which follow the default file and directory + * conventions of common languages and tools; every other file is in the `implementation` layer. */ import picomatch from 'picomatch' @@ -10,11 +12,61 @@ import type { ForgeDiffFile, ForgeFileLayer } from './types.ts' /** Path of the attributes file read beside each diff, relative to the repository root. */ export const ATTRIBUTES_PATH = '.gitattributes' +/** The attribute a repository sets to a layer name to place files in that layer. */ +export const LAYER_ATTRIBUTE = 'dsh-review-layer' + /** The attribute GitHub Linguist reads to treat a file as generated. */ const GENERATED = 'linguist-generated' +const LAYERS: ReadonlySet = new Set(['interface', 'implementation', 'test']) + +/** Whether an attribute value names a layer. */ +function isLayer(value: string): value is ForgeFileLayer { + return LAYERS.has(value) +} + +/** + * Tests, test data, snapshots, locale dictionaries, and lockfiles by the default conventions of their tools: test + * directories, Jest and Vitest `*.spec.*` and `*.test.*` files, `go test` `*_test.go` files and `testdata/` + * directories, pytest's `test_*.py`, `*_test.py`, and `conftest.py`, RSpec's `spec/` and `*_spec.rb`, SwiftPM's + * `Tests/`, .NET `*.Tests/` projects, Jest and insta snapshots, i18next and Rails `locales/`, gettext catalogs, + * Apple `.lproj` strings, Android string resources, and the lockfiles of npm, pnpm, Yarn, Bun, Cargo, Go modules, + * Poetry, uv, Pipenv, Bundler, Composer, SwiftPM, NuGet, Gradle, pub, Mix, and Nix flakes. + */ +export const BUILT_IN_TEST_PATHS: readonly string[] = [ + '**/test/**', '**/tests/**', '**/Tests/**', '**/__tests__/**', '**/spec/**', '**/e2e/**', '**/testdata/**', '**/__mocks__/**', + '**/__fixtures__/**', '**/*.Tests/**', + '**/*.spec.*', '**/*.test.*', '**/*.e2e.*', '**/*_test.go', '**/test_*.py', '**/*_test.py', '**/conftest.py', '**/*_spec.rb', + '**/__snapshots__/**', '**/*.snap', + '**/locales/**', '**/*.po', '**/*.pot', '**/*.lproj/*.strings', '**/res/values-*/strings.xml', + '**/package-lock.json', '**/npm-shrinkwrap.json', '**/pnpm-lock.yaml', '**/yarn.lock', '**/bun.lock', '**/bun.lockb', '**/Cargo.lock', + '**/go.sum', '**/poetry.lock', '**/uv.lock', '**/Pipfile.lock', '**/Gemfile.lock', '**/composer.lock', '**/Package.resolved', + '**/packages.lock.json', '**/gradle.lockfile', '**/pubspec.lock', '**/mix.lock', '**/flake.lock', +] + +/** + * Package manifests of npm, Go modules, Cargo, Python packaging, Bundler and RubyGems, Maven, Gradle, MSBuild, + * SwiftPM, Composer, pub, and Mix; TypeScript declarations, Python stubs, and C and C++ headers; and interface + * definitions of Protocol Buffers, GraphQL, Thrift, and OpenAPI. + */ +export const BUILT_IN_INTERFACE_PATHS: readonly string[] = [ + '**/package.json', '**/go.mod', '**/Cargo.toml', '**/pyproject.toml', '**/setup.py', '**/setup.cfg', '**/Gemfile', '**/*.gemspec', + '**/pom.xml', '**/build.gradle', '**/build.gradle.kts', '**/*.csproj', '**/Package.swift', '**/composer.json', '**/pubspec.yaml', + '**/mix.exs', + '**/*.d.ts', '**/*.d.mts', '**/*.d.cts', '**/*.pyi', '**/*.h', '**/*.hpp', + '**/*.proto', '**/*.graphql', '**/*.graphqls', '**/*.thrift', '**/openapi.{json,yaml,yml}', '**/swagger.{json,yaml,yml}', +] + type Matcher = (path: string) => boolean +/** What a repository's attributes say about one path. */ +interface PathAttributes { + /** The layer `dsh-review-layer` names, or undefined while it is unspecified. */ + readonly layer: ForgeFileLayer | undefined + /** Whether `linguist-generated` is set. */ + readonly generated: boolean +} + /** * Compile globs into one matcher; `*` matches dot files and never crosses `/`. * @param globs - picomatch globs. @@ -25,63 +77,84 @@ function matcherOf(globs: readonly string[]): Matcher { } /** - * Read which paths a `.gitattributes` text marks `linguist-generated`. Lines apply in order, so a later line overrides - * an earlier one; `linguist-generated` and `=true` set the attribute, `-linguist-generated` and `=false` unset it, and - * `!linguist-generated` returns it to unspecified. A pattern without `/` matches a file name at any depth, and one with - * `/` matches from the repository root. Macro definitions, quoted patterns, and patterns ending in `/`, which name - * directories and so never match a file, are skipped. + * Read the review attributes a `.gitattributes` text gives each path. Lines apply in order, so a later line overrides + * an earlier one. `dsh-review-layer=` names `test`, `interface`, or `implementation`; another value, + * `-dsh-review-layer`, and `!dsh-review-layer` leave the layer unspecified. `linguist-generated` and `=true` set + * the generated attribute, `-linguist-generated` and `=false` unset it, and `!linguist-generated` returns it to + * unspecified. A pattern without `/` matches a file name at any depth, and one with `/` matches from the repository + * root. Macro definitions, quoted patterns, and patterns ending in `/`, which name directories and so never match a + * file, are skipped. * @param attributes - the text of the root `.gitattributes`, empty without one. - * @returns whether a repository-relative path is generated. + * @returns the attributes of a repository-relative path. */ -export function generatedMatcher(attributes: string): Matcher { - const rules: { readonly match: Matcher; readonly generated: boolean | undefined }[] = [] +export function attributesOf(attributes: string): (path: string) => PathAttributes { + // `undefined` leaves an attribute as earlier lines set it, and `null` returns it to unspecified. + const rules: { + readonly match: Matcher + readonly layer: ForgeFileLayer | null | undefined + readonly generated: boolean | null | undefined + }[] = [] for (const raw of attributes.split(/\r?\n/)) { const [pattern, ...fields] = raw.trim().split(/\s+/) if (pattern === undefined || pattern === '' || pattern.startsWith('#') || pattern.startsWith('[attr]') || pattern.startsWith('"') || pattern.endsWith('/')) continue - let generated: boolean | null | undefined = null + let layer: ForgeFileLayer | null | undefined + let generated: boolean | null | undefined for (const field of fields) { if (field === GENERATED || field === `${GENERATED}=true`) generated = true else if (field === `-${GENERATED}` || field === `${GENERATED}=false`) generated = false - else if (field === `!${GENERATED}`) generated = undefined + else if (field === `!${GENERATED}`) generated = null + else if (field.startsWith(`${LAYER_ATTRIBUTE}=`)) { + const value = field.slice(LAYER_ATTRIBUTE.length + 1) + layer = isLayer(value) ? value : null + } else if (field === `-${LAYER_ATTRIBUTE}` || field === `!${LAYER_ATTRIBUTE}`) layer = null } - if (generated === null) continue + if (layer === undefined && generated === undefined) continue const anchored = pattern.replace(/^\//, '') - rules.push({ match: picomatch(anchored, { dot: true, basename: !pattern.includes('/') }), generated }) + rules.push({ match: picomatch(anchored, { dot: true, basename: !pattern.includes('/') }), layer, generated }) } return (path) => { - let generated: boolean | undefined - for (const rule of rules) if (rule.match(path)) generated = rule.generated - return generated === true + let layer: ForgeFileLayer | null | undefined + let generated: boolean | null | undefined + for (const rule of rules) { + if (!rule.match(path)) continue + if (rule.layer !== undefined) layer = rule.layer + if (rule.generated !== undefined) generated = rule.generated + } + return { layer: layer ?? undefined, generated: generated === true } } } -/** Classifies changed files into review layers by the panel's path globs and a repository's attributes. */ +/** Classifies changed files into review layers by a repository's attributes, the panel's globs, and the built-in rules. */ export class FileLayers { - private readonly test: Matcher - private readonly interface: Matcher + private readonly rules: readonly { readonly layer: ForgeFileLayer; readonly match: Matcher }[] /** - * @param testPaths - globs of the `test` layer. - * @param interfacePaths - globs of the `interface` layer. + * @param testPaths - configured globs of the `test` layer, checked before the built-in rules. + * @param interfacePaths - configured globs of the `interface` layer, checked after `testPaths` and before the built-in rules. */ constructor(testPaths: readonly string[], interfacePaths: readonly string[]) { - this.test = matcherOf(testPaths) - this.interface = matcherOf(interfacePaths) + this.rules = [ + { layer: 'test', match: matcherOf(testPaths) }, + { layer: 'interface', match: matcherOf(interfacePaths) }, + { layer: 'test', match: matcherOf(BUILT_IN_TEST_PATHS) }, + { layer: 'interface', match: matcherOf(BUILT_IN_INTERFACE_PATHS) }, + ] } /** - * Place each file in its layer: `test` first, then `interface`, else `implementation`. + * Place each file in its layer: the layer its attributes name, else `test` for a generated file, else the first + * configured or built-in rule its path matches, else `implementation`. * @param files - parsed files. * @param attributes - the text of the repository's root `.gitattributes`, empty without one. * @returns the files in the same order with their layers. */ classify(files: readonly ParsedDiffFile[], attributes: string): ForgeDiffFile[] { - const generated = generatedMatcher(attributes) + const attributesAt = attributesOf(attributes) return files.map((file) => { - const layer: ForgeFileLayer = this.test(file.path) || generated(file.path) ? 'test' - : this.interface(file.path) ? 'interface' : 'implementation' - return { ...file, layer } + const { layer, generated } = attributesAt(file.path) + const ruled = layer ?? (generated ? 'test' : this.rules.find(rule => rule.match(file.path))?.layer) ?? 'implementation' + return { ...file, layer: ruled } }) } } diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 64cebb0aa4..1237db87b8 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -287,8 +287,9 @@ export interface ForgeDiffHunk { export type ForgeDiffStatus = 'added' | 'deleted' | 'modified' | 'renamed' /** - * Review layer of a changed file by its path: `test` for a path matching `testPaths` or one the repository's root - * `.gitattributes` marks `linguist-generated`, else `interface` for a path matching `interfacePaths`, else `implementation`. + * Review layer of a changed file: the layer the repository's root `.gitattributes` names with `dsh-review-layer`, else + * `test` for a file it marks `linguist-generated`, else the first of `testPaths`, `interfacePaths`, and the built-in + * test and interface rules that the path matches, else `implementation`. */ export type ForgeFileLayer = 'interface' | 'implementation' | 'test' @@ -397,11 +398,14 @@ export interface Config { /** Most commits of the `branch` scope listed, oldest first. */ maxCommits?: number /** - * Globs of tests, snapshots, locale dictionaries, and lockfiles, matched against repository-relative paths with - * dot files included; their files form the `test` layer, which the changes view can hide. + * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before + * them; matched against repository-relative paths with dot files included. A repository's `.gitattributes` overrides both. */ testPaths?: string[] - /** Globs of package manifests, configuration, and type declarations, matched like `testPaths`; their files form the `interface` layer. */ + /** + * Globs of files in the `interface` layer beside the built-in rules, matched like `testPaths`; checked after + * `testPaths` and before the built-in rules. + */ interfacePaths?: string[] } diff --git a/packages/experimental/client-ui-forge/tests/layers.host.spec.ts b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts index 172ebc57d6..fc18cd0bd9 100644 --- a/packages/experimental/client-ui-forge/tests/layers.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/layers.host.spec.ts @@ -1,25 +1,39 @@ -/** Review layers of changed files: path globs and the `linguist-generated` attribute of a root `.gitattributes`. */ +/** Review layers of changed files: repository attributes, configured globs, and the built-in rules, in that order. */ +import { execFile } from 'node:child_process' +import { readFile } from 'node:fs/promises' +import { promisify } from 'node:util' import { describe, expect, it } from 'vitest' import { untrackedFile } from '../src/diff.ts' -import { FileLayers, generatedMatcher } from '../src/layers.ts' +import { attributesOf, FileLayers } from '../src/layers.ts' + +const run = promisify(execFile) +const file = (path: string) => untrackedFile(path, new Uint8Array()) +const layersOf = (layers: FileLayers, paths: readonly string[], attributes = ''): string[] => + layers.classify(paths.map(file), attributes).map(item => `${item.path} ${item.layer}`) + +describe('attributesOf', () => { + const read = attributesOf([ + '# comment', + '', + '[attr]binary -diff -merge -text', + '"quoted name.json" linguist-generated', + 'build/ linguist-generated', + '*.schema.json linguist-generated=true', + 'docs/kept.schema.json -linguist-generated', + 'docs/reset.schema.json !linguist-generated', + 'docs/off.schema.json linguist-generated=false', + '/root.gen.ts linguist-generated', + 'gen/*.ts text linguist-generated', + 'other.txt text', + 'api/*.yaml dsh-review-layer=interface', + 'api/legacy.yaml -dsh-review-layer', + 'api/odd.yaml dsh-review-layer=docs', + 'api/reset.yaml !dsh-review-layer', + '*.snap.ts dsh-review-layer=test linguist-generated', + ].join('\r\n')) -describe('generatedMatcher', () => { it('applies lines in order, with unset and unspecified values overriding an earlier set', () => { - const generated = generatedMatcher([ - '# comment', - '', - '[attr]binary -diff -merge -text', - '"quoted name.json" linguist-generated', - 'build/ linguist-generated', - '*.schema.json linguist-generated=true', - 'docs/kept.schema.json -linguist-generated', - 'docs/reset.schema.json !linguist-generated', - 'docs/off.schema.json linguist-generated=false', - '/root.gen.ts linguist-generated', - 'gen/*.ts text linguist-generated', - 'other.txt text', - ].join('\r\n')) - + const generated = (path: string): boolean => read(path).generated expect(generated('a.schema.json')).toBe(true) expect(generated('docs/deep/a.schema.json')).toBe(true) expect(generated('docs/kept.schema.json')).toBe(false) @@ -34,32 +48,68 @@ describe('generatedMatcher', () => { expect(generated('other.txt')).toBe(false) }) + it('reads a layer name, and leaves an unset, reset, or unknown layer unspecified', () => { + expect(read('api/v1.yaml')).toEqual({ layer: 'interface', generated: false }) + expect(read('api/legacy.yaml').layer).toBeUndefined() + expect(read('api/odd.yaml').layer).toBeUndefined() + expect(read('api/reset.yaml').layer).toBeUndefined() + expect(read('src/a.snap.ts')).toEqual({ layer: 'test', generated: true }) + }) + it('marks nothing without attributes', () => { - expect(generatedMatcher('')('a.ts')).toBe(false) + expect(attributesOf('')('a.ts')).toEqual({ layer: undefined, generated: false }) + }) + + it('agrees with git check-attr on this repository\'s own review layer lines', async () => { + const paths = [ + 'packages/experimental/client-ui-forge/locale/en.json', 'packages/experimental/client-ui-forge/src/client/locales.ts', + 'packages/experimental/client-ui-forge/src/types.ts', 'packages/typert/generator/tests/fixtures/remote-model/packages/domain/src/types.ts', + 'packages/client/locale/package.json', 'snapshots/session/headless.snapshot.ts', 'README.i18n.yaml', 'docs/persistence-schema.json', + ] + const { stdout } = await run('git', ['check-attr', 'dsh-review-layer', 'linguist-generated', '--', ...paths]) + const expected = paths.map((path) => { + const value = (name: string): string | undefined => new RegExp(`^${path.replaceAll('.', '\\.')}: ${name}: (.*)$`, 'm').exec(stdout)?.[1] + const layer = value('dsh-review-layer') + return { layer: layer === 'unspecified' ? undefined : layer, generated: value('linguist-generated') === 'true' } + }) + const read = attributesOf(await readFile(new URL('../../../../.gitattributes', import.meta.url), 'utf8')) + expect(paths.map(path => read(path))).toEqual(expected) }) }) describe('FileLayers', () => { - const file = (path: string) => untrackedFile(path, new Uint8Array()) - - it('places a file in the test layer first, then the interface layer, else the implementation layer', () => { - const layers = new FileLayers(['**/*.spec.*', '**/locale/*.json'], ['**/package.json', '**/*.json']) - const classified = layers.classify( - ['src/a.ts', 'src/a.spec.ts', 'package.json', 'locale/en.json', 'docs/schema.json', '.github/x.json'].map(file), - 'docs/schema.json linguist-generated\n', - ) - - expect(classified.map(item => [item.path, item.layer])).toEqual([ - ['src/a.ts', 'implementation'], - ['src/a.spec.ts', 'test'], - ['package.json', 'interface'], - ['locale/en.json', 'test'], - ['docs/schema.json', 'test'], - ['.github/x.json', 'interface'], + it('follows the built-in conventions of common languages and tools', () => { + expect(layersOf(new FileLayers([], []), [ + 'pkg/server_test.go', 'pkg/testdata/in.txt', 'app/test_api.py', 'app/api_test.py', 'conftest.py', 'spec/models/user_spec.rb', + 'Tests/AppTests/AppTests.swift', 'App.Tests/UnitTest1.cs', 'src/a.spec.ts', 'src/__snapshots__/a.snap', 'config/locales/en.yml', + 'po/zh_CN.po', 'App/en.lproj/Localizable.strings', 'app/src/main/res/values-zh/strings.xml', 'Cargo.lock', 'go.sum', 'uv.lock', + 'go.mod', 'Cargo.toml', 'pyproject.toml', 'lib.gemspec', 'build.gradle.kts', 'App.csproj', 'Package.swift', 'include/api.h', + 'stubs/api.pyi', 'api/service.proto', 'schema.graphql', 'openapi.yaml', 'index.d.ts', 'package.json', + 'src/main.rs', 'docs/config-catalog.md', 'tsconfig.json', 'README.i18n.yaml', + ])).toEqual([ + 'pkg/server_test.go test', 'pkg/testdata/in.txt test', 'app/test_api.py test', 'app/api_test.py test', 'conftest.py test', + 'spec/models/user_spec.rb test', 'Tests/AppTests/AppTests.swift test', 'App.Tests/UnitTest1.cs test', 'src/a.spec.ts test', + 'src/__snapshots__/a.snap test', 'config/locales/en.yml test', 'po/zh_CN.po test', 'App/en.lproj/Localizable.strings test', + 'app/src/main/res/values-zh/strings.xml test', 'Cargo.lock test', 'go.sum test', 'uv.lock test', + 'go.mod interface', 'Cargo.toml interface', 'pyproject.toml interface', 'lib.gemspec interface', 'build.gradle.kts interface', + 'App.csproj interface', 'Package.swift interface', 'include/api.h interface', 'stubs/api.pyi interface', 'api/service.proto interface', + 'schema.graphql interface', 'openapi.yaml interface', 'index.d.ts interface', 'package.json interface', + 'src/main.rs implementation', 'docs/config-catalog.md implementation', 'tsconfig.json implementation', 'README.i18n.yaml implementation', ]) }) - it('places every file in the implementation layer without globs or attributes', () => { - expect(new FileLayers([], []).classify([file('a.spec.ts')], '')).toMatchObject([{ layer: 'implementation' }]) + it('checks repository attributes, then configured globs, then the built-in rules', () => { + const layers = new FileLayers(['**/fixtures/**'], ['**/cordis.yml', '**/*.spec.ts']) + expect(layersOf(layers, [ + 'src/a.spec.ts', 'tests/fixtures/cordis.yml', 'apps/cordis.yml', 'docs/schema.json', 'tests/keep.ts', 'src/api.ts', 'src/gen.ts', + ], [ + 'docs/schema.json linguist-generated', + 'tests/keep.ts dsh-review-layer=implementation', + 'src/api.ts dsh-review-layer=interface', + 'src/gen.ts linguist-generated dsh-review-layer=implementation', + ].join('\n'))).toEqual([ + 'src/a.spec.ts interface', 'tests/fixtures/cordis.yml test', 'apps/cordis.yml interface', 'docs/schema.json test', + 'tests/keep.ts implementation', 'src/api.ts interface', 'src/gen.ts implementation', + ]) }) }) From 9fc22ad970e3459db828505b0af0b72985ccd5a9 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 18:57:52 +0800 Subject: [PATCH 066/103] fix(commands): report saved permission and plan changes during shutdown --- docs/subsystems/approval.md | 6 +- docs/subsystems/approval.zh.md | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- .../tests/projection.spec.ts | 26 +++++++++ .../user-approval/README.i18n.yaml | 12 ++-- packages/interaction/user-approval/README.md | 6 +- .../interaction/user-approval/README.zh.md | 6 +- .../interaction/user-approval/src/index.ts | 17 ++++-- packages/plan/plan-mode/README.i18n.yaml | 4 +- packages/plan/plan-mode/README.md | 2 +- packages/plan/plan-mode/README.zh.md | 2 +- packages/plan/plan-mode/src/index.ts | 21 +++++-- .../plan/plan-mode/tests/plan-mode.spec.ts | 58 ++++++++++++++++++- 13 files changed, 134 insertions(+), 34 deletions(-) diff --git a/docs/subsystems/approval.md b/docs/subsystems/approval.md index 5a2513775a..a35ef99e9f 100644 --- a/docs/subsystems/approval.md +++ b/docs/subsystems/approval.md @@ -103,9 +103,9 @@ Approval service that applies session policy before answerers and logs every ask ```ts cordis-catalog /** - * Switch one live agent's policy and queue the transition for its next model - * step. Session initialization uses {@link setApprovalPolicy} directly - * because there is no previously visible policy to change. + * Persist a live Agent's policy. Queue the switch notice for the next model + * step while the Agent accepts input. Session initialization uses + * {@link setApprovalPolicy} directly. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ diff --git a/docs/subsystems/approval.zh.md b/docs/subsystems/approval.zh.md index 74aa7fbfc1..445f2d9be6 100644 --- a/docs/subsystems/approval.zh.md +++ b/docs/subsystems/approval.zh.md @@ -103,9 +103,9 @@ Approval service that applies session policy before answerers and logs every ask ```ts cordis-catalog /** - * Switch one live agent's policy and queue the transition for its next model - * step. Session initialization uses {@link setApprovalPolicy} directly - * because there is no previously visible policy to change. + * Persist a live Agent's policy. Queue the switch notice for the next model + * step while the Agent accepts input. Session initialization uses + * {@link setApprovalPolicy} directly. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 74a5703129..14f663e5c4 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -402,7 +402,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'setPolicy(agent: Agent, policy: ApprovalPolicy): void', - description: 'Switch one live agent\'s policy and queue the transition for its next model step. Session initialization uses setApprovalPolicy directly because there is no previously visible policy to change.', + description: 'Persist a live Agent\'s policy. Queue the switch notice for the next model step while the Agent accepts input. Session initialization uses setApprovalPolicy directly.', parameters: [{ name: 'agent', description: 'the live agent whose policy is changing.' }, { name: 'policy', description: 'the new effective policy.' }], }, { diff --git a/packages/interaction/permission-presets/tests/projection.spec.ts b/packages/interaction/permission-presets/tests/projection.spec.ts index d1d98d7c66..e2b2749f24 100644 --- a/packages/interaction/permission-presets/tests/projection.spec.ts +++ b/packages/interaction/permission-presets/tests/projection.spec.ts @@ -14,6 +14,7 @@ import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deep import { Context } from '@deepseek-ai/cordis' import { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' +import { AgentClosedError } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { createScope } from '@deepseek-ai/dsh-scope' import CommandRuntime from '@deepseek-ai/dsh-commands' @@ -176,6 +177,31 @@ describe('/permission command', () => { expect(run?.data).toMatchObject({ name: 'permission', args: ' danger-full-access' }) }) + it('reports the saved preset when a closing Agent rejects its policy notice', async () => { + const { ctx, session } = await harness() + const { agent, inject } = await agentFor(ctx, session) + inject.mockImplementation(() => { throw new AgentClosedError(agent.id) }) + + const execution = await ctx.commands.execute(agent, '/permission danger-full-access', [], new AbortController().signal) + + expect(execution?.result).toEqual({ kind: 'success', text: 'preset danger-full-access' }) + expect(ctx.permissionPresets.current(session)).toBe('danger-full-access') + const events = session.snapshotEvents() + expect(events.findLast(event => event.type === 'sandbox/mode')?.data.mode).toBe('danger-full-access') + expect(events.findLast(event => event.type === 'approval/policy')?.data.policy).toBe('never') + expect(events.findLast(event => event.type === 'command/done')?.data.kind).toBe('success') + }) + + it('propagates an unexpected policy notice failure', async () => { + const { ctx, session } = await harness() + const { agent, inject } = await agentFor(ctx, session) + const failure = new Error('could not write policy notice') + inject.mockImplementation(() => { throw failure }) + + await expect(ctx.commands.execute(agent, '/permission danger-full-access', [], new AbortController().signal)) + .rejects.toBe(failure) + }) + it('reports the current preset and the table on bare invocation', async () => { const { ctx, session } = await harness() const { agent } = await agentFor(ctx, session) diff --git a/packages/interaction/user-approval/README.i18n.yaml b/packages/interaction/user-approval/README.i18n.yaml index d648bb92f3..3420e02af8 100644 --- a/packages/interaction/user-approval/README.i18n.yaml +++ b/packages/interaction/user-approval/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3618ddc3386e65f0 zh: d6c0ac91aae122bb /deepseek-ai-dsh-user-approval/use-this-package/setting-the-policy: - en: 79f3334a395b9368 - zh: 0c4026b505ee254a + en: d6e8b94fb407947f + zh: b1a60a6ad2448eca /deepseek-ai-dsh-user-approval/use-this-package/requesting-a-decision: en: dc465de82799bab0 zh: 51144cc77bb15689 @@ -39,8 +39,8 @@ en: 38c3646e45d3dddd zh: 3363dde8c786d6b2 /deepseek-ai-dsh-user-approval/understand-the-implementation/policy-and-the-runtime-context-snapshot: - en: a1aa2178ce3a4b85 - zh: db06e4d2e8e259f1 + en: afd007076c584667 + zh: f2951e0dbd01c6e6 /deepseek-ai-dsh-user-approval/understand-the-implementation/audit: en: 145530678bac5912 zh: a464effa3a29fce0 @@ -54,8 +54,8 @@ en: d23980f003b42fbb zh: 532f0174de5d87b5 /deepseek-ai-dsh-user-approval/model-experience/current-approval-policy-context/what-the-model-sees: - en: eb41f1a4972c07f5 - zh: 4264f408eb951951 + en: 59311269308fa32c + zh: d8b1bcae501c9903 /deepseek-ai-dsh-user-approval/model-experience/current-approval-policy-context/what-the-model-sees/ask-policy-contribution: en: b9f1262c97ec7568 zh: 8a6613695f896f70 diff --git a/packages/interaction/user-approval/README.md b/packages/interaction/user-approval/README.md index 1ac2fce1d8..35ef24b1ef 100644 --- a/packages/interaction/user-approval/README.md +++ b/packages/interaction/user-approval/README.md @@ -46,7 +46,7 @@ The effective policy is the one set for the session, falling back to the configu |---|---|---| | `policy` | `ask` | Default for sessions without an `approval/policy` override | -The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-user-approval) is the exhaustive source for every accepted field and its JSDoc. `setPolicy(agent, policy)` switches a live agent and queues the switch notice described under Model Experience for its next model step; `setApprovalPolicy(session, policy)` is the direct durable write path used by session initialization. +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-user-approval) is the exhaustive source for every accepted field and its JSDoc. `setPolicy(agent, policy)` persists a live Agent's policy and queues the switch notice described under Model Experience while the Agent accepts input; `setApprovalPolicy(session, policy)` is the direct durable write path used by session initialization. ### Requesting a decision @@ -83,7 +83,7 @@ The private host-only `approvalState` projection stores the policy override and Service activation waits for projection registration and fails if registration fails. The service keeps the returned reader private. The host and registry own Session recovery; approval methods do not load history or call hydration from a synchronous read. See the [registration and recovery API](../../session/session-projection/README.md). Pending questions, answerers, and grants remain in the runtime. -The system-prompt contribution `approval:policy` states the complete current meaning of the effective policy — `ask` with its fail-closed consequence, or `never` with its non-escalation consequence — after retained history, so switching policy appends a new full snapshot instead of rewriting the stable request header. `setPolicy()` also injects a sourced user message announcing the change for the next step. +The system-prompt contribution `approval:policy` states the complete current meaning of the effective policy — `ask` with its fail-closed consequence, or `never` with its non-escalation consequence — after retained history, so switching policy appends a new full snapshot instead of rewriting the stable request header. `setPolicy()` also injects a sourced user message announcing the change for the next step while the Agent accepts input. ### Audit @@ -112,7 +112,7 @@ Read these pages when the package-level contract is not enough. They move from t #### What the model sees -The first request and each effective policy change append a full runtime-context snapshot after retained history. Under `ask`, the approval contribution states that configured answerers may be consulted and absence fails closed. Under `never`, it states the deterministic rejection and non-escalation consequence. Unchanged requests retain the earlier snapshot without adding another message. When the user switches a live Session's policy, the next model step also receives a switch notice. +The first request and each effective policy change append a full runtime-context snapshot after retained history. Under `ask`, the approval contribution states that configured answerers may be consulted and absence fails closed. Under `never`, it states the deterministic rejection and non-escalation consequence. Unchanged requests retain the earlier snapshot without adding another message. A live policy switch also queues a notice for the next model step while the Agent accepts input. ##### Ask-policy contribution diff --git a/packages/interaction/user-approval/README.zh.md b/packages/interaction/user-approval/README.zh.md index 1dabd4bfe9..3cbbc994b6 100644 --- a/packages/interaction/user-approval/README.zh.md +++ b/packages/interaction/user-approval/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" |---|---|---| | `policy` | `ask` | 没有 `approval/policy` 覆盖的会话的默认策略 | -生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-user-approval)是每个受支持字段及其 JSDoc 的穷尽式真源。`setPolicy(agent, policy)` 切换运行中的 agent 的策略,并为它的下一个模型步骤排队一条模型体验一节所述的切换通知;`setApprovalPolicy(session, policy)` 是会话初始化使用的直接持久写入路径。 +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-user-approval)是每个受支持字段及其 JSDoc 的穷尽式真源。`setPolicy(agent, policy)` 持久化运行中的 Agent 的策略,并在 Agent 仍接纳输入时为下一个模型步骤排队一条模型体验一节所述的切换通知;`setApprovalPolicy(session, policy)` 是会话初始化使用的直接持久写入路径。 ### 请求决定 @@ -83,7 +83,7 @@ kind: "package-reference" 服务激活会等待 Projection 注册完成;注册失败会使激活失败。服务私有持有返回的读取句柄。宿主和注册表负责会话恢复;审批方法不会在同步读取时加载历史或调用 hydration。参见[注册与恢复 API](../../session/session-projection/README.zh.md)。待处理问题、应答者和授权仍由运行时负责。 -系统提示词贡献 `approval:policy` 在保留历史之后陈述有效策略的完整当前含义——`ask` 及其以拒绝方式关闭的后果,或 `never` 及其非升权后果——因此切换策略会追加一份新的完整快照,而不会改写稳定的请求头。`setPolicy()` 还会注入一条带来源的用户消息,为下一步宣布变更。 +系统提示词贡献 `approval:policy` 在保留历史之后陈述有效策略的完整当前含义——`ask` 及其以拒绝方式关闭的后果,或 `never` 及其非升权后果——因此切换策略会追加一份新的完整快照,而不会改写稳定的请求头。`setPolicy()` 还会在 Agent 仍接纳输入时注入一条带来源的用户消息,为下一步宣布变更。 ### 审计 @@ -112,7 +112,7 @@ kind: "package-reference" #### 模型看到的内容 -首次请求与有效策略每次变化时,都会在保留的历史后追加一份完整运行时上下文快照。在 `ask` 下,审批上下文内容会说明系统可以咨询已配置的应答者,缺少可用应答者时则以拒绝方式关闭。在 `never` 下,它会说明确定性的拒绝与非升权后果。未变化的请求会保留先前快照,不增加另一条消息。用户切换运行中 Session 的策略时,下一次模型调用还会收到一条切换通知。 +首次请求与有效策略每次变化时,都会在保留的历史后追加一份完整运行时上下文快照。在 `ask` 下,审批上下文内容会说明系统可以咨询已配置的应答者,缺少可用应答者时则以拒绝方式关闭。在 `never` 下,它会说明确定性的拒绝与非升权后果。未变化的请求会保留先前快照,不增加另一条消息。Agent 仍接纳输入时,策略切换还会为下一次模型调用排队一条通知。 ##### Ask 策略贡献 diff --git a/packages/interaction/user-approval/src/index.ts b/packages/interaction/user-approval/src/index.ts index df48aca514..f469ff43ec 100644 --- a/packages/interaction/user-approval/src/index.ts +++ b/packages/interaction/user-approval/src/index.ts @@ -9,7 +9,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { Agent } from '@deepseek-ai/dsh-agent' -import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { HarnessError, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -202,9 +202,9 @@ export class ApprovalService extends Service { } /** - * Switch one live agent's policy and queue the transition for its next model - * step. Session initialization uses {@link setApprovalPolicy} directly - * because there is no previously visible policy to change. + * Persist a live Agent's policy. Queue the switch notice for the next model + * step while the Agent accepts input. Session initialization uses + * {@link setApprovalPolicy} directly. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ @@ -212,13 +212,18 @@ export class ApprovalService extends Service { const previous = this.effectivePolicy(agent.session) if (previous === policy) return setApprovalPolicy(agent.session, policy) - agent.inject(createUserMessage({ + const notice = createUserMessage({ content: [{ type: 'text', text: `The user changed the approval policy from "${POLICY_NOTICE_NAMES[previous]}" to "${POLICY_NOTICE_NAMES[policy]}".`, }], source: { kind: 'user-approval' }, - })) + }) + try { + agent.inject(notice) + } catch (error: unknown) { + if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error + } } /** diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index 96b7f724c7..ec9790ee28 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -24,8 +24,8 @@ en: 30b67de3f6e97eab zh: 746cc81fbf5e0ed1 /deepseek-ai-dsh-plan-mode/use-this-package/entering-and-leaving-plan-mode: - en: 2d300cdb883352ec - zh: 5a81be005b3716d3 + en: 07ea7917ccae9613 + zh: a095e3eee8189456 /deepseek-ai-dsh-plan-mode/use-this-package/the-reviewed-exit: en: dbf12997d2359e81 zh: 120a91554d2154f4 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index 0ea3a4b33c..f7ea4c60c0 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -54,7 +54,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a Type `/plan` to enter plan mode, or `/plan ` to enter with an instruction — the message becomes your next request under plan guidance. Type `/plan off` to leave plan mode directly; it also cancels a plan-mode entry that has not taken effect yet. -You can attach images and generic files to a `/plan` message, and they are included with your instruction in selection order. `/plan off` with attachments is rejected before the mode changes, so the draft and cards remain available. The `/plan` command is available wherever slash commands are supported, such as the Web client. +You can attach images and generic files to a `/plan` message, and they are included with your instruction in selection order. `/plan off` with attachments is rejected before the mode changes, so the draft and cards remain available. If the Agent closes before the message enters the inbox, the command reports whether plan mode is active or pending and leaves attachments in the composer. The `/plan` command is available wherever slash commands are supported, such as the Web client. ### The reviewed exit diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index 90ee3c97e5..ec0bd0c5a4 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -54,7 +54,7 @@ kind: "package-reference" 输入 `/plan` 进入计划模式,或输入 `/plan ` 连同一条指令一起进入——该消息会成为你在计划引导下的下一条请求。输入 `/plan off` 直接离开计划模式;它还会取消尚未生效的计划模式进入。 -你可以在 `/plan` 消息中附带图片与通用文件,它们按选择顺序随指令一起提交。带附件的 `/plan off` 会在模式变更前被拒绝,因此草稿和附件卡仍可继续使用。`/plan` 命令在支持斜杠命令的界面中可用,例如 Web 客户端。 +你可以在 `/plan` 消息中附带图片与通用文件,它们按选择顺序随指令一起提交。带附件的 `/plan off` 会在模式变更前被拒绝,因此草稿和附件卡仍可继续使用。如果 Agent 在消息入队前开始关闭,命令会说明计划模式已生效还是待生效,并将附件保留在输入区。`/plan` 命令在支持斜杠命令的界面中可用,例如 Web 客户端。 ### 经评审的退出 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index 06af5c2828..c909e7e982 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -27,7 +27,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' -import { createUserMessage } from '@deepseek-ai/dsh-llm' +import { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' import { defineTool } from '@deepseek-ai/dsh-tools' @@ -259,13 +259,20 @@ export class PlanModeController extends Service { } const outcome = this.set(agent, true) if (message !== '' || attachments.length > 0) { - agent.steer(createUserMessage({ + const input = createUserMessage({ content: [ ...attachments, ...(message === '' ? [] : [{ type: 'text' as const, text: message }]), ], source: { kind: 'user' }, - })) + }) + try { + agent.steer(input) + } catch (error: unknown) { + if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error + const state = this.loggedActive(agent.session) ? 'Plan mode is on.' : 'Plan mode is still pending.' + return { kind: 'error', text: `${state} The agent is closing, so the message was not submitted.` } + } } return { kind: 'success', @@ -446,7 +453,13 @@ export class PlanModeController extends Service { session.append('plan/mode', { active }) this.pendingIntents.delete(session) const narration = this.narration(session, active) - if (narration !== undefined) agent.inject(narration) + if (narration !== undefined) { + try { + agent.inject(narration) + } catch (error: unknown) { + if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error + } + } return 'committed' } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 99d72afd1d..5fa706ea77 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -10,7 +10,7 @@ import ToolRuntime, { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import type { ToolExecutionToken, ToolRunContext } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { Session, SessionId, SESSION_FORMAT_VERSION, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { AgentClosedError, agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { createScope } from '@deepseek-ai/dsh-scope' import UserQuestionService, { UserQuestionError, type AskUserQuestionAnswer, type AskUserQuestionRequest, @@ -680,6 +680,62 @@ describe('/plan', () => { expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) }) + it.each([ + { open: false, active: true, state: 'Plan mode is on.' }, + { open: true, active: false, state: 'Plan mode is still pending.' }, + ])('reports the mode and the rejected message when a closing Agent has open turn $open', async ({ open, active, state }) => { + const ctx = await setup() + try { + await ctx.plugin(CommandRuntime) + const agent = await agentWithSession(ctx, 'closing-plan-command') + if (open) openTurn(agent.session) + agent.steer = () => { throw new AgentClosedError(agent.id) } + + const execution = await ctx.commands.execute(agent, '/plan sketch the layout', [], testToolSignal) + + const expected = { kind: 'error', text: `${state} The agent is closing, so the message was not submitted.` } + expect(execution?.result).toEqual(expected) + expect(foldPlanMode(agent.session.snapshotEvents())).toBe(active) + expect(ctx.planMode.get(agent)).toEqual(open ? { active, pending: true } : { active }) + expect(agent.session.snapshotEvents().findLast(event => event.type === 'command/done')?.data) + .toMatchObject(expected) + } finally { + await ctx.fiber.dispose() + } + }) + + it('reports a saved mode switch when a closing Agent rejects its switch notice', async () => { + const ctx = await setup() + try { + await ctx.plugin(CommandRuntime) + const agent = await agentWithSession(ctx, 'closing-plan-notice', { active: true }) + header(agent.session) + agent.inject = () => { throw new AgentClosedError(agent.id) } + + const execution = await ctx.commands.execute(agent, '/plan off', [], testToolSignal) + + expect(execution?.result).toEqual({ kind: 'success', text: 'Plan mode off.' }) + expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) + } finally { + await ctx.fiber.dispose() + } + }) + + it.each(['inject', 'steer'] as const)('propagates an unexpected plan %s failure', async (delivery) => { + const ctx = await setup() + try { + await ctx.plugin(CommandRuntime) + const agent = await agentWithSession(ctx, 'plan-delivery-error') + header(agent.session) + const failure = new Error('could not write plan input') + agent[delivery] = () => { throw failure } + + await expect(ctx.commands.execute(agent, '/plan sketch the layout', [], testToolSignal)).rejects.toBe(failure) + } finally { + await ctx.fiber.dispose() + } + }) + it('steers mixed attachments with or without text and refuses them on /plan off', async () => { const ctx = await setup() await ctx.plugin(CommandRuntime) From 0e5c4765e64b25727f6f202c44f29d675b3e5f65 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 19:20:28 +0800 Subject: [PATCH 067/103] refactor(agent): isolate cancellation and quiescent teardown --- docs/architecture.i18n.yaml | 4 +- docs/architecture.md | 2 +- docs/architecture.zh.md | 2 +- docs/event-producer-consumer.md | 22 +++---- docs/event-producer-consumer.zh.md | 22 +++---- docs/subsystems/approval.md | 6 +- docs/subsystems/approval.zh.md | 6 +- docs/subsystems/core.i18n.yaml | 4 +- docs/subsystems/core.md | 8 +-- docs/subsystems/core.zh.md | 8 +-- .../agent-closed-admission/guide.i18n.yaml | 16 ----- .../agent-closed-admission/guide.md | 17 ------ .../agent-closed-admission/guide.zh.md | 17 ------ packages/core/agent-loop/README.i18n.yaml | 4 +- packages/core/agent-loop/README.md | 2 +- packages/core/agent-loop/README.zh.md | 2 +- packages/core/agent-loop/src/agent.ts | 18 ++---- packages/core/agent-loop/src/inbox.ts | 12 ---- packages/core/agent-loop/src/index.ts | 1 - packages/core/agent-loop/tests/cancel.spec.ts | 4 +- .../agent-loop/tests/input-lifecycle.spec.ts | 56 +----------------- .../agent-loop/tests/request-freeze.spec.ts | 6 +- packages/core/agent/README.i18n.yaml | 8 +-- packages/core/agent/README.md | 4 +- packages/core/agent/README.zh.md | 4 +- packages/core/agent/src/closed-error.ts | 15 ----- packages/core/agent/src/index.ts | 1 - packages/core/agent/src/runtime-types.ts | 6 +- .../extensions/tool-cordis/src/api-catalog.ts | 2 +- packages/goal/command-goal/README.i18n.yaml | 4 +- packages/goal/command-goal/README.md | 2 +- packages/goal/command-goal/README.zh.md | 2 +- packages/goal/command-goal/src/index.ts | 39 ++++++------- .../command-goal/tests/command-goal.spec.ts | 41 +------------ .../goal/goal-round-driver/README.i18n.yaml | 4 +- packages/goal/goal-round-driver/README.md | 2 +- packages/goal/goal-round-driver/README.zh.md | 2 +- packages/goal/goal-round-driver/src/index.ts | 3 +- .../tests/goal-round-driver.spec.ts | 16 +---- .../tests/projection.spec.ts | 26 --------- .../user-approval/README.i18n.yaml | 12 ++-- packages/interaction/user-approval/README.md | 6 +- .../interaction/user-approval/README.zh.md | 6 +- .../interaction/user-approval/src/index.ts | 17 ++---- packages/plan/plan-mode/README.i18n.yaml | 4 +- packages/plan/plan-mode/README.md | 2 +- packages/plan/plan-mode/README.zh.md | 2 +- packages/plan/plan-mode/src/index.ts | 21 ++----- .../plan/plan-mode/tests/plan-mode.spec.ts | 58 +------------------ packages/sdk/server/src/server.ts | 5 +- .../working-directory/README.i18n.yaml | 4 +- packages/session/working-directory/README.md | 2 +- .../session/working-directory/README.zh.md | 2 +- .../session/working-directory/src/index.ts | 3 +- .../tests/working-directory.spec.ts | 18 ------ packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 9 +-- .../subagent/tests/continuation.spec.ts | 18 +----- 60 files changed, 128 insertions(+), 489 deletions(-) delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md delete mode 100644 docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md delete mode 100644 packages/core/agent/src/closed-error.ts diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index decf0ba439..d897229806 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -21,8 +21,8 @@ en: 20ef882e44b06a10 zh: c10c3934ed5570e9 /deepseek-harness-architecture/events: - en: 9a7297518f6b7bdf - zh: 883364ea3f1ac82b + en: 0d4481070a0ba352 + zh: 026be77a9f3db68e /deepseek-harness-architecture/turn-flow: en: 1d496f1893bdbb8d zh: f16d162a803fc791 diff --git a/docs/architecture.md b/docs/architecture.md index c401c3bbeb..c7c036016b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -74,7 +74,7 @@ Events provide extension points in three domains. Subagent Activations own runtime tree membership. -AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown closes input admission, cancels and waits for admitted work despite queue-cleanup failures, then releases resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). +AgentLoop rolls back failed initialization and awaits serial `agent/created` before queued work; shutdown cancels and awaits active work despite queue-cleanup failures before releasing resources ([ordering](../packages/core/agent-loop/README.md#understand-the-implementation)). [Event producers and consumers](event-producer-consumer.md). diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index bc1cf7326c..2eae113769 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -76,7 +76,7 @@ Electron 使用 Electron Node 模式启动私有 Desktop Host。Host 调用共 Subagent Activation 拥有运行时树成员关系。 -AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭先停止接收输入,在队列清理失败时仍取消并等待已接纳工作,然后释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 +AgentLoop 回滚失败的初始化,并在启动已排队工作前等待串行 `agent/created`;关闭时即使队列清理失败,也会取消并等待当前工作,再释放资源([顺序](../packages/core/agent-loop/README.zh.md#understand-the-implementation))。 [事件生产者与消费者](event-producer-consumer.zh.md)。 diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 5247fc4477..4e0f7920d6 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -12,17 +12,17 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f8c8c77e5a..1b9be5ea97 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -14,17 +14,17 @@ | --- | --- | --- | --- | --- | | `agent-loop/config-start-failed` | `emit` | [`packages/core/agent-loop/src/index.ts:198`](../packages/core/agent-loop/src/index.ts) | [`agent-loop`](../packages/core/agent-loop) (`events.dispatch`) | - | | `agent-preset/selected` | `emit` | [`packages/preset/agent-preset-registry/src/types.ts:66`](../packages/preset/agent-preset-registry/src/types.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`) | [`cua`](../packages/experimental/cua), `remotes` | -| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:404`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | -| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:295`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | -| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:304`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:434`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | -| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:333`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:341`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | -| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:322`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | -| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:355`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | -| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:394`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | -| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:314`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | -| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:422`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | +| `agent/assistant-stream` | `emit` | [`packages/core/agent/src/runtime-types.ts:400`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`headless`](../packages/bundle/headless), `session-controller` | +| `agent/created` | `serial` | [`packages/core/agent/src/runtime-types.ts:291`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`serial`) | [`agent-team`](../packages/team/agent-team), `browser-use-runtime`, `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`cua`](../packages/experimental/cua), [`file-reference-local`](../packages/context/file-reference-local), [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`loader-smoke`](../packages/test-support/loader-smoke), [`permission-presets`](../packages/interaction/permission-presets), `session-controller`, [`tool-subagent`](../packages/subagent/tool-subagent) | +| `agent/disposed` | `emit` | [`packages/core/agent/src/runtime-types.ts:300`](../packages/core/agent/src/runtime-types.ts) | [`agent`](../packages/core/agent) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-loop`](../packages/core/agent-loop), `claude-code-mods`, [`creation-recommendations`](../packages/experimental/creation-recommendations), [`file-reference-local`](../packages/context/file-reference-local), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/error` | `emit` | [`packages/core/agent/src/runtime-types.ts:430`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`deepseek-account`](../packages/credentials/deepseek-account), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), `server`, `session-controller`, [`session-telemetry`](../packages/session/session-telemetry), [`subagent`](../packages/subagent/subagent) | +| `agent/inbox/claimed` | `emit` | [`packages/core/agent/src/runtime-types.ts:329`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/discarded` | `emit` | [`packages/core/agent/src/runtime-types.ts:337`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`user-questions`](../packages/interaction/user-questions) | +| `agent/inbox/inserted` | `emit` | [`packages/core/agent/src/runtime-types.ts:318`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | `client-ui-forge`, [`goal-round-driver`](../packages/goal/goal-round-driver), [`subagent`](../packages/subagent/subagent), [`tool-jobs`](../packages/jobs/tool-jobs), [`tool-subagent-control`](../packages/subagent/tool-subagent-control) | +| `agent/pre-step` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:351`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`action-cards`](../packages/experimental/action-cards), [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `session-controller`, [`session-reference`](../packages/context/session-reference), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tmux-context`](../packages/context/tmux-context), [`tool-skill`](../packages/skill/tool-skill) | +| `agent/request-error` | `waterfall` | [`packages/core/agent/src/runtime-types.ts:390`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compaction-basic`](../packages/compaction/compaction-basic), [`compaction-image-offload`](../packages/compaction/compaction-image-offload), [`llm-retry`](../packages/llm/llm-retry) | +| `agent/status` | `emit` | [`packages/core/agent/src/runtime-types.ts:310`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`acp`](../packages/acp/acp), [`compaction-basic`](../packages/compaction/compaction-basic), [`goal-round-driver`](../packages/goal/goal-round-driver), `server`, `session-controller` | +| `agent/turn-stopping` | `serial` | [`packages/core/agent/src/runtime-types.ts:418`](../packages/core/agent/src/runtime-types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `api-session/activity` | `emit` | [`packages/api/session-controller/src/types.ts:705`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/added` | `emit` | [`packages/api/session-controller/src/types.ts:685`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | | `api-session/error` | `emit` | [`packages/api/session-controller/src/types.ts:712`](../packages/api/session-controller/src/types.ts) | `session-controller` (`emit`) | `remotes` | diff --git a/docs/subsystems/approval.md b/docs/subsystems/approval.md index a35ef99e9f..5a2513775a 100644 --- a/docs/subsystems/approval.md +++ b/docs/subsystems/approval.md @@ -103,9 +103,9 @@ Approval service that applies session policy before answerers and logs every ask ```ts cordis-catalog /** - * Persist a live Agent's policy. Queue the switch notice for the next model - * step while the Agent accepts input. Session initialization uses - * {@link setApprovalPolicy} directly. + * Switch one live agent's policy and queue the transition for its next model + * step. Session initialization uses {@link setApprovalPolicy} directly + * because there is no previously visible policy to change. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ diff --git a/docs/subsystems/approval.zh.md b/docs/subsystems/approval.zh.md index 445f2d9be6..74aa7fbfc1 100644 --- a/docs/subsystems/approval.zh.md +++ b/docs/subsystems/approval.zh.md @@ -103,9 +103,9 @@ Approval service that applies session policy before answerers and logs every ask ```ts cordis-catalog /** - * Persist a live Agent's policy. Queue the switch notice for the next model - * step while the Agent accepts input. Session initialization uses - * {@link setApprovalPolicy} directly. + * Switch one live agent's policy and queue the transition for its next model + * step. Session initialization uses {@link setApprovalPolicy} directly + * because there is no previously visible policy to change. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index c3495dec81..363584a5fd 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -12,8 +12,8 @@ en: d71c669c1a36bf52 zh: 9b335f90c84a894e /core/the-agent-handle: - en: bb0aec7a50800c1e - zh: a58a3392368f644a + en: 6ee15fec81bc0686 + zh: b6f3fcd48823ea75 /core/initiating-agent: en: 6c8c47ac78de2dde zh: c9d527a25a85d1d9 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 7e86e6e0d1..a00dc512ef 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -98,7 +98,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. + * @throws synchronously when turn-driving or another maintenance task already owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -113,7 +113,6 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -121,7 +120,6 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -131,7 +129,6 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -142,7 +139,6 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -374,8 +370,6 @@ The cause is a TypeScript-enforced same-process input. An active cancellation ho The [event taxonomy](../architecture.md#events) owns the `agent/*` lifecycle, checkpoint, and waterfall contracts. Turn and step boundaries are durable session events rather than agent emits. -`AgentClosedError` extends `HarnessError` with code `AGENT_CLOSED` and the affected `agentId`. Admission closes when the caller cancels creation, the Agent starts disposal, or its factory begins shutdown. The creation signal stops governing admission after creation succeeds. - ## Initiating Agent The process-local initiator carried by `ctx.agents` is the exact `Agent` above, not a separate frame or copied identity. Ambient presence is neither liveness proof nor authorization; the [initiator-scope decision](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.md) defines its lifetime and scope rules. diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index c82be05f03..5cb66a1692 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -102,7 +102,7 @@ interface Agent { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. + * @throws synchronously when turn-driving or another maintenance task already owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -117,7 +117,6 @@ interface Agent { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -125,7 +124,6 @@ interface Agent { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -135,7 +133,6 @@ interface Agent { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -146,7 +143,6 @@ interface Agent { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } @@ -380,8 +376,6 @@ cause 是由 TypeScript 强制约束的同进程输入。活跃的取消持有 -`AgentClosedError` 继承 `HarnessError`,包含错误码 `AGENT_CLOSED` 和受影响的 `agentId`。调用方取消创建、Agent 开始释放或工厂开始关闭时,Agent 停止接纳新工作。创建成功后,创建信号不再控制工作接纳。 - ## 发起 Agent `ctx.agents` 携带的进程本地 initiator 就是上面的确切 `Agent`,不是单独的 frame 或复制的标识。环境中存在该值既不能证明存活,也不代表授权;[initiator 作用域决策](../../.agents/notes/implemented/architecture/2026-07-15-agent-initiator-scope.zh.md)定义其生命周期和作用域规则。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml deleted file mode 100644 index 83fa03b9c8..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.i18n.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading -# section, a hash of its English and Chinese blocks outside code blocks and generated regions. -# After editing either side, bring the other along and re-record with: -# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md -/: - en: e4666ee6e813e7a3 - zh: ab68705b61d0da3c -/handle-agent-input-rejected-during-shutdown: - en: 5ec42a6575141728 - zh: a5174b0e04526c58 -/handle-agent-input-rejected-during-shutdown/change: - en: def59fb50e36f026 - zh: 91e79aad0ea758ad -/handle-agent-input-rejected-during-shutdown/migration: - en: e4c7ffd0e06c01bf - zh: 7fc1f43747209fb7 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md deleted file mode 100644 index 7aaff2efc6..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -kind: upgrade-guide -description: "Agent input and maintenance methods throw AgentClosedError once the Agent stops accepting new work." ---- - -# Handle Agent input rejected during shutdown - -English | [中文](guide.zh.md) - -## Change - -In v0.2.2-rc.1, a retained `Agent` could accept input while teardown was in progress. The Agent now rejects new input and maintenance work with `AgentClosedError` as soon as its lifetime is aborted. It can still appear in the registry while admitted work settles. - -## Migration - -1. In extensions that call `Agent.send`, `followup`, `steer`, `inject`, or `runMaintenance`, handle the synchronous `AgentClosedError` from `@deepseek-ai/dsh-agent` at the call site. Treat code `AGENT_CLOSED` as an unavailable Agent and preserve handling for other failures. -2. Verify by disposing an Agent with a maintenance task still settling. A subsequent input call throws `AgentClosedError` without adding an inbox entry. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md deleted file mode 100644 index 9ee1eb17a1..0000000000 --- a/docs/upgrade-guide/v0.2.2-rc.1/agent-closed-admission/guide.zh.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -kind: upgrade-guide -description: "Agent 停止接纳新工作后,输入和维护方法会抛出 AgentClosedError。" ---- - -# 处理关闭期间被拒绝的 Agent 输入 - -[English](guide.md) | 中文 - -## 变更 - -在 v0.2.2-rc.1 中,调用方持有的 `Agent` 在清理过程中仍可能接收输入。现在,Agent 的生命周期信号一旦中止,就会以 `AgentClosedError` 拒绝新输入和维护工作。已接纳的工作收尾期间,注册表中仍可能找到该 Agent。 - -## 迁移 - -1. 若扩展调用 `Agent.send`、`followup`、`steer`、`inject` 或 `runMaintenance`,请在调用处处理从 `@deepseek-ai/dsh-agent` 导出的同步异常 `AgentClosedError`。收到 `AGENT_CLOSED` 时按 Agent 不可用处理,保留其他失败的处理逻辑。 -2. 在维护任务尚未结束时开始释放 Agent 以验证改动。之后调用输入方法应抛出 `AgentClosedError`,且不向 inbox 添加条目。 diff --git a/packages/core/agent-loop/README.i18n.yaml b/packages/core/agent-loop/README.i18n.yaml index ed707355b5..253c4536e4 100644 --- a/packages/core/agent-loop/README.i18n.yaml +++ b/packages/core/agent-loop/README.i18n.yaml @@ -39,8 +39,8 @@ en: ec2bf804bd1a5439 zh: 316e767507e859ef /deepseek-ai-dsh-agent-loop/understand-the-implementation/creation-and-teardown: - en: e66e878db8193219 - zh: 11a79267958b2f51 + en: 4a10108fb0d37732 + zh: cc3be0eb8f00901c /deepseek-ai-dsh-agent-loop/understand-the-implementation/persistence-integration: en: 3b48a480036bd5df zh: 28cea2036b0dccee diff --git a/packages/core/agent-loop/README.md b/packages/core/agent-loop/README.md index d681ed5ac4..30443d6ace 100644 --- a/packages/core/agent-loop/README.md +++ b/packages/core/agent-loop/README.md @@ -109,7 +109,7 @@ The loop deep-freezes each derived message identity on its first request and reu Fresh creation and resume share one rollback-covered initialization: construct the concrete agent and scoped context around the acquired Session; store constructor history, enter the SessionStore, and complete `session/created`; await optional setup and its commit; enter the AgentRegistry; await serial `agent/created` listeners; then release queued input. The caller Context owns the transaction and live handle; delegation services bind their runtime relationships during setup. Setup, commit, or listener failure and owner disposal roll back the prepared resources. The Session is writable during setup, and every removal emits `session/disposed`, including setup failure before Agent creation is announced. Failed initialization preserves restored inbox input and any events already stored; it rejects only after releasing its scope and acquired write handle. Cancellation while persistence is still creating a write handle can reject earlier; that handle closes when creation settles. Announcements already delivered remain observable and receive matching disposal notifications. Teardown stops and drains the driver, unwinds the scope, closes the session's write path, detaches the agent, then detaches the session. Every detach binds the exact entered object, so a stale disposer cannot remove a later same-id replacement. -The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. New input is rejected when teardown begins; queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles. +The loop awaits its required registrations before publishing its factory. It calls `readerFor(session)` on its model-selection and inbox handles and passes the callbacks to the driver in one typed object; the model and inbox collaborators receive their respective callbacks. During factory unload, global registrations may disappear before teardown finishes; retained handles remain readable through scope cleanup, including cancellation from scoped abort listeners. Caller unload, factory unload, and handle disposal await the same teardown. Queue-clear errors do not skip cancellation or the wait for admitted work, and resources remain available until that work settles. ### Persistence integration diff --git a/packages/core/agent-loop/README.zh.md b/packages/core/agent-loop/README.zh.md index 50ee3a1475..e20aa96f37 100644 --- a/packages/core/agent-loop/README.zh.md +++ b/packages/core/agent-loop/README.zh.md @@ -109,7 +109,7 @@ const handle = await ctx.agents.create({ 新建和恢复共用一个受回滚保护的初始化流程:围绕已取得的 Session 构造具象 agent 与带作用域上下文;存储构造历史、进入 SessionStore 并完成 `session/created`;等待可选 setup 及其 commit;进入 AgentRegistry;等待串行 `agent/created` 监听器;随后释放已排队输入。调用方 Context 拥有事务和存活句柄;委派服务在 setup 期间绑定自己的运行时关系。Setup、commit、监听器失败或所有者 dispose 都会回滚已准备的资源。setup 期间 Session 可写;每次移除都会发出 `session/disposed`,包括 Agent 创建宣告前的 setup 失败。初始化失败保留恢复出的收件箱输入及已存储事件,并在释放自身作用域及已取得的写句柄后才拒绝。持久化层仍在创建写句柄时发生取消,可以更早拒绝;该句柄在创建完成后关闭。已送达的宣告仍可被观察,并有配对的销毁通知。Teardown 停止并排空驱动器、撤销作用域、关闭会话写路径、detach agent,再 detach 会话。每次 detach 都绑定到确切进入的对象,因此陈旧 disposer 无法移除之后出现的同 id 替代项。 -loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。teardown 开始后拒绝新输入;清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。 +loop 在发布工厂前等待必需的注册完成。它对模型选择和 inbox 句柄调用 `readerFor(session)`,将读取回调放入一个类型化对象传给驱动器;模型和 inbox 小组件接收各自的回调。工厂卸载时,全局注册可以先于 teardown 完成而消失;保留句柄在整个作用域清理期间仍可读取,包括作用域内 abort 监听器发起取消的时刻。调用方卸载、工厂卸载和句柄释放等待同一次 teardown。清队列错误不会跳过取消或等待已接纳工作,资源会保留到该工作结束。 ### 持久化集成 diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 95c27e6c92..58b1930241 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -18,7 +18,7 @@ import type { PreStepDecision, RequestErrorAction, } from '@deepseek-ai/dsh-agent' -import { AgentClosedError, AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' +import { AgentModel, agentEvents, assembleContextFor } from '@deepseek-ai/dsh-agent' import type { GenerateOptions, LlmCallConfig, Message, PreparedLlmCall } from '@deepseek-ai/dsh-llm' import { LlmError, @@ -141,14 +141,13 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, projections: LoopProjections, lastTurn: number, - private readonly lifetimeSignal: AbortSignal, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) this.scope = createScope(loopCtx, this) this.ctx = this.scope.ctx this.model = new AgentModel(projections.modelSelection, session, options) - this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch, () => { this.assertOpen() }) + this.inbox = new ReactLoopInbox(projections.inbox, session, this.dispatch) this.phase = { kind: 'idle', lastTurn } this.runtimeContext = new RuntimeContextProjection(this.ctx, session) this.systemPrompt = new SystemPromptProjection(session) @@ -169,7 +168,6 @@ export class ReactLoopAgent implements Agent { } send(message: UserMessage, target: InboxTarget, wakeup: boolean): void { - this.assertOpen() // Waking input cannot join an aborted activity, so it starts the next turn. // Captured before the insertion so a reentrant cancel from a splice observer cannot reclassify it. const wakingAfterAbort = wakeup && this.phase.kind !== 'idle' && this.phase.abort.signal.aborted @@ -203,7 +201,6 @@ export class ReactLoopAgent implements Agent { } runMaintenance(job: (signal: AbortSignal) => Promise): Promise { - this.assertOpen() if (this.phase.kind !== 'idle') throw new Error(`agent "${this.id}" already has active work`) const done = Promise.withResolvers() const maintenance: Phase = { @@ -235,7 +232,6 @@ export class ReactLoopAgent implements Agent { * the inbox insertion so a reentrant cancel cannot reclassify it. */ private wakeDriver(wakeAfterAbort = false): void { - if (this.lifetimeSignal.aborted) return if (this.phase.kind !== 'idle') { // Maintenance and aborted drivers cannot deliver the wake: latch it for // replay at convergence. Live drivers claim queued work themselves; @@ -265,12 +261,6 @@ export class ReactLoopAgent implements Agent { } while (activity !== this.activityDone) } - private assertOpen(): void { - if (this.lifetimeSignal.aborted) { - throw new AgentClosedError(this.id, { cause: this.lifetimeSignal.reason }) - } - } - /** Report one failure at its live boundary, then preserve it for driver containment. */ private throwError(error: unknown): never { const turn = this.phase.kind === 'running' ? this.phase.turn : this.phase.lastTurn @@ -606,13 +596,13 @@ export class ReactLoopAgent implements Agent { maxParallelToolCalls, toolSet: decision.toolSet, }) for (const context of result.additionalContexts) { - this.inbox.retainContext(context) + this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) } return result.concluded ? { kind: 'completed' } : null } catch (error: unknown) { if (!(error instanceof ToolBatchExecutionError)) throw error for (const context of error.partial.additionalContexts) { - this.inbox.retainContext(context) + this.inbox.splice('next-step', this.inbox.nextStep.length, 0, [context]) } throw error.cause } diff --git a/packages/core/agent-loop/src/inbox.ts b/packages/core/agent-loop/src/inbox.ts index 8972667b10..affe0c6b2f 100644 --- a/packages/core/agent-loop/src/inbox.ts +++ b/packages/core/agent-loop/src/inbox.ts @@ -69,14 +69,12 @@ export const inboxProjectionDefinition = { * @param readState - reader for the live Inbox projection state. * @param session - session whose durable events store pending input. * @param dispatch - agent-scoped notifications for Inbox lifecycle events. - * @param assertAdmission - rejects public insertions and replacements after admission closes. */ export class ReactLoopInbox implements InboxContract { constructor( private readonly readState: () => InboxState, private readonly session: Session, private readonly dispatch: AgentEventDispatch, - private readonly assertAdmission: () => void = () => {}, ) {} /** Prompts awaiting individual turns. */ @@ -139,7 +137,6 @@ export class ReactLoopInbox implements InboxContract { * @returns whether the message was still pending. */ replace(messageId: MessageId, newMessage: UserMessage): boolean { - this.assertAdmission() const location = this.locate(messageId) if (location === undefined) return false this.splice(location.target, location.index, 1, [newMessage]) @@ -172,18 +169,9 @@ export class ReactLoopInbox implements InboxContract { deleteCount: number, inserted: UserMessage[], ): UserMessage[] { - if (inserted.length > 0) this.assertAdmission() return this.mutate(target, start, deleteCount, inserted, true) } - /** - * Retain context finalized by admitted work, including during shutdown. - * @param message - context produced by the active driver. - */ - retainContext(message: UserMessage): void { - this.mutate('next-step', this.nextStep.length, 0, [message], true) - } - /** Locate one pending identity across both owned lists. */ private locate(messageId: MessageId): { target: InboxTarget; index: number } | undefined { const state = this.readState() diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index ecdafadb9d..3277d9fb83 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -575,7 +575,6 @@ export class AgentLoop extends Service implements AgentFactory { loopCtx, id, agentOptions, session, projections, lastTurn, - abort.signal, ) machineReady.resolve() // Adopt the scope on its original fiber so it cannot unload before teardown. diff --git a/packages/core/agent-loop/tests/cancel.spec.ts b/packages/core/agent-loop/tests/cancel.spec.ts index 434857afe9..5bb1d828da 100644 --- a/packages/core/agent-loop/tests/cancel.spec.ts +++ b/packages/core/agent-loop/tests/cancel.spec.ts @@ -16,7 +16,7 @@ import SessionStore, { Session, SessionId, SessionLogOffset, TurnEndReason } fro import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRuntime, { TOOL_ABORTED_BEFORE_DISPATCH } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' -import AgentRegistry, { AgentClosedError, type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { type Agent, type AgentCancelCause } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import { MockAdapter, textResponse, toolCallResponse } from './mock-adapter.ts' @@ -324,7 +324,7 @@ describe('Agent.cancel()', () => { send(agent, 'active') await streaming.promise const disposal = handle.dispose() - expect(() => { send(agent, 'late wake') }).toThrow(AgentClosedError) + send(agent, 'late wake') await disposal expect(adapter.requests).toHaveLength(1) diff --git a/packages/core/agent-loop/tests/input-lifecycle.spec.ts b/packages/core/agent-loop/tests/input-lifecycle.spec.ts index 3e9bb2cf10..0ce7898bb2 100644 --- a/packages/core/agent-loop/tests/input-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/input-lifecycle.spec.ts @@ -4,9 +4,9 @@ import { mkdtemp, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' -import AgentRegistry, { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' -import LlmRuntime, { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' +import LlmRuntime, { createUserMessage } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as JsonlSessionPersistence from '@deepseek-ai/dsh-session-persistence-jsonl' @@ -82,41 +82,6 @@ it('cancellation still aborts the running request when queue clearing fails', as } }) -it('an Agent still in the registry rejects new input while its owner is closing', async () => { - const { ctx, agent, handle } = await harness() - const release = Promise.withResolvers() - const aborted = Promise.withResolvers() - const work = agent.runMaintenance(async (signal) => { - signal.addEventListener('abort', () => { aborted.resolve(undefined) }, { once: true }) - await release.promise - }) - const closing = handle.dispose() - try { - await aborted.promise - expect(ctx.agents.get(agent.id)).toBe(agent) - const message = input('during closing') - const error = vi.fn((failure: unknown) => failure) - try { - agent.followup(message) - } catch (failure) { - error(failure) - } - expect(error).toHaveBeenCalledWith(expect.objectContaining({ - name: 'AgentClosedError', code: 'AGENT_CLOSED', agentId: agent.id, - })) - expect(error.mock.calls[0]?.[0]).toBeInstanceOf(HarnessError) - for (const submit of [() => { agent.followup(message) }, () => { agent.steer(message) }, () => { agent.inject(message) }, () => { agent.send(message, 'next-turn', true) }, () => agent.runMaintenance(async () => {}), () => { agent.inbox.append('next-turn', message) }, () => { agent.inbox.prepend('next-step', message) }, () => agent.inbox.splice('next-turn', 0, 0, [message]), () => agent.inbox.replace(message.id, message)]) { - expect(submit).toThrow(AgentClosedError) - } - const pending = [...agent.inbox.nextTurn, ...agent.inbox.nextStep].some(entry => entry.id === message.id) - expect(pending).toBe(false) - } finally { - release.resolve(undefined) - await work - await closing - } -}) - it('waits for admitted maintenance after a queue-clear failure before releasing its Session', async () => { const { ctx, agent, handle } = await harness() const release = Promise.withResolvers() @@ -157,23 +122,6 @@ it('waits for admitted maintenance after a queue-clear failure before releasing } }) -it('does not start a driver when an inbox observer closes its owner during admission', async () => { - const { ctx, agent, handle, adapter } = await harness() - let closing: Promise | undefined - const stop = ctx.on('agent/inbox/inserted', ({ message }) => { - if (message.source.kind === 'user') closing = handle.dispose() - }) - try { - agent.followup(input('close during admission')) - expect(closing).toBeDefined() - await closing - expect(adapter.requests).toHaveLength(0) - } finally { - stop() - await closing - } -}) - it('reports a quiescence failure while releasing the Agent and Session', async () => { const { ctx, agent, handle } = await harness() const failure = new Error('injected quiescence failure') diff --git a/packages/core/agent-loop/tests/request-freeze.spec.ts b/packages/core/agent-loop/tests/request-freeze.spec.ts index f4ef29eea3..8ed1c4d138 100644 --- a/packages/core/agent-loop/tests/request-freeze.spec.ts +++ b/packages/core/agent-loop/tests/request-freeze.spec.ts @@ -79,8 +79,7 @@ describe('loop-owned request freezing', () => { const inbox = await loopCtx.sessionProjections.register(inboxProjectionDefinition) const model = await loopCtx.sessionProjections.register(modelSelectionProjectionDefinition) const agent = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, - new AbortController().signal) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) cleanups.push(async () => { agent.cancel({ kind: 'disposed' }) await agent.whenIdle() @@ -130,8 +129,7 @@ describe('loop-owned request freezing', () => { expect(freeze.mock.calls.filter(([value]) => value === userEvent.data)).toHaveLength(1) expect(freeze.mock.calls.filter(([value]) => value === replacement.data)).toHaveLength(1) const resumed = new ReactLoopAgent(loopCtx, id, { provider: 'mock', model: 'mock' }, session, - { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn, - new AbortController().signal) + { modelSelection: model.readerFor(session), inbox: inbox.readerFor(session) }, ctx.agents.turnBoundaryOf(session).lastTurn) cleanups.push(async () => { resumed.cancel({ kind: 'disposed' }) await resumed.whenIdle() diff --git a/packages/core/agent/README.i18n.yaml b/packages/core/agent/README.i18n.yaml index 6c21a72d7d..46e9eb2a5a 100644 --- a/packages/core/agent/README.i18n.yaml +++ b/packages/core/agent/README.i18n.yaml @@ -24,11 +24,11 @@ en: 85b0ff72a187110f zh: 3f61c1568d27b8bc /deepseek-ai-dsh-agent/use-this-package/drive-an-agent-s-conversation: - en: ff2b530bb20bcfe2 - zh: 4f9024c4881a4ba5 + en: 8dcb90a344e7ef2c + zh: d48f07379f4674d6 /deepseek-ai-dsh-agent/use-this-package/scope-registrations-to-one-agent: - en: cec57f2cb7ab3a5c - zh: 2896b42eb5310441 + en: 2594a1e02adea801 + zh: cae8860369728efb /deepseek-ai-dsh-agent/use-this-package/intercept-or-observe-work-in-flight: en: 371511fb13093dd2 zh: 4be81d246cf299b2 diff --git a/packages/core/agent/README.md b/packages/core/agent/README.md index 024f69aeef..c7ff87b6d0 100644 --- a/packages/core/agent/README.md +++ b/packages/core/agent/README.md @@ -55,7 +55,7 @@ For scoped switch notices, call `installModelSelection(agentCtx)` from `dsh-agen ### Drive an agent's conversation -The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. Disposal rejects new input and maintenance with `AgentClosedError` before mutation. A queue-write failure during cancellation still aborts active work and propagates to the caller. +The handle's methods route identified user-role messages into the agent's inbox. `followup()` queues an ordinary next-turn prompt and wakes the driver; `steer()` submits next-step input and wakes it; `inject()` adds model-facing context without waking the driver, so it lands in the next admitted step. `cancel(cause)` aborts the active activity and, unless `keepInbox` is set, clears pending work; `whenIdle()` resolves after the whole agent reaches quiescence. A queue-write failure during cancellation still aborts active work and propagates to the caller. ```text handle.agent.followup({ @@ -73,8 +73,6 @@ await handle.agent.whenIdle() `Agent.ctx` is the agent's scoped context: registrations made through it (tools, prompt sections, variables, event listeners, restrictions) apply to that agent alone and unwind on disposal. The same mechanism is what agent presets use to give one session a different capability set without affecting its neighbors. -Input and maintenance methods reject closed Agents with `AgentClosedError` (`AGENT_CLOSED`). See [Agent lifetime and admission](../../../docs/subsystems/core.md#the-agent-handle) for the lifecycle rules. - ### Intercept or observe work in flight `agent/request` is deprecated and retained for existing listeners. Do not add new listeners. Provider, model, and optional explicit reasoning effort are fixed at step preparation; listeners must preserve all three, including an absent effort. `AgentOptions.maxTokens` sets the output cap. Other per-request control overrides have no replacement API. See the [migration guide](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.md) for affected callers. diff --git a/packages/core/agent/README.zh.md b/packages/core/agent/README.zh.md index 693ad615ce..98cda69819 100644 --- a/packages/core/agent/README.zh.md +++ b/packages/core/agent/README.zh.md @@ -55,7 +55,7 @@ await handle.dispose() // stops the loop, unregisters, removes the session, un ### 驱动 agent 的对话 -句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。释放开始后,新输入和维护任务会在修改状态前抛出 `AgentClosedError`。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。 +句柄的方法把带标识的 user 角色消息路由进 agent 的收件箱。`followup()` 排队一条普通的下一个轮次提示词并唤醒驱动器;`steer()` 提交下一步输入并唤醒它;`inject()` 添加面向模型的上下文但不唤醒驱动器,因此它落在下一个被接纳的步骤中。`cancel(cause)` 中止当前活动,并在未设置 `keepInbox` 时清除待处理工作;`whenIdle()` 会在整个 agent 达到完全停稳后完成。取消期间的队列写入失败仍会中止当前工作,并把错误传给调用方。 ```text handle.agent.followup({ @@ -73,8 +73,6 @@ await handle.agent.whenIdle() `Agent.ctx` 是该 agent 的作用域上下文:通过它进行的注册(工具、提示词段、变量、事件监听器、限制)只对该 agent 生效,并在 dispose(资源释放)时全部撤销。同一机制也是 agent preset 用来让一个会话获得不同能力集、同时不影响其邻居的方式。 -输入和维护方法会以 `AgentClosedError`(`AGENT_CLOSED`)拒绝已停止接纳新工作的 Agent。生命周期规则见 [Agent 句柄](../../../docs/subsystems/core.zh.md#the-agent-handle)。 - ### 拦截或观察进行中的工作 `agent/request` 已弃用,仅为现有监听器保留。不要添加新监听器。提供方、模型和可选的显式推理强度在步骤准备时固定;监听器必须保留三者,包括未指定强度的状态。`AgentOptions.maxTokens` 设置输出上限。其他逐请求控制参数覆盖没有替代 API。受影响的调用方参见[迁移指南](../../../docs/upgrade-guide/v0.2.1-alpha.4/session-model-selection/guide.zh.md)。 diff --git a/packages/core/agent/src/closed-error.ts b/packages/core/agent/src/closed-error.ts deleted file mode 100644 index a4ca452887..0000000000 --- a/packages/core/agent/src/closed-error.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** Rejection of new work after an Agent starts closing. @module @deepseek-ai/dsh-agent/closed-error */ - -import { HarnessError } from '@deepseek-ai/dsh-llm' -import type { SessionId } from '@deepseek-ai/dsh-session' - -/** An Agent has stopped accepting new input and maintenance work (`AGENT_CLOSED`). */ -export class AgentClosedError extends HarnessError { - /** - * @param agentId - closing Agent identity. - * @param options - original lifecycle cancellation, when available. - */ - constructor(readonly agentId: SessionId, options?: ErrorOptions) { - super(`agent "${agentId}" is closing`, 'AGENT_CLOSED', options) - } -} diff --git a/packages/core/agent/src/index.ts b/packages/core/agent/src/index.ts index 35fbdd6b1d..374be30180 100644 --- a/packages/core/agent/src/index.ts +++ b/packages/core/agent/src/index.ts @@ -19,7 +19,6 @@ import type { AgentOptions, SessionStartSource } from './runtime-types.ts' import { turnBoundaryProjectionDefinition } from './projection.ts' export * from './runtime-types.ts' -export { AgentClosedError } from './closed-error.ts' export * from './types.ts' export { AgentModel, modelSelectionProjectionDefinition, installModelSelection } from './model-selection.ts' export type { ModelSelectionProjectionState } from './model-selection.ts' diff --git a/packages/core/agent/src/runtime-types.ts b/packages/core/agent/src/runtime-types.ts index 39b15064dc..7012dfdf50 100644 --- a/packages/core/agent/src/runtime-types.ts +++ b/packages/core/agent/src/runtime-types.ts @@ -226,7 +226,7 @@ declare module './types.ts' { * inbox until the task settles, while public status stays `idle`. * `whenIdle()` follows both the task and any waking work released behind it. * @param task - operation whose fulfillment or rejection is preserved, with a signal aborted by {@link cancel}. - * @throws AgentClosedError once the Agent lifetime is aborted, or an Error when another activity owns the agent. + * @throws synchronously when turn-driving or another maintenance task already owns the agent. * @returns the task promise. */ runMaintenance(task: (signal: AbortSignal) => Promise): Promise @@ -241,7 +241,6 @@ declare module './types.ts' { * @param message - identified content and the source that supplied it. * @param target - the preferred next-turn or next-step inbox boundary. * @param wakeup - whether delivery may wake the driver. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ send(message: UserMessage, target: InboxTarget, wakeup: boolean): void @@ -249,7 +248,6 @@ declare module './types.ts' { * Queue an ordinary follow-up turn and wake the driver. The item becomes the * sole ordinary message of its own turn. * @param message - identified prompt content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ followup(message: UserMessage): void @@ -259,7 +257,6 @@ declare module './types.ts' { * A rejected step leaves steering parked in the inbox until the next * wake; cancellation or disposal may discard pending steering. * @param message - identified steering content and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ steer(message: UserMessage): void @@ -270,7 +267,6 @@ declare module './types.ts' { * wakes them. It may miss a request whose pre-step already claimed its * batch. Cancellation or disposal may discard pending context. * @param message - identified injected context and the source that supplied it. - * @throws AgentClosedError once the Agent lifetime is aborted. The inbox is unchanged. */ inject(message: UserMessage): void } diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 14f663e5c4..74a5703129 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -402,7 +402,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ methods: [ { signature: 'setPolicy(agent: Agent, policy: ApprovalPolicy): void', - description: 'Persist a live Agent\'s policy. Queue the switch notice for the next model step while the Agent accepts input. Session initialization uses setApprovalPolicy directly.', + description: 'Switch one live agent\'s policy and queue the transition for its next model step. Session initialization uses setApprovalPolicy directly because there is no previously visible policy to change.', parameters: [{ name: 'agent', description: 'the live agent whose policy is changing.' }, { name: 'policy', description: 'the new effective policy.' }], }, { diff --git a/packages/goal/command-goal/README.i18n.yaml b/packages/goal/command-goal/README.i18n.yaml index 31c0717abf..9efbb3b229 100644 --- a/packages/goal/command-goal/README.i18n.yaml +++ b/packages/goal/command-goal/README.i18n.yaml @@ -24,8 +24,8 @@ en: 38a273cb14017e13 zh: d4b7b501bcd9589b /deepseek-ai-dsh-command-goal/use-this-package/attachments: - en: 742010a31542e6a2 - zh: 10f18b79b0d14f7c + en: e61cd7437ed4aa73 + zh: 552c36c3b8d16007 /deepseek-ai-dsh-command-goal/use-this-package/compose-it: en: ba5792bd8714f1c3 zh: c9e5500c0a3b7651 diff --git a/packages/goal/command-goal/README.md b/packages/goal/command-goal/README.md index da56e8b885..a627a15e82 100644 --- a/packages/goal/command-goal/README.md +++ b/packages/goal/command-goal/README.md @@ -46,7 +46,7 @@ Control words (`clear`, `pause`, `resume`, `edit`) are recognized only when they ### Attachments -`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. If the Agent rejects attachment submission with `AGENT_CLOSED` after the objective is saved, the command reports the saved objective and leaves the attachments in the composer. +`/goal` declares attachment support. Attachments accompany only an objective: after a successful create or edit, the command submits one user followup carrying the admitted image and file blocks in selection order plus the fixed text `Reference attachments for the goal objective.` Later goal rounds read that ordinary session history; the goal domain stores no attachment state. Every other sub-command, and any refused create or edit, returns a direct error before a domain mutation and leaves the dispatching composer's draft and cards intact. ### Compose it diff --git a/packages/goal/command-goal/README.zh.md b/packages/goal/command-goal/README.zh.md index e27c6490c5..9e4bac63d9 100644 --- a/packages/goal/command-goal/README.zh.md +++ b/packages/goal/command-goal/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" ### 附件 -`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 如果目标已保存,随后 Agent 以 `AGENT_CLOSED` 拒绝附件提交,命令会提示目标已保存,并将附件保留在输入区。 +`/goal` 声明附件支持。附件只随目标本身:create 或 edit 成功后,命令提交一条用户 followup 消息,按选择顺序携带已准入的图片块与文件块,再附加固定文本 `Reference attachments for the goal objective.`。后续 Goal Round 从普通会话历史读取这些内容,goal 领域不存储附件状态。其他任何子命令以及被拒绝的 create 或 edit,都会在领域变更前返回直接错误,并保留 composer 的草稿和附件卡。 ### 组合方式 diff --git a/packages/goal/command-goal/src/index.ts b/packages/goal/command-goal/src/index.ts index da449fb5db..9238d76632 100644 --- a/packages/goal/command-goal/src/index.ts +++ b/packages/goal/command-goal/src/index.ts @@ -8,7 +8,7 @@ import { CommandDefinitionId } from '@deepseek-ai/dsh-commands/brand' import type { CommandInvocation, CommandResult } from '@deepseek-ai/dsh-commands' import { GoalError } from '@deepseek-ai/dsh-goal' import type { GoalPhase, GoalRef, GoalView } from '@deepseek-ai/dsh-goal' -import { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage } from '@deepseek-ai/dsh-llm' export const name = 'command-goal' export const inject = ['commands', 'goals'] @@ -109,25 +109,17 @@ function missingGoal(action: string): CommandResult { } /** - * Report the committed objective and submit its attachments ahead of the next goal round. - * A closed Agent leaves the objective saved and the attachments in the composer. + * Submit the invocation's admitted composer attachments as one model-visible user + * message ahead of the goal's next round. The attachments precede a fixed text + * block naming their role, so a later goal round reads them from ordinary + * session history without the goal domain storing attachment state. */ -function finishObjective(invocation: CommandInvocation, title: string, goal: GoalView): CommandResult { - if (invocation.attachments.length > 0) { - try { - invocation.agent.followup(createUserMessage({ - content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], - source: { kind: 'user' }, - })) - } catch (error: unknown) { - if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error - return { - kind: 'error', - text: 'Goal saved. The agent is closing, so the attachments were not submitted.', - } - } - } - return renderGoal(title, goal) +function submitObjectiveAttachments(invocation: CommandInvocation): void { + if (invocation.attachments.length === 0) return + invocation.agent.followup(createUserMessage({ + content: [...invocation.attachments, { type: 'text', text: 'Reference attachments for the goal objective.' }], + source: { kind: 'user' }, + })) } /** Execute one parsed human command through the domain that owns persistence. */ @@ -156,16 +148,19 @@ function executeGoalCommand(ctx: Context, invocation: CommandInvocation): Comman } } const created = ctx.goals.create(invocation.agent, { objective: command.objective }) - return finishObjective(invocation, 'Goal created', created) + submitObjectiveAttachments(invocation) + return renderGoal('Goal created', created) } case 'edit': { if (current === undefined) return missingGoal('edit') if (current.phase === 'complete') { const replaced = ctx.goals.create(invocation.agent, { objective: command.objective }) - return finishObjective(invocation, 'Goal created', replaced) + submitObjectiveAttachments(invocation) + return renderGoal('Goal created', replaced) } const edited = ctx.goals.edit(invocation.agent, goalRef(current), { objective: command.objective }) - return finishObjective(invocation, 'Goal updated', edited) + submitObjectiveAttachments(invocation) + return renderGoal('Goal updated', edited) } case 'pause': if (current === undefined) return missingGoal('pause') diff --git a/packages/goal/command-goal/tests/command-goal.spec.ts b/packages/goal/command-goal/tests/command-goal.spec.ts index e7c02e487d..6cb4cf83c9 100644 --- a/packages/goal/command-goal/tests/command-goal.spec.ts +++ b/packages/goal/command-goal/tests/command-goal.spec.ts @@ -1,12 +1,11 @@ import { describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import Loader from '@deepseek-ai/cordis-plugin-loader' -import AgentRegistry, { AgentClosedError } from '@deepseek-ai/dsh-agent' +import AgentRegistry from '@deepseek-ai/dsh-agent' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import CommandRuntime from '@deepseek-ai/dsh-commands' import GoalService from '@deepseek-ai/dsh-goal' import type { GoalRef } from '@deepseek-ai/dsh-goal' -import { HarnessError } from '@deepseek-ai/dsh-llm' import SessionStore, { Session, SessionId, type SessionEvent } from '@deepseek-ai/dsh-session' import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' import * as commandGoal from '@deepseek-ai/dsh-command-goal' @@ -318,44 +317,6 @@ describe('/goal attachments', () => { expect(followup).toHaveBeenCalledTimes(1) }) - it.each(['create', 'edit'] as const)('reports the saved objective when a closing Agent rejects attachments on %s', async (operation) => { - const test = await harness() - provideStore(test) - if (operation === 'edit') test.ctx.goals.create(test.agent, { objective: 'original objective' }) - const failure = new AgentClosedError(test.agent.id) - vi.spyOn(test.agent, 'followup').mockImplementation(() => { throw failure }) - const suffix = operation === 'edit' ? ' edit use the reference image' : ' use the reference image' - try { - const result = await runWithAttachments(test, suffix) - expect(result).toEqual({ - kind: 'error', - text: 'Goal saved. The agent is closing, so the attachments were not submitted.', - }) - expect(test.ctx.goals.get(test.agent)?.objective).toBe('use the reference image') - expect(test.session.snapshotEvents().at(-1)).toMatchObject({ - type: 'command/done', - data: result, - }) - expect(test.agent.inbox.nextTurn).toEqual([]) - } finally { - await test.ctx.fiber.dispose() - } - }) - - it.each([ - new Error('inbox write failed'), - new HarnessError('another typed failure', 'ATTACHMENT_TEST_FAILURE'), - ])('propagates unrelated attachment delivery failure %s', async (failure) => { - const test = await harness() - provideStore(test) - vi.spyOn(test.agent, 'followup').mockImplementation(() => { throw failure }) - try { - await expect(runWithAttachments(test, ' use the reference image')).rejects.toBe(failure) - } finally { - await test.ctx.fiber.dispose() - } - }) - it('rejects attachments on sub-commands that cannot use them, leaving the domain untouched', async () => { const test = await harness() provideStore(test) diff --git a/packages/goal/goal-round-driver/README.i18n.yaml b/packages/goal/goal-round-driver/README.i18n.yaml index 18af868300..19e3ebc68a 100644 --- a/packages/goal/goal-round-driver/README.i18n.yaml +++ b/packages/goal/goal-round-driver/README.i18n.yaml @@ -24,8 +24,8 @@ en: a1312339977f1127 zh: 57450327ff7e7d83 /deepseek-ai-dsh-goal-round-driver/use-this-package/when-continuation-stops: - en: 7c4d150d79e55ba4 - zh: be24cd1956894787 + en: f3cb23a11176dc4f + zh: de7aa54d5c93445d /deepseek-ai-dsh-goal-round-driver/use-this-package/after-resume-fork-or-unload: en: 85d5470b1b330330 zh: e761f9046ba7af8a diff --git a/packages/goal/goal-round-driver/README.md b/packages/goal/goal-round-driver/README.md index 2998c3f8fe..1302bc6fdc 100644 --- a/packages/goal/goal-round-driver/README.md +++ b/packages/goal/goal-round-driver/README.md @@ -50,7 +50,7 @@ With an exact live agent idle, an active armed goal, and remaining capacity, the ### When continuation stops -A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. If Agent shutdown rejects a queued round, the goal stays active. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. +A round starts only at whole-agent idle and, when the subagent service is loaded, only after the agent's progressing descendants settle; completion, pause, and blocking suppress continuation; a host-initiated pause also aborts the turn already running, while a model-initiated pause inside its own turn finishes normally. An edit only invalidates an in-flight round through the revision fence, and the driver continues the new revision. The driver also stops on its own when a turn ends on max tokens, a durability write fails, the agent is cancelled, the plugin unloads, or the round cap is exhausted — at the cap it records a blocker with the stable code `round-limit`. Cancellation never auto-restarts a round: a goal whose round was under way is paused at the next idle point, and a cancellation unrelated to a goal attempt only disarms continuation. Agent disposal, such as a graceful process shutdown or a reload of the plugin that owns the Agent, aborts the round with the `disposed` cause and only disarms continuation, so the goal stays active, as on plugin unload; user, parent, and hook cancellations still pause it. A round prompt still queued when the agent reaches idle is removed from the inbox, so later human input does not wait behind it; when the cancelled turn belonged to other work, continuation is disarmed rather than paused. ### After resume, fork, or unload diff --git a/packages/goal/goal-round-driver/README.zh.md b/packages/goal/goal-round-driver/README.zh.md index 65cc9c1b77..05905c7043 100644 --- a/packages/goal/goal-round-driver/README.zh.md +++ b/packages/goal/goal-round-driver/README.zh.md @@ -50,7 +50,7 @@ kind: "package-reference" ### 何时停止续行 -Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 关闭期间拒绝轮次入队时,goal 保持 active。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 +Round 只在整个 agent 进入 idle 时启动;加载了子 agent 服务时,还要等该 agent 仍在推进的后代全部结束后才启动;完成、暂停和阻塞会阻止续行;宿主发起的暂停还会中止正在运行的轮次,而模型在自己轮次内发起的暂停会正常结束。编辑只会通过修订栅栏使进行中的 Round 失效,驱动器会继续新修订。驱动器也会在以下情况自行停止:轮次因 max tokens 结束、持久性写入失败、agent 被取消、插件卸载,或 Round 上限耗尽——上限耗尽时它会以稳定代码 `round-limit` 记录一个 blocker。取消绝不会自动重启 Round:Round 已在进行的 goal 会在下一次 idle 时被暂停;与 goal 尝试无关的取消只会停用续行。Agent 被处置(例如进程正常关停,或重载拥有该 Agent 的插件)时,Round 以 `disposed` 原因中止,此时只停用续行,goal 保持 active,与插件卸载时一致;用户、父 Agent 与 hook 发起的取消仍会暂停它。agent 进入 idle 时仍在排队的 Round 提示会从收件箱移除,后续人类输入不会排在它后面等待;被取消的轮次属于其他工作时,续行会被停用而不是暂停。 ### resume、fork 或卸载之后 diff --git a/packages/goal/goal-round-driver/src/index.ts b/packages/goal/goal-round-driver/src/index.ts index 461a874f08..d3ddfda4cc 100644 --- a/packages/goal/goal-round-driver/src/index.ts +++ b/packages/goal/goal-round-driver/src/index.ts @@ -6,7 +6,7 @@ import { isDeepStrictEqual } from 'node:util' import { FiberState } from '@deepseek-ai/cordis' import type { Context } from '@deepseek-ai/cordis' -import { AgentClosedError, type Agent, type PreStepDecision } from '@deepseek-ai/dsh-agent' +import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' import type { GoalMessageSource, GoalRef, GoalView } from '@deepseek-ai/dsh-goal' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -208,7 +208,6 @@ export function apply(ctx: Context): void { agent.followup(message) } catch (error: unknown) { state.attempt = undefined - if (error instanceof AgentClosedError) return ctx.logger.warn(`goal-round-driver: could not queue round ${round} for agent "${agent.id}": ${renderThrown(error)}`) const latest = currentGoal(state) if (latest !== undefined && latest.id === goal.id && latest.revision === goal.revision diff --git a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts index 35b2d0c3ee..d9f97df07d 100644 --- a/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts +++ b/packages/goal/goal-round-driver/tests/goal-round-driver.spec.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { Context } from '@deepseek-ai/cordis' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' -import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' +import { agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import GoalService, { GoalId } from '@deepseek-ai/dsh-goal' @@ -727,20 +727,6 @@ describe('same-session goal driving', () => { expect(goal?.roundsStarted).toBe(1) }) - it('keeps the goal active when the Agent closes before queue admission', async () => { - const test = await harness([]) - const admission = Promise.withResolvers() - vi.spyOn(test.agent, 'followup').mockImplementation(() => { - admission.resolve(undefined) - throw new AgentClosedError(test.agent.id) - }) - test.ctx.goals.create(test.agent, { objective: 'resume after shutdown' }) - await admission.promise - - expect(test.ctx.goals.get(test.agent)).toMatchObject({ phase: 'active', roundsStarted: 0 }) - expect(test.agent.session.snapshotEvents().some(event => event.type === 'goal/change' && event.data.operation === 'block')).toBe(false) - }) - it('blocks the goal when a custom agent rejects the otherwise valid follow-up', async () => { const test = await harness([]) // Reject only the goal-sourced round follow-up, not the state-change injection diff --git a/packages/interaction/permission-presets/tests/projection.spec.ts b/packages/interaction/permission-presets/tests/projection.spec.ts index e2b2749f24..d1d98d7c66 100644 --- a/packages/interaction/permission-presets/tests/projection.spec.ts +++ b/packages/interaction/permission-presets/tests/projection.spec.ts @@ -14,7 +14,6 @@ import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deep import { Context } from '@deepseek-ai/cordis' import { SessionId } from '@deepseek-ai/dsh-session' import type { Session } from '@deepseek-ai/dsh-session' -import { AgentClosedError } from '@deepseek-ai/dsh-agent' import type { Agent } from '@deepseek-ai/dsh-agent' import { createScope } from '@deepseek-ai/dsh-scope' import CommandRuntime from '@deepseek-ai/dsh-commands' @@ -177,31 +176,6 @@ describe('/permission command', () => { expect(run?.data).toMatchObject({ name: 'permission', args: ' danger-full-access' }) }) - it('reports the saved preset when a closing Agent rejects its policy notice', async () => { - const { ctx, session } = await harness() - const { agent, inject } = await agentFor(ctx, session) - inject.mockImplementation(() => { throw new AgentClosedError(agent.id) }) - - const execution = await ctx.commands.execute(agent, '/permission danger-full-access', [], new AbortController().signal) - - expect(execution?.result).toEqual({ kind: 'success', text: 'preset danger-full-access' }) - expect(ctx.permissionPresets.current(session)).toBe('danger-full-access') - const events = session.snapshotEvents() - expect(events.findLast(event => event.type === 'sandbox/mode')?.data.mode).toBe('danger-full-access') - expect(events.findLast(event => event.type === 'approval/policy')?.data.policy).toBe('never') - expect(events.findLast(event => event.type === 'command/done')?.data.kind).toBe('success') - }) - - it('propagates an unexpected policy notice failure', async () => { - const { ctx, session } = await harness() - const { agent, inject } = await agentFor(ctx, session) - const failure = new Error('could not write policy notice') - inject.mockImplementation(() => { throw failure }) - - await expect(ctx.commands.execute(agent, '/permission danger-full-access', [], new AbortController().signal)) - .rejects.toBe(failure) - }) - it('reports the current preset and the table on bare invocation', async () => { const { ctx, session } = await harness() const { agent } = await agentFor(ctx, session) diff --git a/packages/interaction/user-approval/README.i18n.yaml b/packages/interaction/user-approval/README.i18n.yaml index 3420e02af8..d648bb92f3 100644 --- a/packages/interaction/user-approval/README.i18n.yaml +++ b/packages/interaction/user-approval/README.i18n.yaml @@ -21,8 +21,8 @@ en: 3618ddc3386e65f0 zh: d6c0ac91aae122bb /deepseek-ai-dsh-user-approval/use-this-package/setting-the-policy: - en: d6e8b94fb407947f - zh: b1a60a6ad2448eca + en: 79f3334a395b9368 + zh: 0c4026b505ee254a /deepseek-ai-dsh-user-approval/use-this-package/requesting-a-decision: en: dc465de82799bab0 zh: 51144cc77bb15689 @@ -39,8 +39,8 @@ en: 38c3646e45d3dddd zh: 3363dde8c786d6b2 /deepseek-ai-dsh-user-approval/understand-the-implementation/policy-and-the-runtime-context-snapshot: - en: afd007076c584667 - zh: f2951e0dbd01c6e6 + en: a1aa2178ce3a4b85 + zh: db06e4d2e8e259f1 /deepseek-ai-dsh-user-approval/understand-the-implementation/audit: en: 145530678bac5912 zh: a464effa3a29fce0 @@ -54,8 +54,8 @@ en: d23980f003b42fbb zh: 532f0174de5d87b5 /deepseek-ai-dsh-user-approval/model-experience/current-approval-policy-context/what-the-model-sees: - en: 59311269308fa32c - zh: d8b1bcae501c9903 + en: eb41f1a4972c07f5 + zh: 4264f408eb951951 /deepseek-ai-dsh-user-approval/model-experience/current-approval-policy-context/what-the-model-sees/ask-policy-contribution: en: b9f1262c97ec7568 zh: 8a6613695f896f70 diff --git a/packages/interaction/user-approval/README.md b/packages/interaction/user-approval/README.md index 35ef24b1ef..1ac2fce1d8 100644 --- a/packages/interaction/user-approval/README.md +++ b/packages/interaction/user-approval/README.md @@ -46,7 +46,7 @@ The effective policy is the one set for the session, falling back to the configu |---|---|---| | `policy` | `ask` | Default for sessions without an `approval/policy` override | -The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-user-approval) is the exhaustive source for every accepted field and its JSDoc. `setPolicy(agent, policy)` persists a live Agent's policy and queues the switch notice described under Model Experience while the Agent accepts input; `setApprovalPolicy(session, policy)` is the direct durable write path used by session initialization. +The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-user-approval) is the exhaustive source for every accepted field and its JSDoc. `setPolicy(agent, policy)` switches a live agent and queues the switch notice described under Model Experience for its next model step; `setApprovalPolicy(session, policy)` is the direct durable write path used by session initialization. ### Requesting a decision @@ -83,7 +83,7 @@ The private host-only `approvalState` projection stores the policy override and Service activation waits for projection registration and fails if registration fails. The service keeps the returned reader private. The host and registry own Session recovery; approval methods do not load history or call hydration from a synchronous read. See the [registration and recovery API](../../session/session-projection/README.md). Pending questions, answerers, and grants remain in the runtime. -The system-prompt contribution `approval:policy` states the complete current meaning of the effective policy — `ask` with its fail-closed consequence, or `never` with its non-escalation consequence — after retained history, so switching policy appends a new full snapshot instead of rewriting the stable request header. `setPolicy()` also injects a sourced user message announcing the change for the next step while the Agent accepts input. +The system-prompt contribution `approval:policy` states the complete current meaning of the effective policy — `ask` with its fail-closed consequence, or `never` with its non-escalation consequence — after retained history, so switching policy appends a new full snapshot instead of rewriting the stable request header. `setPolicy()` also injects a sourced user message announcing the change for the next step. ### Audit @@ -112,7 +112,7 @@ Read these pages when the package-level contract is not enough. They move from t #### What the model sees -The first request and each effective policy change append a full runtime-context snapshot after retained history. Under `ask`, the approval contribution states that configured answerers may be consulted and absence fails closed. Under `never`, it states the deterministic rejection and non-escalation consequence. Unchanged requests retain the earlier snapshot without adding another message. A live policy switch also queues a notice for the next model step while the Agent accepts input. +The first request and each effective policy change append a full runtime-context snapshot after retained history. Under `ask`, the approval contribution states that configured answerers may be consulted and absence fails closed. Under `never`, it states the deterministic rejection and non-escalation consequence. Unchanged requests retain the earlier snapshot without adding another message. When the user switches a live Session's policy, the next model step also receives a switch notice. ##### Ask-policy contribution diff --git a/packages/interaction/user-approval/README.zh.md b/packages/interaction/user-approval/README.zh.md index 3cbbc994b6..1dabd4bfe9 100644 --- a/packages/interaction/user-approval/README.zh.md +++ b/packages/interaction/user-approval/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" |---|---|---| | `policy` | `ask` | 没有 `approval/policy` 覆盖的会话的默认策略 | -生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-user-approval)是每个受支持字段及其 JSDoc 的穷尽式真源。`setPolicy(agent, policy)` 持久化运行中的 Agent 的策略,并在 Agent 仍接纳输入时为下一个模型步骤排队一条模型体验一节所述的切换通知;`setApprovalPolicy(session, policy)` 是会话初始化使用的直接持久写入路径。 +生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-user-approval)是每个受支持字段及其 JSDoc 的穷尽式真源。`setPolicy(agent, policy)` 切换运行中的 agent 的策略,并为它的下一个模型步骤排队一条模型体验一节所述的切换通知;`setApprovalPolicy(session, policy)` 是会话初始化使用的直接持久写入路径。 ### 请求决定 @@ -83,7 +83,7 @@ kind: "package-reference" 服务激活会等待 Projection 注册完成;注册失败会使激活失败。服务私有持有返回的读取句柄。宿主和注册表负责会话恢复;审批方法不会在同步读取时加载历史或调用 hydration。参见[注册与恢复 API](../../session/session-projection/README.zh.md)。待处理问题、应答者和授权仍由运行时负责。 -系统提示词贡献 `approval:policy` 在保留历史之后陈述有效策略的完整当前含义——`ask` 及其以拒绝方式关闭的后果,或 `never` 及其非升权后果——因此切换策略会追加一份新的完整快照,而不会改写稳定的请求头。`setPolicy()` 还会在 Agent 仍接纳输入时注入一条带来源的用户消息,为下一步宣布变更。 +系统提示词贡献 `approval:policy` 在保留历史之后陈述有效策略的完整当前含义——`ask` 及其以拒绝方式关闭的后果,或 `never` 及其非升权后果——因此切换策略会追加一份新的完整快照,而不会改写稳定的请求头。`setPolicy()` 还会注入一条带来源的用户消息,为下一步宣布变更。 ### 审计 @@ -112,7 +112,7 @@ kind: "package-reference" #### 模型看到的内容 -首次请求与有效策略每次变化时,都会在保留的历史后追加一份完整运行时上下文快照。在 `ask` 下,审批上下文内容会说明系统可以咨询已配置的应答者,缺少可用应答者时则以拒绝方式关闭。在 `never` 下,它会说明确定性的拒绝与非升权后果。未变化的请求会保留先前快照,不增加另一条消息。Agent 仍接纳输入时,策略切换还会为下一次模型调用排队一条通知。 +首次请求与有效策略每次变化时,都会在保留的历史后追加一份完整运行时上下文快照。在 `ask` 下,审批上下文内容会说明系统可以咨询已配置的应答者,缺少可用应答者时则以拒绝方式关闭。在 `never` 下,它会说明确定性的拒绝与非升权后果。未变化的请求会保留先前快照,不增加另一条消息。用户切换运行中 Session 的策略时,下一次模型调用还会收到一条切换通知。 ##### Ask 策略贡献 diff --git a/packages/interaction/user-approval/src/index.ts b/packages/interaction/user-approval/src/index.ts index f469ff43ec..df48aca514 100644 --- a/packages/interaction/user-approval/src/index.ts +++ b/packages/interaction/user-approval/src/index.ts @@ -9,7 +9,7 @@ import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' import type { Agent } from '@deepseek-ai/dsh-agent' -import { HarnessError, createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' +import { createUserMessage, type ToolCallId } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' declare module '@deepseek-ai/dsh-llm' { interface MessageSourceMap { @@ -202,9 +202,9 @@ export class ApprovalService extends Service { } /** - * Persist a live Agent's policy. Queue the switch notice for the next model - * step while the Agent accepts input. Session initialization uses - * {@link setApprovalPolicy} directly. + * Switch one live agent's policy and queue the transition for its next model + * step. Session initialization uses {@link setApprovalPolicy} directly + * because there is no previously visible policy to change. * @param agent - the live agent whose policy is changing. * @param policy - the new effective policy. */ @@ -212,18 +212,13 @@ export class ApprovalService extends Service { const previous = this.effectivePolicy(agent.session) if (previous === policy) return setApprovalPolicy(agent.session, policy) - const notice = createUserMessage({ + agent.inject(createUserMessage({ content: [{ type: 'text', text: `The user changed the approval policy from "${POLICY_NOTICE_NAMES[previous]}" to "${POLICY_NOTICE_NAMES[policy]}".`, }], source: { kind: 'user-approval' }, - }) - try { - agent.inject(notice) - } catch (error: unknown) { - if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error - } + })) } /** diff --git a/packages/plan/plan-mode/README.i18n.yaml b/packages/plan/plan-mode/README.i18n.yaml index ec9790ee28..96b7f724c7 100644 --- a/packages/plan/plan-mode/README.i18n.yaml +++ b/packages/plan/plan-mode/README.i18n.yaml @@ -24,8 +24,8 @@ en: 30b67de3f6e97eab zh: 746cc81fbf5e0ed1 /deepseek-ai-dsh-plan-mode/use-this-package/entering-and-leaving-plan-mode: - en: 07ea7917ccae9613 - zh: a095e3eee8189456 + en: 2d300cdb883352ec + zh: 5a81be005b3716d3 /deepseek-ai-dsh-plan-mode/use-this-package/the-reviewed-exit: en: dbf12997d2359e81 zh: 120a91554d2154f4 diff --git a/packages/plan/plan-mode/README.md b/packages/plan/plan-mode/README.md index f7ea4c60c0..0ea3a4b33c 100644 --- a/packages/plan/plan-mode/README.md +++ b/packages/plan/plan-mode/README.md @@ -54,7 +54,7 @@ The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-a Type `/plan` to enter plan mode, or `/plan ` to enter with an instruction — the message becomes your next request under plan guidance. Type `/plan off` to leave plan mode directly; it also cancels a plan-mode entry that has not taken effect yet. -You can attach images and generic files to a `/plan` message, and they are included with your instruction in selection order. `/plan off` with attachments is rejected before the mode changes, so the draft and cards remain available. If the Agent closes before the message enters the inbox, the command reports whether plan mode is active or pending and leaves attachments in the composer. The `/plan` command is available wherever slash commands are supported, such as the Web client. +You can attach images and generic files to a `/plan` message, and they are included with your instruction in selection order. `/plan off` with attachments is rejected before the mode changes, so the draft and cards remain available. The `/plan` command is available wherever slash commands are supported, such as the Web client. ### The reviewed exit diff --git a/packages/plan/plan-mode/README.zh.md b/packages/plan/plan-mode/README.zh.md index ec0bd0c5a4..90ee3c97e5 100644 --- a/packages/plan/plan-mode/README.zh.md +++ b/packages/plan/plan-mode/README.zh.md @@ -54,7 +54,7 @@ kind: "package-reference" 输入 `/plan` 进入计划模式,或输入 `/plan ` 连同一条指令一起进入——该消息会成为你在计划引导下的下一条请求。输入 `/plan off` 直接离开计划模式;它还会取消尚未生效的计划模式进入。 -你可以在 `/plan` 消息中附带图片与通用文件,它们按选择顺序随指令一起提交。带附件的 `/plan off` 会在模式变更前被拒绝,因此草稿和附件卡仍可继续使用。如果 Agent 在消息入队前开始关闭,命令会说明计划模式已生效还是待生效,并将附件保留在输入区。`/plan` 命令在支持斜杠命令的界面中可用,例如 Web 客户端。 +你可以在 `/plan` 消息中附带图片与通用文件,它们按选择顺序随指令一起提交。带附件的 `/plan off` 会在模式变更前被拒绝,因此草稿和附件卡仍可继续使用。`/plan` 命令在支持斜杠命令的界面中可用,例如 Web 客户端。 ### 经评审的退出 diff --git a/packages/plan/plan-mode/src/index.ts b/packages/plan/plan-mode/src/index.ts index c909e7e982..06af5c2828 100644 --- a/packages/plan/plan-mode/src/index.ts +++ b/packages/plan/plan-mode/src/index.ts @@ -27,7 +27,7 @@ import { brandString } from '@deepseek-ai/dsh-brand' import { z as zod } from 'zod' import type { ZodType } from 'zod' import type { Agent, PreStepDecision } from '@deepseek-ai/dsh-agent' -import { HarnessError, createUserMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { ContextFormed } from '@deepseek-ai/dsh-llm' import type { Session, UserMessage } from '@deepseek-ai/dsh-session' import { defineTool } from '@deepseek-ai/dsh-tools' @@ -259,20 +259,13 @@ export class PlanModeController extends Service { } const outcome = this.set(agent, true) if (message !== '' || attachments.length > 0) { - const input = createUserMessage({ + agent.steer(createUserMessage({ content: [ ...attachments, ...(message === '' ? [] : [{ type: 'text' as const, text: message }]), ], source: { kind: 'user' }, - }) - try { - agent.steer(input) - } catch (error: unknown) { - if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error - const state = this.loggedActive(agent.session) ? 'Plan mode is on.' : 'Plan mode is still pending.' - return { kind: 'error', text: `${state} The agent is closing, so the message was not submitted.` } - } + })) } return { kind: 'success', @@ -453,13 +446,7 @@ export class PlanModeController extends Service { session.append('plan/mode', { active }) this.pendingIntents.delete(session) const narration = this.narration(session, active) - if (narration !== undefined) { - try { - agent.inject(narration) - } catch (error: unknown) { - if (!(error instanceof HarnessError) || error.code !== 'AGENT_CLOSED') throw error - } - } + if (narration !== undefined) agent.inject(narration) return 'committed' } diff --git a/packages/plan/plan-mode/tests/plan-mode.spec.ts b/packages/plan/plan-mode/tests/plan-mode.spec.ts index 5fa706ea77..99d72afd1d 100644 --- a/packages/plan/plan-mode/tests/plan-mode.spec.ts +++ b/packages/plan/plan-mode/tests/plan-mode.spec.ts @@ -10,7 +10,7 @@ import ToolRuntime, { RUN_CODE_NAME } from '@deepseek-ai/dsh-tools' import type { ToolExecutionToken, ToolRunContext } from '@deepseek-ai/dsh-tools' import { defineContentToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { Session, SessionId, SESSION_FORMAT_VERSION, type SessionEvent, type UserMessage } from '@deepseek-ai/dsh-session' -import AgentRegistry, { AgentClosedError, agentEvents, type Agent } from '@deepseek-ai/dsh-agent' +import AgentRegistry, { agentEvents, type Agent } from '@deepseek-ai/dsh-agent' import { createScope } from '@deepseek-ai/dsh-scope' import UserQuestionService, { UserQuestionError, type AskUserQuestionAnswer, type AskUserQuestionRequest, @@ -680,62 +680,6 @@ describe('/plan', () => { expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) }) - it.each([ - { open: false, active: true, state: 'Plan mode is on.' }, - { open: true, active: false, state: 'Plan mode is still pending.' }, - ])('reports the mode and the rejected message when a closing Agent has open turn $open', async ({ open, active, state }) => { - const ctx = await setup() - try { - await ctx.plugin(CommandRuntime) - const agent = await agentWithSession(ctx, 'closing-plan-command') - if (open) openTurn(agent.session) - agent.steer = () => { throw new AgentClosedError(agent.id) } - - const execution = await ctx.commands.execute(agent, '/plan sketch the layout', [], testToolSignal) - - const expected = { kind: 'error', text: `${state} The agent is closing, so the message was not submitted.` } - expect(execution?.result).toEqual(expected) - expect(foldPlanMode(agent.session.snapshotEvents())).toBe(active) - expect(ctx.planMode.get(agent)).toEqual(open ? { active, pending: true } : { active }) - expect(agent.session.snapshotEvents().findLast(event => event.type === 'command/done')?.data) - .toMatchObject(expected) - } finally { - await ctx.fiber.dispose() - } - }) - - it('reports a saved mode switch when a closing Agent rejects its switch notice', async () => { - const ctx = await setup() - try { - await ctx.plugin(CommandRuntime) - const agent = await agentWithSession(ctx, 'closing-plan-notice', { active: true }) - header(agent.session) - agent.inject = () => { throw new AgentClosedError(agent.id) } - - const execution = await ctx.commands.execute(agent, '/plan off', [], testToolSignal) - - expect(execution?.result).toEqual({ kind: 'success', text: 'Plan mode off.' }) - expect(foldPlanMode(agent.session.snapshotEvents())).toBe(false) - } finally { - await ctx.fiber.dispose() - } - }) - - it.each(['inject', 'steer'] as const)('propagates an unexpected plan %s failure', async (delivery) => { - const ctx = await setup() - try { - await ctx.plugin(CommandRuntime) - const agent = await agentWithSession(ctx, 'plan-delivery-error') - header(agent.session) - const failure = new Error('could not write plan input') - agent[delivery] = () => { throw failure } - - await expect(ctx.commands.execute(agent, '/plan sketch the layout', [], testToolSignal)).rejects.toBe(failure) - } finally { - await ctx.fiber.dispose() - } - }) - it('steers mixed attachments with or without text and refuses them on /plan off', async () => { const ctx = await setup() await ctx.plugin(CommandRuntime) diff --git a/packages/sdk/server/src/server.ts b/packages/sdk/server/src/server.ts index 46cda8d44b..bccfa6634e 100644 --- a/packages/sdk/server/src/server.ts +++ b/packages/sdk/server/src/server.ts @@ -263,8 +263,9 @@ export class HarnessSdkJsonRpcServer { if (!this.initialized) throw new Error('SDK server is not initialized') const rec = await this.getOrCreateSession(params.sessionId) this.lifetime.signal.throwIfAborted() - // An agent-loop reload can dispose the Agent while the SDK still retains - // this record. Reject stale records before admitting prompt attachments. + // An agent-loop-only reload disposes the loop's agents while this record + // survives; a retained agent accepts followup() silently, so validate the + // record against the live registry before delivery. this.assertLiveAgent(rec, params.sessionId) const content = await durablePromptContent(this.ctx, params.contentBlocks) this.lifetime.signal.throwIfAborted() diff --git a/packages/session/working-directory/README.i18n.yaml b/packages/session/working-directory/README.i18n.yaml index 4ed48e75cc..fd50066fe2 100644 --- a/packages/session/working-directory/README.i18n.yaml +++ b/packages/session/working-directory/README.i18n.yaml @@ -18,8 +18,8 @@ en: e65405026debde7c zh: e12a648eb10ed16b /deepseek-ai-dsh-working-directory/understand-the-implementation: - en: c0681d6879ece29d - zh: 42bf039fc1bbdaf5 + en: f0458147d29631b1 + zh: 6a288670dd084ffb /deepseek-ai-dsh-working-directory/further-exploration: en: eabff683146786c8 zh: 7997dec17802ef64 diff --git a/packages/session/working-directory/README.md b/packages/session/working-directory/README.md index 9506cfa788..44ed9ba9dc 100644 --- a/packages/session/working-directory/README.md +++ b/packages/session/working-directory/README.md @@ -41,7 +41,7 @@ Directory validation and publication delegate through `working-directory/access`
Implementation internals — click to expand -The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory. It warns unless the Agent is closing. The next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. +The Session projection owns the effective directory and exposes it in Session observations, so cold readers can use it without activating an Agent; the header continues to identify the original project. Changes serialize per Session, validate through the filesystem provider, check cancellation and Agent lifetime, commit an event, and queue a user-context notice. If notice queuing fails after commit, the operation returns the committed directory and logs a warning; the next request or resume still receives the required directory context. Prompt assembly validates the current directory before publishing its required context contribution. Existing processes and sandbox grants keep their independent ownership. The [service implementation](src/index.ts) defines the API. No runtime invariant companion is published because the service reads its only directory state from the Session projection and checks filesystem validity at use. diff --git a/packages/session/working-directory/README.zh.md b/packages/session/working-directory/README.zh.md index 1df1f5673b..9561d73972 100644 --- a/packages/session/working-directory/README.zh.md +++ b/packages/session/working-directory/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference"
实现细节 — 点击展开 -Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录。Agent 正在关闭时无需告警。下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 +Session 投影拥有当前目录,并通过 Session observation 暴露它,因此冷态读取方无需激活 Agent 即可使用;header 继续标识原始项目。每个 Session 的变更串行执行,通过文件系统 provider 验证,并检查取消状态与 Agent 生命周期,提交事件后排入用户上下文通知。若提交后通知入队失败,操作仍返回已提交的目录并记录警告;下一次请求或恢复仍会收到必需的目录上下文。提示词组装在发布必需的上下文条目前验证当前目录。已有进程与沙箱授权继续由各自的服务拥有。[服务实现](src/index.ts) 定义 API。 不发布 `./invariant` 伴生模块,因为服务从 Session 投影读取唯一的目录状态,并在使用时检查文件系统有效性。 diff --git a/packages/session/working-directory/src/index.ts b/packages/session/working-directory/src/index.ts index be0c9e5187..62c3750c2c 100644 --- a/packages/session/working-directory/src/index.ts +++ b/packages/session/working-directory/src/index.ts @@ -7,7 +7,7 @@ import { isAbsolute } from 'node:path' import { Context, Service } from '@deepseek-ai/cordis' import z from '@deepseek-ai/schemastery' import { z as zod } from 'zod' -import { AgentClosedError, type Agent } from '@deepseek-ai/dsh-agent' +import type { Agent } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-fs' import { createUserMessage } from '@deepseek-ai/dsh-llm' import type { Session } from '@deepseek-ai/dsh-session' @@ -217,7 +217,6 @@ export class WorkingDirectoryService extends Service { try { agent.inject(notice) } catch (error) { - if (error instanceof AgentClosedError) return this.ctx.logger.warn(`working-directory: committed ${JSON.stringify(directory)}, but could not queue its notice: ${String(error)}`) } } diff --git a/packages/session/working-directory/tests/working-directory.spec.ts b/packages/session/working-directory/tests/working-directory.spec.ts index d05bf06f10..22fb99af47 100644 --- a/packages/session/working-directory/tests/working-directory.spec.ts +++ b/packages/session/working-directory/tests/working-directory.spec.ts @@ -5,7 +5,6 @@ import { join } from 'node:path' import { setImmediate } from 'node:timers/promises' import { Context } from '@deepseek-ai/cordis' import { describe, expect, it, vi } from 'vitest' -import { AgentClosedError } from '@deepseek-ai/dsh-agent' import LocalFileSystem from '@deepseek-ai/dsh-fs-local' import WorkingDirectory, { type Config as WorkingDirectoryConfig } from '@deepseek-ai/dsh-working-directory' import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit' @@ -315,23 +314,6 @@ describe('Session working directories', () => { } }) - it('keeps the committed directory when the Agent closes before accepting its notice', async () => { - await using f = await fixture() - const child = join(f.root, 'child') - await mkdir(child) - const inject = vi.spyOn(f.agent, 'inject').mockImplementation(() => { throw new AgentClosedError(f.agent.id) }) - const warn = vi.spyOn(f.ctx.logger, 'warn') - try { - await expect(f.ctx.workingDirectory.set(f.agent, child)).resolves.toBe(child) - expect(f.ctx.workingDirectory.get(f.agent.session)).toBe(child) - expect(inject).toHaveBeenCalledOnce() - expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('could not queue its notice')) - } finally { - inject.mockRestore() - warn.mockRestore() - } - }) - it('returns committed state and warns when the notice cannot be queued', async () => { await using f = await fixture() const child = join(f.root, 'child') diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 4248dbcefa..3c72f6dcf5 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: e8b2853fe4a5105d - zh: fb0fdeeefee852ce + en: 177eb4ba47958b90 + zh: 592308f7e8898f86 /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index a2012acd79..307f0d5461 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When an Agent has begun closing, the manager settles its Activation through the shared close transaction without retrying maintenance admission. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When the Agent factory disposes a local Agent, the manager settles its Activation after the Agent has drained and left the registry. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index b5159612d0..a2b43b1fae 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。 Agent 开始关闭后,管理器通过共享关闭事务结算其 Activation,不再重试维护准入。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。本地 Agent 因工厂卸载而释放时,管理器在 Agent 停稳并离开注册表后结算其 Activation。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index 1f9108edae..724b6442df 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -10,7 +10,7 @@ import { randomUUID } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' import type { Context } from '@deepseek-ai/cordis' -import { AgentClosedError, type Agent, type AgentOptions, type CreateAgentOptions } from '@deepseek-ai/dsh-agent' +import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageId, MessageSource } from '@deepseek-ai/dsh-llm' @@ -997,11 +997,7 @@ export class SubagentManager { done = this.close(activation, () => this.finishDisposal(activation, false)) return Promise.resolve() }) - } catch (error: unknown) { - if (error instanceof AgentClosedError) { - done = this.close(activation, () => this.finishDisposal(activation, false)) - return Promise.resolve({ done }) - } + } catch (_error: unknown) { // Another activity already owns the Agent's idle phase. return Promise.resolve('retry') } @@ -1132,7 +1128,6 @@ export class SubagentManager { } this.sendWaking(parent, message, parent.status === 'idle' ? 'queue' : 'steer') } catch (error: unknown) { - if (error instanceof AgentClosedError) return this.ctx.logger.warn( `subagent "${activation.childId}" settlement notice was not delivered to its parent: ` + errorChain(error), diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index 627f0f085e..a3cb8d3b93 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -8,7 +8,7 @@ import { join } from 'node:path' import { Context } from '@deepseek-ai/cordis' import { liveConfig } from '../../../settings/settings/tests/live-config.ts' import type { Agent } from '@deepseek-ai/dsh-agent' -import { AgentClosedError, agentEvents } from '@deepseek-ai/dsh-agent' +import { agentEvents } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { mountAgentLoopTestDependencies } from '@deepseek-ai/dsh-agent-loop-testkit' import { SessionId } from '@deepseek-ai/dsh-session' @@ -2570,22 +2570,6 @@ describe('continuable review regressions', () => { expect(managerState(ctx).resident.get(started.childId)).toBeUndefined() }) - it('settles when Agent admission closes before settlement maintenance starts', async () => { - const release = Promise.withResolvers() - const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) - const { ctx, parent } = await setupWith(adapter) - const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'caller' }) - await vi.waitFor(() => { expect(adapter.requests).toHaveLength(1) }) - const child = ctx.agents.get(started.childId)! - const maintenance = vi.spyOn(child, 'runMaintenance').mockImplementation(() => { - throw new AgentClosedError(child.id) - }) - release.resolve(undefined) - await waitNoActivation(ctx, started.childId) - expect(maintenance).toHaveBeenCalledTimes(1) - expect(await started.result).toMatchObject({ stopReason: 'completed' }) - }) - it('keeps a maintenance task that claimed the idle phase after whenIdle resolved', async () => { const release = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('working'), gate: release.promise }]) From 681d947cad4959283df26978f8d6d13321c6eee5 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 20:02:01 +0800 Subject: [PATCH 068/103] fix(agent): prevent late wakes during teardown --- packages/core/agent-loop/src/agent.ts | 2 + packages/core/agent-loop/src/index.ts | 2 +- .../tests/fixtures/serial-created.mjs | 15 +++++--- packages/subagent/subagent/README.i18n.yaml | 4 +- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- packages/subagent/subagent/src/manager.ts | 9 ++++- .../subagent/tests/continuation.spec.ts | 37 ++++++++++++++++++- .../subagent/tests/factory-settlement.spec.ts | 8 +++- snapshots/sdk/sdk.snapshot.ts | 13 ++++++- snapshots/sdk/serial-created/cordis.yml | 2 + snapshots/sdk/serial-created/session.v4.jsonl | 26 ++++++++----- 12 files changed, 96 insertions(+), 26 deletions(-) diff --git a/packages/core/agent-loop/src/agent.ts b/packages/core/agent-loop/src/agent.ts index 58b1930241..d0c23d565a 100644 --- a/packages/core/agent-loop/src/agent.ts +++ b/packages/core/agent-loop/src/agent.ts @@ -141,6 +141,7 @@ export class ReactLoopAgent implements Agent { public readonly session: Session, projections: LoopProjections, lastTurn: number, + private readonly lifetimeSignal?: AbortSignal, ) { this.requestSurfaceGeneration = session.surface.contentGeneration this.dispatch = agentEvents(loopCtx, this) @@ -232,6 +233,7 @@ export class ReactLoopAgent implements Agent { * the inbox insertion so a reentrant cancel cannot reclassify it. */ private wakeDriver(wakeAfterAbort = false): void { + if (this.lifetimeSignal?.aborted) return if (this.phase.kind !== 'idle') { // Maintenance and aborted drivers cannot deliver the wake: latch it for // replay at convergence. Live drivers claim queued work themselves; diff --git a/packages/core/agent-loop/src/index.ts b/packages/core/agent-loop/src/index.ts index 3277d9fb83..bda53c3b56 100644 --- a/packages/core/agent-loop/src/index.ts +++ b/packages/core/agent-loop/src/index.ts @@ -574,7 +574,7 @@ export class AgentLoop extends Service implements AgentFactory { const created = machine = new ReactLoopAgent( loopCtx, id, agentOptions, session, projections, - lastTurn, + lastTurn, abort.signal, ) machineReady.resolve() // Adopt the scope on its original fiber so it cannot unload before teardown. diff --git a/packages/core/agent-loop/tests/fixtures/serial-created.mjs b/packages/core/agent-loop/tests/fixtures/serial-created.mjs index 2b27a7f33b..e3e659f15c 100644 --- a/packages/core/agent-loop/tests/fixtures/serial-created.mjs +++ b/packages/core/agent-loop/tests/fixtures/serial-created.mjs @@ -6,11 +6,11 @@ export const name = 'serial-created-fixture' export const inject = ['agents', 'sessions'] /** Install ordered creation listeners whose context must precede the first turn. */ -export function apply(ctx) { +export function apply(ctx, config = {}) { const checkedCancellation = new WeakSet() ctx.on('agent/pre-step', async ({ agent, messages, signal }, next) => { if (checkedCancellation.has(agent) - || agent.session.header.origin !== 'subagent') return next() + || (!config.checkRootCancellation && agent.session.header.origin !== 'subagent')) return next() checkedCancellation.add(agent) const pending = { id: randomUUID(), role: 'user', @@ -25,13 +25,18 @@ export function apply(ctx) { if (session === agent.session && event.type === 'agent/inbox/spliced' && event.data.outcome === 'canceled' && (event.data.removedCount ?? 0) > 0) throw failure }) + let rejected = false try { - try { agent.cancel({ kind: 'user' }) } - catch (error) { if (error !== failure) throw error } + try { + agent.cancel({ kind: 'user' }) + } catch (error) { + if (error !== failure) throw error + rejected = true + } } finally { stopRejecting() } - if (!signal.aborted) throw new Error('queue-clear failure prevented cancellation') + if (!rejected || !signal.aborted) throw new Error('expected queue-clear rejection and activity cancellation') agent.inbox.remove(pending.id) for (const message of messages) { const ordinary = message.source.kind === 'user' diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index 3c72f6dcf5..ba1e09b3ea 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 177eb4ba47958b90 - zh: 592308f7e8898f86 + en: 63105e704827a4e4 + zh: 12908b6319fb8b1e /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index 307f0d5461..ff2ba67405 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When the Agent factory disposes a local Agent, the manager settles its Activation after the Agent has drained and left the registry. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When the Agent factory disposes a local Agent, the manager settles its Activation after the Agent has drained and left the registry. If teardown fails with input still pending, the result reports `error` and retains any output already produced. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index a2b43b1fae..a93e545587 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。本地 Agent 因工厂卸载而释放时,管理器在 Agent 停稳并离开注册表后结算其 Activation。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。本地 Agent 因工厂卸载而释放时,管理器在 Agent 停稳并离开注册表后结算其 Activation。如果关闭失败时仍有待处理输入,结果报告 `error`,并保留已经生成的输出。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/src/manager.ts b/packages/subagent/subagent/src/manager.ts index 724b6442df..83fa44e325 100644 --- a/packages/subagent/subagent/src/manager.ts +++ b/packages/subagent/subagent/src/manager.ts @@ -9,7 +9,7 @@ import { randomUUID } from 'node:crypto' import { isAbsolute, resolve } from 'node:path' import type {} from '@deepseek-ai/dsh-working-directory' -import type { Context } from '@deepseek-ai/cordis' +import { FiberState, type Context } from '@deepseek-ai/cordis' import type { Agent, AgentOptions, CreateAgentOptions } from '@deepseek-ai/dsh-agent' import { brandString } from '@deepseek-ai/dsh-brand' import { ReasoningEffortId, contentHasImage, createUserMessage, errorChain } from '@deepseek-ai/dsh-llm' @@ -1095,6 +1095,10 @@ export class SubagentManager { { cause: new AggregateError(failures) }, ) } + if (failure !== undefined && result.stopReason === 'completed' && child !== undefined + && (child.inbox.nextStep.length > 0 || child.inbox.nextTurn.length > 0)) { + result = { ...result, stopReason: 'error' } + } this.resident.delete(childId) activation.releaseSlot() const terminal: SubagentResult = failure === undefined ? result : { output: [], stopReason: 'error' } @@ -1117,7 +1121,8 @@ export class SubagentManager { try { const parentId = activation.ancestors.at(-1) as SessionId const parent = this.ctx.agents.get(parentId) - if (parent === undefined || this.rootOf(parent) !== activation.root) return + if (parent === undefined || parent.ctx.fiber.state !== FiberState.ACTIVE + || this.rootOf(parent) !== activation.root) return const message = createSettlementMessage( activation.childId, agentAddress(activation.path, activation.childId), terminal, activation.kind === 'local', activation.kind === 'local' && activation.omitClosingText, diff --git a/packages/subagent/subagent/tests/continuation.spec.ts b/packages/subagent/subagent/tests/continuation.spec.ts index a3cb8d3b93..5e32c776bf 100644 --- a/packages/subagent/subagent/tests/continuation.spec.ts +++ b/packages/subagent/subagent/tests/continuation.spec.ts @@ -99,7 +99,7 @@ async function setupWith( rmSync(persistedRoot, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) }) } - await ctx.plugin(AgentLoop, { agents: [] }) + const loop = await ctx.plugin(AgentLoop, { agents: [] }) if (options.sessionQuery !== false) await ctx.plugin(TestSessionQuery) await mountWorkingDirectoryFixture(ctx) if (ctx.get('sessionProjections') === undefined) await ctx.plugin(SessionProjectionRegistry) @@ -109,7 +109,7 @@ async function setupWith( await ctx.plugin(SubagentFork, { providerName: 'fork' }) ctx.llm.registerAdapter(['mock'], adapter) const parent = await ctx.agentLoop.create(SessionId('parent'), { provider: 'mock', model: 'mock' }) - return { ctx, parent, disposePersistence, root } + return { ctx, parent, disposePersistence, root, loop } } async function setup(script: Script, options: { persistence?: boolean } = {}) { @@ -3450,6 +3450,39 @@ describe('continuable settlement delivery', () => { : [])).toEqual([{ inserted: 1, removed: 0 }, { inserted: 0, removed: 1 }]) }) + it('does not wake a parent whose scope is unwinding during factory unload', async () => { + const { ctx, parent, loop } = await setup([textResponse('child answer')]) + const flushing = Promise.withResolvers() + const releaseFlush = Promise.withResolvers() + const unwinding = Promise.withResolvers() + const releaseParent = Promise.withResolvers() + parent.ctx.effect(() => async () => { + unwinding.resolve(undefined) + await releaseParent.promise + }) + ctx.on('session/flush', async (session) => { + if (session.header.origin !== 'subagent') return + flushing.resolve(undefined) + await releaseFlush.promise + }) + let unload: Promise | undefined + try { + const started = await ctx.subagents.startActivation({ ...startSpec(parent), delivery: 'parent' }) + await flushing.promise + unload = loop.dispose() + await unwinding.promise + await started.result + expect(ctx.agents.get(parent.id)).toBe(parent) + expect(parent.session.snapshotEvents().some(event => event.type === 'turn/start')).toBe(false) + expect(settlementNotices(parent)).toEqual([]) + } finally { + releaseFlush.resolve(undefined) + releaseParent.resolve(undefined) + await unload + await ctx.fiber.dispose() + } + }) + it('drops the notice without disturbing teardown when the parent is gone', async () => { const releaseChild = Promise.withResolvers() const adapter = new GatedAdapter([{ chunks: textResponse('answer'), gate: releaseChild.promise }]) diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index 0228655cc5..4a70337c87 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -52,9 +52,13 @@ it.each([false, true])('settles an activation after factory unload with queue-cl expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) - expect(await started.result).toMatchObject({ stopReason: 'completed' }) + const stopReason = rejectQueueClear ? 'error' : 'completed' + expect(await started.result).toMatchObject({ + output: [{ type: 'text', text: 'answer' }], + stopReason, + }) expect(released).toHaveBeenCalledTimes(1) - expect(ended).toHaveBeenCalledTimes(1) + expect(ended).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ stopReason })) } finally { release.resolve(undefined) await ctx.fiber.dispose() diff --git a/snapshots/sdk/sdk.snapshot.ts b/snapshots/sdk/sdk.snapshot.ts index 43fce16175..f231d3a8d4 100644 --- a/snapshots/sdk/sdk.snapshot.ts +++ b/snapshots/sdk/sdk.snapshot.ts @@ -801,7 +801,10 @@ async function runScenario(scenario: CorpusScenario): Promise<{ ignoredRootEntries: RUNTIME_WORKSPACE_ENTRIES, }) const [parentFixture, ...childFixtures] = replayFixtures - const actions = sdkActions(primaryFixture, assertions.replayStandaloneCommands === true) + const recordedActions = sdkActions(primaryFixture, assertions.replayStandaloneCommands === true) + const actions = scenario.name === 'serial-created' + ? recordedActions.filter(action => action.kind === 'turn' && action.content !== undefined) + : recordedActions const resumeReplayFile = scenario.name === 'session-resume' && !recording ? join(patchRoot, 'resume-replay.json') : undefined const prepareTurnReplay = async (turn: number): Promise => { @@ -1020,6 +1023,9 @@ async function runScenario(scenario: CorpusScenario): Promise<{ observe, ) } + if (scenario.name === 'serial-created') { + await harness.client.request('session/wait', { sessionId }) + } for (const type of postActionEventTypes(primaryFixture)) { await waitForRootEvent(subscription, sessionId, event => event.type === type, observe) } @@ -1754,6 +1760,11 @@ describe('TypeScript SDK snapshots over the jsonrpc runtime', () => { } if (scenario.name === 'serial-created') { expect(observedMethods.has('subagent.started')).toBe(false) + const turns = parseSessionLog(ordered[0]!.content).filter(event => event.type === 'turn/end') + expect(turns.map(event => event.data.reason)).toEqual([ + { kind: 'aborted', reason: { kind: 'user' } }, + { kind: 'completed' }, + ]) } if (ordered.length > 1 && assertions.dshSdkChild === undefined) { expect(observedMethods.has('subagent.started')).toBe(true) diff --git a/snapshots/sdk/serial-created/cordis.yml b/snapshots/sdk/serial-created/cordis.yml index aa02a3714c..7d0e5c0a67 100644 --- a/snapshots/sdk/serial-created/cordis.yml +++ b/snapshots/sdk/serial-created/cordis.yml @@ -34,3 +34,5 @@ - insert: - id: serial-created-fixture name: '../../../packages/core/agent-loop/tests/fixtures/serial-created.mjs' + config: + checkRootCancellation: true diff --git a/snapshots/sdk/serial-created/session.v4.jsonl b/snapshots/sdk/serial-created/session.v4.jsonl index 2b38032fe9..ad1c13f08a 100644 --- a/snapshots/sdk/serial-created/session.v4.jsonl +++ b/snapshots/sdk/serial-created/session.v4.jsonl @@ -7,16 +7,24 @@ {"type":"turn/start","data":{"turn":1}} {"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} {"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} -{"type":"step/start","data":{"turn":1,"step":1}} -{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:3}}"}},"surfaceOp":"append"} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:3}}","role":"user","content":[{"type":"text","text":"Cancellation checkpoint probe."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[],"outcome":"canceled"}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}}]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"}]}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"aborted","reason":{"kind":"user"}}}} +{"type":"turn/start","data":{"turn":2}} +{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":2,"step":1}} +{"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:4}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"id":"{{message:1}}","role":"user","content":[{"type":"text","text":"Serial agent creation completed. Ordinary and nested forks are independent; historical fork metadata remains readable."}],"source":{"kind":"plugin:serial-created-fixture"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly: SDK snapshot OK"}],"source":{"kind":"user"},"role":"user","id":"{{message:2}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:6}}"},"surfaceOp":"append"} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} -{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[11],"source":{"kind":"fallback"}}} -{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":16}} -{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1793796117777,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793796117777,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1793796117778,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793796117778,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1793796117778,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1793796117778,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1793796117778,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1793796117778,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} -{"type":"step/end","data":{"turn":1,"step":1}} -{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} +{"type":"session/title","data":{"title":"Reply with exactly: SDK snapshot","messageSeqs":[19],"source":{"kind":"fallback"}}} +{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":24}} +{"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."},{"type":"text","text":"SDK snapshot OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19},"stream":[{"type":"chunk","time":1793966135593,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793966135593,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," reply"," with"," exactly"," \"","SD","K"," snapshot"," OK","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1793966135593,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793966135593,"index":1,"dt":[0,0,0],"texts":["SD","K"," snapshot"," OK"]},{"type":"chunk","time":1793966135593,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to reply with exactly \"SDK snapshot OK\". Let me do that."}}},{"type":"chunk","time":1793966135593,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"SDK snapshot OK"}}},{"type":"chunk","time":1793966135593,"chunk":{"type":"usage","usage":{"inputTokens":1769,"outputTokens":24,"cacheReadTokens":0,"reasoningTokens":19}}},{"type":"chunk","time":1793966135593,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} +{"type":"step/end","data":{"turn":2,"step":1}} +{"type":"turn/end","data":{"turn":2,"reason":{"kind":"completed"}}} From dc96caa63e431da33ddce4108b86fa5e88e67300 Mon Sep 17 00:00:00 2001 From: liukx0205 Date: Fri, 6 Nov 2026 20:23:20 +0800 Subject: [PATCH 069/103] test(agent): cover work after creation signal aborts --- packages/core/agent-loop/tests/scope-lifecycle.spec.ts | 7 ++++++- packages/subagent/subagent/README.i18n.yaml | 4 ++-- packages/subagent/subagent/README.md | 2 +- packages/subagent/subagent/README.zh.md | 2 +- .../subagent/subagent/tests/factory-settlement.spec.ts | 2 +- 5 files changed, 11 insertions(+), 6 deletions(-) diff --git a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts index d6a6f50730..4b01c61f80 100644 --- a/packages/core/agent-loop/tests/scope-lifecycle.spec.ts +++ b/packages/core/agent-loop/tests/scope-lifecycle.spec.ts @@ -446,7 +446,9 @@ describe('agent scope lifecycle', () => { }) it('uses signal only for creation: aborts pending setup but not a returned live handle', async () => { - const ctx = await harness() + const adapter = new MockAdapter([textResponse('ok')]) + const ctx = await harness(adapter) + onTestFinished(() => ctx.fiber.dispose()) const pendingController = new AbortController() const setupStarted = Promise.withResolvers() const pending = ctx.agents.create({ @@ -474,6 +476,9 @@ describe('agent scope lifecycle', () => { await Promise.resolve() expect(ctx.agents.get(live.agent.id)).toBe(live.agent) expect(live.agent.status).toBe('idle') + live.agent.followup(createUserMessage({ content: text('continue'), source: { kind: 'user' } })) + await live.agent.whenIdle() + expect(adapter.requests).toHaveLength(1) await live.dispose() }) diff --git a/packages/subagent/subagent/README.i18n.yaml b/packages/subagent/subagent/README.i18n.yaml index ba1e09b3ea..d6864b8745 100644 --- a/packages/subagent/subagent/README.i18n.yaml +++ b/packages/subagent/subagent/README.i18n.yaml @@ -54,8 +54,8 @@ en: 61cddba23f4e7d1c zh: 052c8331a747403f /deepseek-ai-dsh-subagent/understand-the-implementation/activation-settlement: - en: 63105e704827a4e4 - zh: 12908b6319fb8b1e + en: ba22f6dd5f15f405 + zh: a469c6a4e49adea9 /deepseek-ai-dsh-subagent/understand-the-implementation/restoring-child-composition: en: 843f9f4319ca2ae3 zh: 218bf355816d4ff6 diff --git a/packages/subagent/subagent/README.md b/packages/subagent/subagent/README.md index ff2ba67405..a212a1ff72 100644 --- a/packages/subagent/subagent/README.md +++ b/packages/subagent/subagent/README.md @@ -124,7 +124,7 @@ External providers mint a fresh `SubagentRun.id` for each execution in the runti ### Activation settlement -The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When the Agent factory disposes a local Agent, the manager settles its Activation after the Agent has drained and left the registry. If teardown fails with input still pending, the result reports `error` and retains any output already produced. +The manager reserves child identity and capacity, materializes a local Agent or external execution, and accepts the initial task. Local admission closes after Agent activity and pending input finish, with activity revalidated after the final Session flush. Both local and external activations deliver their result after handle cleanup, capacity release, and settlement notifications. Host waits on the subagent tree root join progressing members and their cleanup, including failed executions; idle members with parked input remain resident without delaying host completion. Ordinary members do not wait for descendants. Closing admission and disposing the handle prevent late work from entering a released Agent. Parent delivery emits its notice after settlement only if the creator is still online; caller delivery leaves collection to the awaiting workflow. Headless hosts repeat `agent.whenIdle()` and `waitForTreeWork(agent)` until no child work remains and the parent stays idle with an unchanged Session sequence across the child check, so completion notices can produce the final parent answer. When the Agent factory disposes a local Agent, the manager settles its Activation after the Agent has drained and left the registry. If teardown fails with input still pending, an otherwise `completed` result reports `error` and retains any output already produced. Settlement attribution records the exact execution stop reason without altering model-facing notice content. Historical notices can omit this field; readers must not infer it from the English summary. diff --git a/packages/subagent/subagent/README.zh.md b/packages/subagent/subagent/README.zh.md index a93e545587..a1f2745150 100644 --- a/packages/subagent/subagent/README.zh.md +++ b/packages/subagent/subagent/README.zh.md @@ -124,7 +124,7 @@ kind: "package-reference" ### Activation 结算 -管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。本地 Agent 因工厂卸载而释放时,管理器在 Agent 停稳并离开注册表后结算其 Activation。如果关闭失败时仍有待处理输入,结果报告 `error`,并保留已经生成的输出。 +管理器预留子级身份与容量,创建本地 Agent 或外部执行,并接受初始任务。本地 Agent 活动和待处理输入结束后,管理器在最终 Session flush 后重新验证活动状态并关闭准入。本地与外部 activation 都在句柄清理、容量归还及结算通知结束后交付结果。宿主在 subagent 树根上等待仍在推进的成员及其清理,包括失败的执行;有停放输入的空闲成员继续驻留,但不延迟宿主完成。普通成员不等待后代。关闭准入并释放句柄可防止迟到工作进入已释放的 Agent。父级投递仅在创建者仍在线时于结算后发送通知;调用方投递由等待中的工作流收集。Headless 宿主交替等待 `agent.whenIdle()` 与 `waitForTreeWork(agent)`,直至没有子级工作,且父级在检查子级期间保持空闲、Session 序号不变,让完成通知可驱动父级生成最终答案。本地 Agent 因工厂卸载而释放时,管理器在 Agent 停稳并离开注册表后结算其 Activation。如果关闭失败时仍有待处理输入,原本为 `completed` 的结果改为报告 `error`,并保留已经生成的输出。 结算归属信息记录确切的执行停止原因,不改变面向模型的通知内容。历史通知可以缺少该字段;读取方不得从英文摘要推断它。 diff --git a/packages/subagent/subagent/tests/factory-settlement.spec.ts b/packages/subagent/subagent/tests/factory-settlement.spec.ts index 4a70337c87..032a2adcab 100644 --- a/packages/subagent/subagent/tests/factory-settlement.spec.ts +++ b/packages/subagent/subagent/tests/factory-settlement.spec.ts @@ -51,12 +51,12 @@ it.each([false, true])('settles an activation after factory unload with queue-cl rejectClear() expect(ctx.agents.get(started.childId)).toBeUndefined() release.resolve(undefined) - await vi.waitFor(() => { expect(state.resident.has(started.childId)).toBe(false) }, { timeout: 1000 }) const stopReason = rejectQueueClear ? 'error' : 'completed' expect(await started.result).toMatchObject({ output: [{ type: 'text', text: 'answer' }], stopReason, }) + expect(state.resident.has(started.childId)).toBe(false) expect(released).toHaveBeenCalledTimes(1) expect(ended).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ stopReason })) } finally { From 0a228f0a6affd854133bd02a2c1cf5657cf13532 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 6 Nov 2026 14:53:11 +0800 Subject: [PATCH 070/103] feat(ui-chat): load earlier history with explicit consumption intent --- ...chat-history-consumption-details.i18n.yaml | 34 +++ ...-11-06-chat-history-consumption-details.md | 101 +++++++++ ...-06-chat-history-consumption-details.zh.md | 101 +++++++++ ...6-11-06-chat-history-consumption.i18n.yaml | 31 +++ .../2026-11-06-chat-history-consumption.md | 74 ++++++ .../2026-11-06-chat-history-consumption.zh.md | 74 ++++++ .../api/session-controller/README.i18n.yaml | 4 +- packages/api/session-controller/README.md | 2 +- packages/api/session-controller/README.zh.md | 2 +- .../src/client/contract/session.ts | 18 +- .../src/client/contract/snapshot.ts | 5 + .../src/client/sessions/session.ts | 151 ++++++++++--- .../tests/session.client.spec.ts | 212 +++++++++++++++++- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 4 +- packages/client/ui-chat/README.zh.md | 4 +- packages/client/ui-chat/src/client/apply.ts | 3 +- .../src/client/chat/ChatView.module.css | 17 ++ .../ui-chat/src/client/chat/ChatView.tsx | 31 ++- .../ui-chat/src/client/chat/flow-motion.ts | 3 + .../src/client/chat/use-chat-navigation.ts | 137 +++++++++-- .../src/client/chat/use-chat-scroll.ts | 54 +++-- .../src/client/chat/use-chat-viewport.ts | 209 +++++++++++++++-- .../ui-chat/src/client/contract/slots.ts | 3 + packages/client/ui-chat/src/client/locale.ts | 32 +++ .../tests/apply-inject.client.spec.tsx | 2 +- .../tests/chat-history-intent.client.spec.ts | 117 ++++++++++ .../ui-chat/tests/chat-scroll.client.spec.tsx | 18 +- .../ui-chat/tests/chat-view.client.spec.tsx | 173 ++++++++++---- .../tests/chat-viewport.client.spec.ts | 130 +++++++++++ .../conversation-registry.client.spec.ts | 3 +- .../tests/queue-dock.client.spec.tsx | 2 +- .../schedule-catalog-action.client.spec.tsx | 2 +- .../tests/ui-session.client.spec.ts | 2 +- .../ui-trajectory/tests/views.client.spec.tsx | 2 +- .../tests/plan-review-panel.client.spec.tsx | 2 +- .../user-questions-composer.client.spec.tsx | 2 +- .../src/client/api-catalog.ts | 4 +- .../src/client/slot-catalog.ts | 24 +- .../tests/quote-selection.client.spec.tsx | 2 +- .../client-runtime/src/fixtures.ts | 2 +- .../client-runtime/src/sessions.ts | 8 + 42 files changed, 1625 insertions(+), 180 deletions(-) create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md create mode 100644 .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md create mode 100644 packages/client/ui-chat/tests/chat-history-intent.client.spec.ts diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml new file mode 100644 index 0000000000..4d1f5caf20 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml @@ -0,0 +1,34 @@ +# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption-details.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md +/agent-note-chat-history-consumption-classes-and-interactions: + en: 69ce0866b2608208 + zh: 55fdeded5d7a4779 +/agent-note-chat-history-consumption-classes-and-interactions/problem: + en: edaa7ca0e55a9c33 + zh: 33d2b5ac07760988 +/agent-note-chat-history-consumption-classes-and-interactions/proposal: + en: 5e5553981c48d0e2 + zh: 1195ac8d64180451 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/owners-and-interfaces: + en: 58f6f76fd263cafb + zh: 13ac0a6259d30cda +/agent-note-chat-history-consumption-classes-and-interactions/proposal/data-lifetimes: + en: ffdbe0e796463624 + zh: f10bd2ced5748017 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/consumption-intent-and-wakeups: + en: 993c2985bf6f3c8f + zh: 8f88fb46584fb272 +/agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads: + en: 2439cd4cb6a81bc4 + zh: 63b8c83897a88d2c +/agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered: + en: 1b9b8eb12ee5dbd7 + zh: e4ecc3cdc3375438 +/agent-note-chat-history-consumption-classes-and-interactions/acceptance-criteria: + en: 8a51c549570a5e0d + zh: eb7b3c27b9dcd98c +/agent-note-chat-history-consumption-classes-and-interactions/risks: + en: aee9f541d058818b + zh: 74e4b6098b9f4b46 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md new file mode 100644 index 0000000000..ccc137d86b --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md @@ -0,0 +1,101 @@ +# Agent Note: Chat history consumption classes and interactions + +Status: proposed + +English | [中文](2026-11-06-chat-history-consumption-details.zh.md) + +## Problem + +Session owns a history page's network lifetime, while Chat owns whether that page can safely enter the current view. Two-phase loading must reuse existing publication and scrolling capabilities without copying business data, consumption intent, and DOM preservation state into one owner. + +## Proposal + +[History prefetch and safe consumption](2026-11-06-chat-history-consumption.md) defines user-visible behavior and trade-offs. This note defines class interactions and lifetimes without adding an independent scroll animation or React commit manager. + +### Owners and interfaces + +| Owner | Data and operations | +|---|---| +| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` prepares and optionally consumes a page; `consumeOlder()` synchronously publishes a valid staged page; `historyLoadStatus` is idle/loading/pendingConsumption/error, and `loadingOlder` derives from loading, including Turn jumps | +| Session request record | Holds generation, starting cursor, page entries, hasMore, Promise, and consumption/invalidation flags; staging does not advance the visible window cursor | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; waits or falls back by blocker; only manual consumption registers a fold-completion callback | +| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | Reads internal input/motion state and scrollTop, returns a blocker or native/preserve/prepend, and performs distance measurement and existing anchor algorithms | +| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | Connects existing reading, scroll, content, and size notifications to consumption checks and settles a pending one-shot correction during commit handling | +| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | Requests and consumes through injected callbacks and reads state through useSession; renders a fixed-height history control without retaining Session history data or accumulating historyWasPartial | + +```text +ChatNavigation.checkHistory + ├─ pendingConsumption + intent=none → retain page until clicked + ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain consumption intent + │ ├─ motion/pointer/unavailable → auto falls back, manual waits + │ ├─ native → consumeOlder + │ ├─ prepend → capture paging position → consumeOlder → correct once after commit + │ └─ preserve → beginPreserving → consumeOlder + ├─ loading → no duplicate request + ├─ error → wait for explicit retry + └─ idle + hasMore + (manual intent or near top without following) → request a page + +Session.loadOlder + → prepareOlder reuses or creates the request + → await the captured request Promise + → consumeOlder when request identity remains valid and consumption is not deferred + +Session.prepareOlder + → network prepend → capture the page without publishing eventSource + → validate progress → pendingConsumption or error + +Session.consumeOlder + → check generation/cursor/consuming + → synchronous eventSource.prepend → existing Conversation merge and flush + → clear the request record and publish final status +``` + +### Data lifetimes + +`isOpen` means only that Session `openState === 'open'`; it is independent of whether a page is `pendingConsumption`. `historyWasPartial` is monotonic for one Client Session instance: once its visible window has `hasMore=true`, the fact remains until the instance ends, across component remounts and reconnects, without entering the persistent log. + +`prepareOlder()` returns an existing request or creates one, and `loadOlder()` rechecks identity after awaiting that captured request Promise. An obsolete Promise cannot consume a newer page. A default call consumes the prepared page; `deferConsumption` retains a valid nonempty page, while an empty terminal page can immediately confirm exhaustion. Consumption retains the request record and sets `consuming` to prevent synchronous subscriber reentry without borrowing the network loading state. + +An ordinary request captures the transport page first. It can be consumed only after the request succeeds and its cursor advances, or an empty page explicitly confirms exhaustion. Failures and empty pages that still claim more history enter error without automatic retry. Window replacement, reconnect, and disposal invalidate old pages; when an in-flight request may have advanced the transport cursor, the existing stream restart restores a baseline before another page is allowed. + +`loadThrough(seq)` is explicit navigation: it first adopts a staged page and then uses existing Turn-aligned paging. An ordinary in-flight request remains exclusive, and the caller continues after it settles. A jump publishes its successful prefix once at completion or a later failure, without delaying live appends. `loadingOlder` always equals `historyLoadStatus === 'loading'`. + +### Consumption intent and wakeups + +An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Motion, pointer, or unavailable positioning returns auto to none; touch and inner-scroll retain auto. Manual intent waits through these blockers rather than treating deferral as success. + +Prefetch reuses the existing 500ms reading sample, scrollend, content commits, and size notifications, coalescing them into one rAF check. It uses no IntersectionObserver or additional sample timer and measures nothing in the raw scroll event. Only a ResizeObserver entry for the scroller itself refreshes cached clientHeight during the callback's read phase; column growth does not reread viewport height. Once internal state permits an automatic request, it reads the history control's distance from the viewport and compares it with two cached viewport heights. + +`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained intent; fold-completion callbacks are registered only for manual intent. Without consumption intent, these notifications do not revive an abandoned automatic page. + +### Shared anchors and layout reads + +At `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`. + +Persistent preservation restores the captured screen position. One-shot correction retains inner and outer scrolling since capture and compensates only layout displacement; it neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. + +Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence. + +## Alternatives considered + +**Pause publication globally in Conversation.** That also blocks live tail output and expands the cross-view impact. + +**Retain a complete window snapshot in Chat.** That copies business data and can overwrite messages received while waiting. + +**Store separate coordinates and continuously track the first row for one-shot correction.** That duplicates existing paging anchors and can expand scroll ownership; share the position record and calculations while keeping lifetimes separate. + +## Acceptance criteria + +- Default single-stage calls, deferred consumption, and Turn jumps coexist; an old request cannot consume or overwrite a new one. +- Ordinary events do not revive automatic fallback; touch/inner-scroll continuation, manual completion, and unmount cleanup have focused verification. +- One-shot correction does not register persistent observation or undo intervening reader movement; existing persistent and inner preservation do not regress. +- Distance checks use cached viewport height; raw scroll listeners and consumption admission perform no layout reads. + +## Risks + +**Known issue: `preserveMovement` cannot distinguish native anchoring from reader input.** The shared correction adds changes in the outer and inner scroll positions since capture. A deterministic geometry model confirms duplicate compensation when the browser has already anchored the same prepend: an outer `scrollTop` of `0.5`, or outer `0` with inner `40`, enters the one-shot path and treats the native adjustment as movement to preserve. The resulting additional displacement is an algorithmic limitation, not evidence that every browser exhibits it. Code remains unchanged for this report-only finding; independent actual-browser verification is pending. + +Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual intent can still wait if usable positioning never becomes available; actual views need cancellation, reconnect, and anchorless-structure verification. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build. + +Reports must identify source/artifact versions, real or synthetic inputs, missing conditions, and cleanup results. V8 function or range hits are not TypeScript line/branch percentages; earlier iteration recordings, Chrome/Safari manual feedback, or a successful build do not establish a complete matrix pass for this proposal. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md new file mode 100644 index 0000000000..104b65e5a6 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md @@ -0,0 +1,101 @@ +# Agent Note: Chat 历史消费的类与交互 + +Status: proposed + +[English](2026-11-06-chat-history-consumption-details.md) | 中文 + +## Problem + +历史页的网络生命周期属于 Session,能否安全进入当前页面属于 Chat。两阶段加载需要复用现有事件发布与滚动能力,不能把业务数据、消费意图和 DOM 保位状态复制到同一个所有者。 + +## Proposal + +用户可见行为与取舍由[历史预取与安全消费](2026-11-06-chat-history-consumption.zh.md)定义。本文规定类之间的调用与生命周期,不增加独立的滚动动画或 React 提交管理。 + +### 所有者与接口 + +| 所有者 | 数据与操作 | +|---|---| +| [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` 准备并按选项消费一页;`consumeOlder()` 同步发布有效暂存页;`historyLoadStatus` 表达 idle/loading/pendingConsumption/error,`loadingOlder` 从 loading 派生并包含 Turn 跳转 | +| Session 请求记录 | 保存 generation、请求前游标、页内容、hasMore、Promise 与消费/失效标记;缓存页不提前改变可见窗口游标 | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;按阻塞原因等待或退回按钮;仅手动消费注册折叠结束通知 | +| [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | 读取内部输入/动画状态与 scrollTop,报告阻塞原因或 native/preserve/prepend;执行距离测量和已有锚点算法 | +| [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | 把既有阅读、滚动、内容及尺寸通知接到消费检查;在提交阶段结算待执行的一次补偿 | +| [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | 通过注入回调请求/消费,通过 useSession 读取状态;固定高度显示历史控件,不保存 Session 历史数据或累计 historyWasPartial | + +```text +ChatNavigation.checkHistory + ├─ pendingConsumption + intent=none → retain page until clicked + ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain consumption intent + │ ├─ motion/pointer/unavailable → auto falls back, manual waits + │ ├─ native → consumeOlder + │ ├─ prepend → capture paging position → consumeOlder → correct once after commit + │ └─ preserve → beginPreserving → consumeOlder + ├─ loading → no duplicate request + ├─ error → wait for explicit retry + └─ idle + hasMore + (manual intent or near top without following) → request a page + +Session.loadOlder + → prepareOlder reuses or creates the request + → await the captured request Promise + → consumeOlder when request identity remains valid and consumption is not deferred + +Session.prepareOlder + → network prepend → capture the page without publishing eventSource + → validate progress → pendingConsumption or error + +Session.consumeOlder + → check generation/cursor/consuming + → synchronous eventSource.prepend → existing Conversation merge and flush + → clear the request record and publish final status +``` + +### 数据生命周期 + +`isOpen` 只表达会话 `openState === 'open'`,与某页是否 `pendingConsumption` 无关。`historyWasPartial` 是客户端 Session 实例的单调事实:可见窗口曾有 `hasMore=true` 后保留到实例结束,不随组件重挂载或重连清除,不写持久化日志。 + +`prepareOlder()` 返回已有请求或创建一个请求,`loadOlder()` 等待捕获的请求 Promise 后再核对身份。旧 Promise 完成不能消费随后创建的新页。默认调用消费准备好的页;`deferConsumption` 保留有效非空页,终态空页可以直接确认耗尽。消费期间保持请求记录并设置 `consuming`,阻止同步订阅者重入,不借用网络 loading 状态。 + +普通请求先捕获传输返回页,只有请求成功且游标前进,或空页明确表示耗尽时才能消费。失败或空页仍声称有更多则进入 error,不自动重试。窗口替换、重连和销毁使旧页失效;如果在途请求可能已推进传输游标,现有流重启先恢复基线,再允许下一页。 + +`loadThrough(seq)` 是显式导航:先采用已有待消费页,再沿既有 Turn 对齐规则加载;普通请求在途时保持互斥,由调用方在其结算后继续。跳转的成功前缀在完成或后续失败时一次发布,实时追加不等待它。`loadingOlder` 始终等价于 `historyLoadStatus === 'loading'`。 + +### 消费意图与唤醒 + +自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。motion、pointer 或 unavailable 使 auto 退回 none;touch 与 inner-scroll 保留 auto。manual 在这些阻塞下继续等待,不把暂缓当成成功。 + +历史预取复用已有 500ms 阅读采样、scrollend、内容提交和尺寸通知,并合并为一次 rAF 检查。不使用 IntersectionObserver,不新增采样计时器,不在原始 scroll 事件中测量。仅 scroller 自身的 ResizeObserver 条目在回调读阶段更新 clientHeight 缓存,column 增长不重新读取视口高度。内部状态允许自动请求时,读取历史控件相对视口的位置,与缓存的两屏高度比较。 + +`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的意图;折叠结束回调只为 manual 注册。没有消费意图时这些通知不恢复已经放弃的自动页。 + +### 锚点复用与布局读取 + +顶部 `scrollTop ≤ 0.5` 使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。 + +持续保位恢复采集时的屏幕位置。一次补偿保留采集后发生的内外层滚动,只抵消布局位移;它不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 + +距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。 + +## Alternatives considered + +**在 Conversation 全局暂停发布。** 会同时阻止尾部实时输出,扩大跨视图影响。 + +**在 Chat 保存完整窗口快照。** 复制业务数据,消费时可能覆盖等待期间的新消息。 + +**为一次补偿另存坐标并持续追踪首行。** 与既有分页锚点重复,并可能扩大滚动控制;共享位置记录和计算,只区分生命周期。 + +## Acceptance criteria + +- 默认单阶段调用、延迟消费及 Turn 跳转共存,旧请求不能消费或覆盖新请求。 +- auto 回退不会被普通事件恢复;触摸与内层滚动续接、manual 完成承诺和卸载清理都有定向验证。 +- 一次补偿不注册持续观察、不撤销期间的读者滚动;既有持续保位和内层补偿不退化。 +- 距离读取使用缓存视口高度;原始滚动监听与消费准入不读取布局。 + +## Risks + +**已知问题:`preserveMovement` 无法区分原生锚定与读者输入。** 共享补偿计算会加上采集后内外层滚动位置的变化。确定性的几何模型已确认:浏览器已为同一次前插完成锚定时,外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40`,会进入一次补偿路径,把原生调整当成需要保留的移动,从而重复补偿。产生的额外位移是算法限制,不代表所有浏览器都会复现。本问题按仅报告处理,代码不变;独立真实浏览器验证仍待完成。 + +显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动操作若永远得不到可用定位条件仍可能等待;实际页面应验证取消、重连和无锚点结构。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。 + +验收报告应列明源码/产物版本、真实或合成输入、未覆盖条件以及清理结果。V8 函数或区间命中不等于 TypeScript 行/分支百分比;早期迭代的录像、Chrome/Safari 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml new file mode 100644 index 0000000000..85c5633b69 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml @@ -0,0 +1,31 @@ +# Bilingual-pair consistency record for 2026-11-06-chat-history-consumption.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md +/agent-note-chat-history-prefetch-and-safe-consumption: + en: b0bb85f8780edc41 + zh: f3576c234a2f1a99 +/agent-note-chat-history-prefetch-and-safe-consumption/problem: + en: fbdf714be9ea6c90 + zh: d9b6c07347812fc1 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal: + en: bda6c4b3dfff143e + zh: 4316f6dec6adaa50 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/manual-and-automatic-loading: + en: 2cbfd8cc05037895 + zh: 024968506e2ac994 +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation: + en: 1afb940b9b2a2fcc + zh: 8201614a80598e5b +/agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions: + en: dd4eeadd2fccab4b + zh: e05d53e63cc44ddf +/agent-note-chat-history-prefetch-and-safe-consumption/alternatives-considered: + en: 7c6d9d470c5b5c93 + zh: dc12846ee0f56aae +/agent-note-chat-history-prefetch-and-safe-consumption/acceptance-criteria: + en: b3005052df98ab10 + zh: c4bdf2bed8d23550 +/agent-note-chat-history-prefetch-and-safe-consumption/risks: + en: 2016c51019518572 + zh: e31e4e4ac09a2c5d diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md new file mode 100644 index 0000000000..bfe932f77b --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md @@ -0,0 +1,74 @@ +# Agent Note: Chat history prefetch and safe consumption + +Status: proposed + +English | [中文](2026-11-06-chat-history-consumption.zh.md) + +## Problem + +With only a Load earlier button, readers must reach the beginning of loaded history before clicking. Prefetch can reduce interruption, but a request that starts in a suitable state can return during touch dragging, a navigation change, or a fold animation. History prepending must not change the existing fold driver or simulate momentum. + +## Proposal + +Separate requesting history from consuming it. The Client Session retains at most one unconsumed page, and Chat decides whether and when to publish it. It retains the new page rather than an old window snapshot, so waiting does not block streaming at the tail. Class ownership and calls are described in the [technical details](2026-11-06-chat-history-consumption-details.md). + +### Manual and automatic loading + +A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. A temporary blocker does not complete the click; the operation ends with effective consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent. + +Automatic loading requests history after the reader leaves tail following and comes within two viewport heights of the history control. It reuses the existing 500ms reading sample, scroll completion, content commits, and size notifications, without another polling loop or IntersectionObserver. Detection can therefore wait until the next existing sample. + +A cached page and an intent to continue automatically are separate facts. Automatic loading falls back to a button on occasional conflicts instead of waiting for every state to recover. Touch and actual inner scrolling retain continuation so mobile readers need not click after every finger release. + +| State when data is ready | Automatic intent | Manual intent | +|---|---|---| +| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume with native browser anchoring | +| Stationary reading away from the top | Consume with existing reading preservation | Consume with existing reading preservation | +| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Reuse the paging anchor and correct once after prepend | +| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Retain intent until completion | +| A finger held down or actual inner scrolling | Retain intent and continue afterward | Retain intent and continue afterward | +| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Retain intent until usable | +| Tail following resumes after automatic prefetch | Keep the page and cancel automatic consumption | The click has paused tail following | +| Streaming continues at the tail | Does not itself block consumption | Does not itself block consumption | + +After fallback, scrolling, animation completion, and content notifications cannot reactivate that cached page; only a click or explicit navigation can adopt it. Requests and unconsumed pages remain mutually exclusive: no duplicate request for a cached page and no timeout that forces insertion. + +### Position and status presentation + +The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. A prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; persistent preservation elsewhere retains its existing lifetime. Reader movement during the correction interval is preserved rather than restoring the position from request time. + +The history control keeps the same height across states. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row. + +### Scope and retained decisions + +Do not add `flushSync` or change Conversation publication cadence, fold-batch targets, or ScrollFollow policy. Consumption admission reads only internal state and `scrollTop`; DOM geometry reads belong to distance confirmation and position correction. Do not add an independent persistent head-anchor controller, `batchShift`, or a per-frame compensator. + +[One fold motion](../../implemented/architecture/2026-10-13-chat-single-fold-motion.md) and [group-tree exchanges](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.md) retain ownership of folding and grouping decisions; this proposal does not supersede them. + +## Alternatives considered + +**Prepend every response immediately and compensate continuously.** That makes pagination take over existing motion; this design corrects once at the top and waits or falls back on conflicts. + +**Automatically wait for every unsafe state to recover.** That adds coordination obligations for occasional animations, navigation, and automatic continuation; retain touch continuation and manual completion, but return other automatic conflicts to the button. + +**Remove staging entirely or discard conflicting pages.** Conflicts can start during a request, and the transport history cursor may already have advanced; retaining one page is simpler than rolling back that cursor. + +**Disable loading whenever a Turn is running.** Readers still need history during long replies, so execution state cannot replace the current presentation conditions. + +**Separate IO prefetch wakeups and React synchronous-commit control.** Reuse existing sampling and publication, accepting sample latency; do not add commit scheduling without evidence of a concrete failure. + +## Acceptance criteria + +- Requests, staging, and consumption never duplicate a page request; tail streaming continues. +- Ordinary events do not revive automatic fallback; touch, inner scrolling, and manual clicks retain their specified continuation. +- Stationary and top-edge prepends preserve old content position; ordinary momentum consumption adds no outer JS scroll write. +- Failure, no progress, exhaustion, reconnect, and explicit navigation have defined outcomes without request loops or stale-page consumption. +- Control states have equal height; existing fold-driver behavior is retained, and browser evidence identifies the current build, simulated inputs, and missing cases. + +## Risks + +**Known issue: duplicate anchoring compensation.** A deterministic geometry-model reproduction shows that one-shot correction can count native anchoring for the same page as reader movement and compensate twice: this occurs with an outer `scrollTop` of `0.5`, or with outer `0` and inner `40` when native anchoring has already moved the inner position. The algorithm is therefore not universally safe. This issue is recorded without a code fix; independent verification in actual browsers is pending. The mechanism is detailed in the [technical risks](2026-11-06-chat-history-consumption-details.md#risks). + +CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. A stationary manual operation that can never obtain an anchor retains its completion intent and needs coverage for that structure. + +Audit and measurement are ongoing, so this record remains proposed. Earlier Chrome/Safari manual feedback and headless results from different iterations do not establish a complete matrix pass for the final source; actual scrollbar dragging, same-document reconnect, cross-platform input, and exceptional cleanup paths require separately attributed evidence. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md new file mode 100644 index 0000000000..31787a81b7 --- /dev/null +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md @@ -0,0 +1,74 @@ +# Agent Note: Chat 历史预取与安全消费 + +Status: proposed + +[English](2026-11-06-chat-history-consumption.md) | 中文 + +## Problem + +只提供“加载更早”按钮时,读者必须到达已加载历史的开头再点击。提前请求可以减少中断,但请求发出时适合加载,不代表返回时适合前插:读者可能开始触摸拖动、切换导航目标,或者遇到折叠动画。分页不应为了前插历史改变已有折叠驱动或模拟惯性。 + +## Proposal + +将历史请求与消费分开。客户端 Session 最多保留一页未消费的数据,Chat 决定是否以及何时发布它。数据保存为新页而不是旧窗口快照,所以等待不阻止尾部流式输出。类与调用关系见[技术细节](2026-11-06-chat-history-consumption-details.zh.md)。 + +### 手动与自动加载 + +手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。暂时不安全不算点击完成;该操作以有效消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。 + +自动加载在读者离开底部跟随、进入距历史控件两屏以内时请求。它复用已有 500ms 阅读采样及滚动结束、内容提交、尺寸通知,不新增轮询或 IntersectionObserver。代价是发现进入预取范围可能延后至下一次已有采样。 + +缓存是否存在与是否需要自动续接是两个事实。自动操作在低频冲突下退回按钮,不承诺等所有状态恢复;触摸与实际内层滚动仍保留续接,避免要求手机用户每次松手后再点击。 + +| 数据就绪时的状态 | 自动意图 | 手动意图 | +|---|---|---| +| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 浏览器原生锚定,消费 | +| 非顶部静止阅读 | 既有阅读保位,消费 | 既有阅读保位,消费 | +| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 复用分页锚点,前插后补偿一次 | +| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 保留意图,等待结束 | +| 手指按住或实际内层滚动 | 保留意图,结束后继续 | 保留意图,结束后继续 | +| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 保留意图,等待可用 | +| 自动预取后恢复底部跟随 | 保留缓存,取消自动消费 | 点击已暂停底部跟随 | +| 底部继续流式输出 | 本身不阻止消费 | 本身不阻止消费 | + +退回按钮后,滚动、动画结束和内容通知都不能重新激活该缓存页;只有点击或显式导航可以采用它。请求和待消费页仍然互斥,不为缓存页重复请求,也不超时强行插入。 + +### 位置与状态展示 + +会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;非顶部持续保位保持原生命周期。补偿期间发生的用户滚动保留,不把读者拉回请求发出时的位置。 + +历史控件各状态保持同高。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。 + +### 范围与既有决策 + +不新增 `flushSync`,不改变 Conversation 发布节奏、折叠批次目标或 ScrollFollow 的跟随策略。消费准入只读内部状态和 `scrollTop`;DOM 几何读取留在距离确认和位置补偿处。不新增独立的持续开头锚点控制器、`batchShift` 或每帧补偿器。 + +[单一折叠运动](../../implemented/architecture/2026-10-13-chat-single-fold-motion.zh.md)与[分组树交互段](../../implemented/architecture/2026-10-11-chat-group-tree-exchanges.zh.md)仍拥有折叠和分组决策,本提案不取代它们。 + +## Alternatives considered + +**任意状态下数据到达即前插,再持续补偿。** 需要分页接管已有运动;本方案只在顶部补偿一次,冲突时等待或退回按钮。 + +**所有不安全状态都自动等待恢复。** 增加低频动画、导航与自动续接的协调义务;保留触摸续接和手动完成,其他自动冲突退回按钮。 + +**完全取消暂存或直接丢弃冲突页。** 请求途中仍可能发生冲突,而且传输历史游标可能已经前移;保留一页比回滚游标更直接。 + +**运行中的 Turn 禁止加载。** 长回复期间仍需阅读历史,运行状态不能代替当前界面的消费条件。 + +**独立 IO 预取唤醒与 React 同步提交控制。** 复用已有采样和发布路径,接受采样延迟;没有具体失败证据时不增加提交调度机制。 + +## Acceptance criteria + +- 请求、暂存与消费期间不重复取页;尾部流式继续更新。 +- 自动退回按钮后不会被普通事件恢复;触摸、内层滚动和手动点击保留约定的续接。 +- 静止和顶部前插保持旧内容位置;普通惯性消费不新增 JS 外层滚动写入。 +- 页面失败、无进展、到头、重连和显式导航均有明确结果,不循环请求或消费过期页。 +- 控件各状态同高;既有折叠驱动保持行为,真实浏览器验收区分当前构建、输入模拟和未覆盖情况。 + +## Risks + +**已知问题:锚定重复补偿。** 确定性的几何模型复现表明,一次补偿可能把同一页已经发生的原生锚定当作读者移动,再补偿一次:外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40` 且原生锚定已移动内层位置时会出现。该算法因此不能视为普遍安全。本问题仅记录,不修改代码;独立的真实浏览器验证仍待完成。机制见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。 + +原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。静止手动消费若始终无法获得锚点,完成意图仍会等待,需要覆盖该特殊结构。 + +审计与测量尚在进行,本记录保持 proposed。此前 Chrome/Safari 手工反馈和不同迭代的 headless 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。 diff --git a/packages/api/session-controller/README.i18n.yaml b/packages/api/session-controller/README.i18n.yaml index 3d31867b67..94482498be 100644 --- a/packages/api/session-controller/README.i18n.yaml +++ b/packages/api/session-controller/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1fdf707322fb6996 zh: 0204f7e9d4aa3cce /session-controller/use-this-package: - en: 9cac36e3c0a32959 - zh: 37c42cc3edafa798 + en: 50fa3dd0a2ce79c8 + zh: 88bd7ea6058d2122 /session-controller/client-references: en: e8979a803ec3e194 zh: c567efcd971728ba diff --git a/packages/api/session-controller/README.md b/packages/api/session-controller/README.md index b430594b0e..f414ce78ef 100644 --- a/packages/api/session-controller/README.md +++ b/packages/api/session-controller/README.md @@ -70,7 +70,7 @@ Fork copies the exact inclusive event prefix selected by `atSeq`, including a cu A resume blocked by an existing write handle returns `session/writer-held` with the Session id; other resume failures retain `gateway/internal`. -`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` publishes one Host-selected page directly. +`loadThrough(seq)` retains older pages privately until its shared target is covered or loading ends, then publishes the successful pages as one ordered prepend. Live events remain visible while history loads. A later page failure retains the successful prefix; replacing the history window discards buffered pages from the replaced window. Ordinary `loadOlder()` prepares and consumes one Host-selected page; `{ deferConsumption: true }` retains that page until `consumeOlder()` publishes it synchronously. A retained page blocks another ordinary request without blocking live events. `historyLoadStatus` distinguishes `idle`, `loading`, `pendingConsumption`, and `error`; `loadingOlder` is derived from `loading`, including Turn jumps. Failures and pages without progress permit explicit retry rather than claiming exhaustion. `historyWasPartial` remembers an incomplete visible window for the Client Session lifetime, including reconnects, without persisting presentation state. The Client's initial `follow`, reconnect openings, and `loadOlder()` request at least 50 append-origin `user/message` and `assistant/message` events and cross at least two `turn/start` events, including the partial Turn at the loaded window's beginning. The Host stops at the first Turn start satisfying both minima, or at 500 counted messages or history exhaustion, whichever comes first. Steering does not add a Turn boundary. Intervening events accompany the page without counting toward the message budget. The optional `turnWindow` on page and follow requests supplies these minima under `maxMessages`. `loadThrough()` uses the same rules with a 200-message minimum per page; the 500-message cap does not limit the whole jump. Requests without `turnWindow` retain message-aligned paging. diff --git a/packages/api/session-controller/README.zh.md b/packages/api/session-controller/README.zh.md index 314ec58840..2a83f4504d 100644 --- a/packages/api/session-controller/README.zh.md +++ b/packages/api/session-controller/README.zh.md @@ -70,7 +70,7 @@ Fork 将 `atSeq` 选定的含边界事件前缀(包括开放轮次内的截点 恢复会话时若已有写句柄占用,返回 `session/writer-held`,并携带会话 id;其他恢复失败仍返回 `gateway/internal`。 -`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 直接发布 Host 选取的一页结果。 +`loadThrough(seq)` 在共享目标被覆盖或加载结束前私下保留较早页面,随后把成功取得的页面按顺序作为一次前插发布。历史加载期间实时事件仍然可见。后续页面失败时保留已成功取得的部分;历史窗口被替换时丢弃被替换窗口的暂存页面。普通 `loadOlder()` 准备并消费 Host 选取的一页;传入 `{ deferConsumption: true }` 时保留这一页,直到 `consumeOlder()` 同步发布。暂存页阻止重复普通请求,但不阻止实时事件。`historyLoadStatus` 区分 `idle`、`loading`、`pendingConsumption` 和 `error`;`loadingOlder` 从 `loading` 派生,包含 Turn 跳转。失败和无进展页面允许明确重试,不伪装成历史耗尽。`historyWasPartial` 在客户端 Session 生命周期内记住可见窗口曾不完整,重连保留,但不持久化呈现状态。 Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以 append 方式追加的 `user/message` 和 `assistant/message` 事件,并向前跨过至少两个 `turn/start`,其中包含已加载窗口开头尚未补齐的轮次。Host 在首次同时满足两个下限的轮次开头停止;若先达到 500 条计数消息或历史已耗尽,则立即返回。Steering 不增加轮次分界。区间内的其他事件随页返回,但不计入消息预算。分页和 follow 请求可选的 `turnWindow` 在 `maxMessages` 上限内指定这两个下限。`loadThrough()` 复用相同规则,仅将每页消息数下限设为 200;500 条上限不限制整次跳转。不带 `turnWindow` 的请求保留按消息对齐的分页方式。 diff --git a/packages/api/session-controller/src/client/contract/session.ts b/packages/api/session-controller/src/client/contract/session.ts index 9233ac84cb..ce060ec4aa 100644 --- a/packages/api/session-controller/src/client/contract/session.ts +++ b/packages/api/session-controller/src/client/contract/session.ts @@ -4,8 +4,8 @@ * ObservableSnapshot half), and orchestration code calls the behavior verbs * below — nothing else. Widening this interface is the explicit act of * widening what features may do to a session (and what every test fixture - * must stub); implementation-internal entry points (history staging, wire-frame - * dispatch) stay on the class, invisible out here. + * must stub); implementation-internal wire-frame dispatch stays on the class, + * invisible out here. */ import type { FileAttachmentRef, ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' import type { MessageId } from '@deepseek-ai/dsh-llm/brand' @@ -132,10 +132,18 @@ export interface ISession { /** * Extend history by at least 50 messages and two Turn starts, including a * partial Turn at the window's beginning. Stop at 500 messages or history - * exhaustion even when those minima cannot be met. Publish one prepend. - * @returns completion; failures land in snapshot.openState/loadingOlder. + * exhaustion even when those minima cannot be met. At most one page may be + * loading or awaiting consumption; live events remain independently visible. + * @param options - deferConsumption keeps the page unpublished until consumeOlder; omitted consumes before completion. + * @returns request completion; failures and no progress set snapshot.historyLoadStatus to error. */ - loadOlder(): Promise + loadOlder(options?: { deferConsumption?: boolean }): Promise + /** + * Publish the prepared page synchronously if its generation and starting cursor still match. + * A terminal empty page may publish hasMore=false; an invalidated page is discarded. + * @returns whether a prepared page was published; false while loading, absent, or invalidated. + */ + consumeOlder(): boolean /** * Page history backwards until the window covers `seq` (inclusive) — the * turn-jump loader. Repeated calls while a jump is paging lower its shared diff --git a/packages/api/session-controller/src/client/contract/snapshot.ts b/packages/api/session-controller/src/client/contract/snapshot.ts index 4912d19b16..b6ba71b907 100644 --- a/packages/api/session-controller/src/client/contract/snapshot.ts +++ b/packages/api/session-controller/src/client/contract/snapshot.ts @@ -78,7 +78,12 @@ export interface SessionSnapshot { readonly openState: OpenState readonly openError: RemoteFailure | null readonly hasMore: boolean + /** This Client Session has exposed an incomplete history window; remains true across replacements. */ + readonly historyWasPartial: boolean + /** Whether historyLoadStatus is loading, including Turn-jump requests. */ readonly loadingOlder: boolean + /** History request status; pendingConsumption retains an unpublished ordinary page. */ + readonly historyLoadStatus: 'idle' | 'loading' | 'pendingConsumption' | 'error' readonly promptError: PromptError | null readonly blank: boolean readonly lastAgentError: string | null diff --git a/packages/api/session-controller/src/client/sessions/session.ts b/packages/api/session-controller/src/client/sessions/session.ts index e74dd84422..60194de5eb 100644 --- a/packages/api/session-controller/src/client/sessions/session.ts +++ b/packages/api/session-controller/src/client/sessions/session.ts @@ -67,6 +67,16 @@ interface PendingHistory { readonly pages: (readonly SessionEventLikeEntry[])[] } +interface OlderHistoryRequest { + readonly generation: number + readonly beforeSeq: SessionLogOffset + page: { readonly entries: readonly SessionEventLikeEntry[]; readonly hasMore: boolean } | null + invalidated: boolean + recovering: boolean + consuming: boolean + promise?: Promise +} + /** Manager-owned observers of a Session object's local state edges. */ export interface SessionOptions { /** Catalog-discovered address selecting non-activating subagent transport. */ @@ -95,13 +105,16 @@ export class Session implements SessionFace { // ---- Window and derived state (all private; the snapshot is the only read API) ---- private baseSeq = SessionLogOffset(0) private hasMore = false + private historyWasPartial = false private openState: OpenState = 'cold' private openError: RemoteFailure | null = null private openPromise: Promise | null = null /** Bumped by stream replacement to invalidate an in-flight doOpen. Stale * passes drop all writes once the generation moves on. */ private openGeneration = 0 - private loadingOlder = false + private get loadingOlder(): boolean { return this.historyLoadStatus === 'loading' } + private historyLoadStatus: SessionSnapshot['historyLoadStatus'] = 'idle' + private olderRequest: OlderHistoryRequest | null = null /** Shared low-water target of the running jump loop; null when no jump is paging. */ private jumpTargetSeq: SessionSeq | null = null /** The running jump loop's completion, shared by retargeting callers. */ @@ -415,30 +428,95 @@ export class Session implements SessionFace { return promise } - /** Prepend one Turn-aligned page: at least 50 messages and two Turn starts, capped at 500 messages. */ - async loadOlder(): Promise { - if (this.openState !== 'open' || !this.hasMore || this.loadingOlder) return + /** @inheritdoc */ + async loadOlder(options?: { deferConsumption?: boolean }): Promise { + const request = this.prepareOlder() + await request?.promise + if (request !== null && this.olderRequest === request + && (!options?.deferConsumption || request.page?.entries.length === 0)) this.consumeOlder() + } + + private prepareOlder(): OlderHistoryRequest | null { + if (this.olderRequest !== null) return this.olderRequest const events = this.events - if (events === undefined) return - this.loadingOlder = true + if (this.openState !== 'open' || !this.hasMore || this.loadingOlder || events === undefined) return null + const request: OlderHistoryRequest = { + generation: this.openGeneration, + beforeSeq: this.baseSeq, + page: null, + invalidated: false, + recovering: false, + consuming: false, + } + this.olderRequest = request + this.historyLoadStatus = 'loading' this.notifier.markDirty() - try { - await events.prepend({ - beforeSeq: this.baseSeq, - ...HISTORY_PAGE_OPTIONS, - }) - } catch (error) { - if (!isRemoteFailure(error)) { - console.error('[session-controller] loadOlder failed:', error) + request.promise = (async () => { + try { + await events.prepend({ beforeSeq: request.beforeSeq, ...HISTORY_PAGE_OPTIONS }) + if (this.olderRequest !== request) return + if (request.invalidated || request.generation !== this.openGeneration || request.beforeSeq !== this.baseSeq) return + const page = request.page + const first = page?.entries[0] + this.historyLoadStatus = page === null || (first === undefined ? page.hasMore : first.event.seq >= request.beforeSeq) + ? 'error' : 'pendingConsumption' + } catch (error) { + if (this.olderRequest !== request) return + request.page = null + this.historyLoadStatus = 'error' + if (!isRemoteFailure(error)) console.error('[session-controller] loadOlder failed:', error) + } finally { + if (this.olderRequest === request) { + if (request.invalidated && this.events === events) { + // A replacement restores the transport cursor before another page uses the visible window. + request.recovering = true + this.historyLoadStatus = 'loading' + events.restart() + } else if (this.historyLoadStatus === 'error') this.olderRequest = null + this.notifier.markDirty() + } } + })() + return request + } + + /** @inheritdoc */ + consumeOlder(): boolean { + const request = this.olderRequest + if (request === null || request.consuming || this.historyLoadStatus !== 'pendingConsumption' || request.page === null) return false + if (this.openState !== 'open' || request.invalidated || request.generation !== this.openGeneration + || request.beforeSeq !== this.baseSeq) { + this.clearOlderHistory() + return false + } + const page = request.page + // Retain the request through synchronous feed notification so subscribers cannot reenter consumption. + request.consuming = true + try { + this.prependWindow(page.entries, page.hasMore) + return true + } catch (error) { + if (this.olderRequest === request) this.historyLoadStatus = 'error' + throw error } finally { - this.loadingOlder = false + if (this.olderRequest === request) { + this.olderRequest = null + if (this.historyLoadStatus !== 'error') this.historyLoadStatus = 'idle' + } this.notifier.markDirty() } } + private clearOlderHistory(): void { + this.olderRequest = null + this.historyLoadStatus = this.pendingHistory === null ? 'idle' : 'loading' + this.notifier.markDirty() + } + /** Jump loader: page backwards until the window covers seq (see ISession.loadThrough). */ loadThrough(seq: SessionSeq): Promise { + this.consumeOlder() + if (this.olderRequest !== null) return Promise.resolve() if (this.openState !== 'open' || !this.hasMore || this.baseSeq <= seq) return Promise.resolve() if (this.jumpPromise !== null) { // Retarget the running loop to the lowest requested seq. @@ -459,7 +537,7 @@ export class Session implements SessionFace { } this.pendingHistory = pending this.jumpTargetSeq = seq - this.loadingOlder = true + this.historyLoadStatus = 'loading' this.notifier.markDirty() // Stale-pass guard (the doOpen pattern): a resync mid-loop replaces the // stream generation; this pass then stops instead of paging the new @@ -467,27 +545,35 @@ export class Session implements SessionFace { const generation = this.openGeneration this.jumpPromise = (async () => { try { - while (pending.hasMore && this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { + while (this.jumpTargetSeq !== null && pending.beforeSeq > this.jumpTargetSeq) { if (generation !== this.openGeneration) return const before = pending.beforeSeq await events.prepend({ beforeSeq: before, ...JUMP_PAGE_OPTIONS }) + if (generation !== this.openGeneration || this.pendingHistory !== pending) return // No-progress guard: an empty or dropped page that still claims more // history must end the loop, not spin it. - if (pending.beforeSeq >= before) return + if (pending.beforeSeq >= before) { + if (pending.hasMore) this.historyLoadStatus = 'error' + return + } + if (!pending.hasMore) return } } catch (error) { + if (generation === this.openGeneration && this.pendingHistory === pending) this.historyLoadStatus = 'error' if (!isRemoteFailure(error)) { console.error('[session-controller] loadThrough failed:', error) } } finally { - this.jumpTargetSeq = null - this.jumpPromise = null - this.pendingHistory = null - this.loadingOlder = false - if (generation === this.openGeneration && pending.pages.length > 0) { - this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + if (this.pendingHistory === pending) { + this.jumpTargetSeq = null + this.jumpPromise = null + this.pendingHistory = null + if (this.historyLoadStatus === 'loading') this.historyLoadStatus = 'idle' + if (generation === this.openGeneration && pending.pages.length > 0) { + this.prependWindow(pending.pages.reverse().flat(), pending.hasMore) + } + this.notifier.markDirty() } - this.notifier.markDirty() } })() return this.jumpPromise @@ -499,6 +585,7 @@ export class Session implements SessionFace { async resync(): Promise { if (this.openState === 'cold') return // never opened: no window to rebuild (doOpen flips to 'loading' synchronously, so cold implies no in-flight open) this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -606,6 +693,7 @@ export class Session implements SessionFace { else this.retireFailedSubmission(requestId) } this.openGeneration++ + this.clearOlderHistory() const events = this.events this.events = undefined await events?.dispose() @@ -655,7 +743,9 @@ export class Session implements SessionFace { ) return case 'prepend': - this.prependWindow(change.entries, change.hasMore) + if (this.olderRequest !== null) { + this.olderRequest.page = { entries: change.entries, hasMore: change.hasMore } + } else this.prependWindow(change.entries, change.hasMore) return case 'append': this.publishAssistantEntry(this.assistantStream.acceptDurable(change.entry)) @@ -676,8 +766,13 @@ export class Session implements SessionFace { // attempts makes a held notification reopen follow once for an atomic // page/baseline pair instead of applying it to an unrelated repair cut. const visible = this.assistantStream.replace(entries, assistantStream) + if (this.olderRequest !== null && this.loadingOlder && !this.olderRequest.recovering) { + this.olderRequest.invalidated = true + this.olderRequest.page = null + } else this.clearOlderHistory() this.baseSeq = SessionLogOffset(entries[0]?.event.seq ?? 0) this.hasMore = hasMore + this.historyWasPartial ||= hasMore if (this.pendingHistory !== null) { this.pendingHistory.beforeSeq = this.baseSeq this.pendingHistory.hasMore = hasMore @@ -745,6 +840,7 @@ export class Session implements SessionFace { } this.baseSeq = entries[0] === undefined ? this.baseSeq : SessionLogOffset(entries[0].event.seq) this.hasMore = hasMore + this.historyWasPartial ||= hasMore this.eventSource.prepend(entries, hasMore) } @@ -892,6 +988,7 @@ export class Session implements SessionFace { if (generation !== this.openGeneration || this.events !== events) return if (!isRemoteFailure(error)) throw error this.openGeneration++ + this.clearOlderHistory() this.events = undefined this.openPromise = null this.openState = 'error' @@ -917,7 +1014,9 @@ export class Session implements SessionFace { openState: this.openState, openError: this.openError, hasMore: this.hasMore, + historyWasPartial: this.historyWasPartial, loadingOlder: this.loadingOlder, + historyLoadStatus: this.historyLoadStatus, promptError: this.promptError, blank: this.blankBit, lastAgentError: this.lastAgentError, diff --git a/packages/api/session-controller/tests/session.client.spec.ts b/packages/api/session-controller/tests/session.client.spec.ts index e118ef29e5..6c6d308fe9 100644 --- a/packages/api/session-controller/tests/session.client.spec.ts +++ b/packages/api/session-controller/tests/session.client.spec.ts @@ -199,6 +199,194 @@ describe('paging', () => { expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) }) + it('stages one page without hiding live events and consumes it once', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + await session.loadOlder({ deferConsumption: true }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + await pushEvent(mock, ev.turnStart(SessionSeq(12), 2)) + const consumeStates: { status: string; loading: boolean }[] = [] + const stop = session.eventSource.subscribe(() => { + session.handleRunning(true) + const snapshot = session.getSnapshot() + consumeStates.push({ status: snapshot.historyLoadStatus, loading: snapshot.loadingOlder }) + expect(session.consumeOlder()).toBe(false) + void session.loadOlder({ deferConsumption: true }) + }) + try { + expect(session.consumeOlder()).toBe(true) + } finally { + stop() + } + expect(consumeStates).toEqual([{ status: 'pendingConsumption', loading: false }]) + expect(session.consumeOlder()).toBe(false) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq).concat(SessionSeq(12))) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', hasMore: false }) + }) + + it('joins a deferred request for default consumption without requesting another page', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + const gate = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(gate.promise) + await session.open() + const preparing = session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) + const consuming = session.loadOlder() + gate.resolve(history(older)) + await Promise.all([preparing, consuming]) + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('default loading consumes an already prepared page without another request', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadOlder() + expect(mock.log.requests(PAGE)).toHaveLength(1) + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) + }) + + it('does not consume a newer prepared page when an obsolete default request completes', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + const obsolete = Promise.withResolvers() + const prepend = vi.spyOn(SessionEventStream.prototype, 'prepend').mockImplementationOnce(() => obsolete.promise) + const loading = session.loadOlder() + try { + await session.resync() + await session.loadOlder({ deferConsumption: true }) + obsolete.resolve(undefined) + await loading + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'pendingConsumption', loadingOlder: false }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + expect(session.consumeOlder()).toBe(true) + } finally { + obsolete.resolve(undefined) + await loading + prepend.mockRestore() + } + }) + + it('retains partial-history knowledge across exhaustion and replacement only for the same Session instance', async ({ mock, start }) => { + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + const complete = [...older, ...newer] + const session = await sessionBench(mock, start, SID) + expect(session.getSnapshot().historyWasPartial).toBe(false) + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + expect(session.getSnapshot().historyWasPartial).toBe(true) + await session.loadOlder() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.stream(FOLLOW, followScript(history(complete, false))) + await session.resync() + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace complete window')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(3) }) + await mock.streams.drained(FOLLOW) + expect(session.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: true }) + const client = await start() + const fresh = new Session(SID, client.ctx.remote) + onTestFinished(() => fresh.dispose()) + expect(fresh.getSnapshot().historyWasPartial).toBe(false) + await fresh.open() + expect(fresh.getSnapshot()).toMatchObject({ hasMore: false, historyWasPartial: false }) + }) + + it('reports no progress and allows an explicit retry to confirm exhaustion', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(6), 1, 'new', 'answer'), true))) + mock.remote.session.page.mockImplementation(pageRule(history([], true))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) + expect(session.consumeOlder()).toBe(false) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.loadOlder({ deferConsumption: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(mock.log.requests(PAGE)).toHaveLength(2) + }) + + it('consumes a staged page before a turn jump fetches the remaining history', async ({ mock, start }) => { + const oldest = plainTurn(SessionSeq(0), 0, 'oldest', 'answer') + const middle = plainTurn(SessionSeq(6), 1, 'middle', 'answer') + const newest = plainTurn(SessionSeq(12), 2, 'newest', 'answer') + const session = await sessionBench(mock, start, SID) + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(request => history( + request.beforeSeq === 12 ? middle : oldest, request.beforeSeq === 12, + ))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.loadThrough(SessionSeq(0)) + expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) + expect((mock.log.requests(PAGE) as SessionPageRequest[]).map(request => request.beforeSeq)).toEqual([12, 6]) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + }) + + it('invalidates a staged page when the event window is replaced', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.open() + await session.loadOlder({ deferConsumption: true }) + await session.resync() + expect(session.consumeOlder()).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: true }) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + }) + + it('repairs the transport cursor when follow replaces a window during an older request', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const older = plainTurn(SessionSeq(0), 0, 'old', 'answer') + const newer = plainTurn(SessionSeq(6), 1, 'new', 'answer') + mock.stream(FOLLOW, followScript(history(newer, true))) + const page = Promise.withResolvers>() + mock.remote.session.page.mockReturnValueOnce(page.promise) + await session.open() + const loading = session.loadOlder({ deferConsumption: true }) + await vi.waitFor(() => { expect(mock.log.requests(PAGE)).toHaveLength(1) }) + mock.streams.fail(FOLLOW, new RemoteStreamCarrierError('replace while paging')) + await vi.waitFor(() => { expect(mock.log.requests(FOLLOW)).toHaveLength(2) }) + await mock.streams.drained(FOLLOW) + page.resolve(history(older)) + await loading + await vi.waitFor(() => { + expect(mock.log.requests(FOLLOW)).toHaveLength(3) + expect(session.getSnapshot().historyLoadStatus).toBe('idle') + }) + expect(session.consumeOlder()).toBe(false) + expect(eventSeqs(session)).toEqual(newer.map(event => event.seq)) + mock.remote.session.page.mockImplementation(pageRule(history(older))) + await session.loadOlder() + expect(eventSeqs(session)).toEqual([...older, ...newer].map(event => event.seq)) + }) + it('installs a page without interpreting business replacement metadata', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history([ @@ -218,7 +406,7 @@ describe('paging', () => { } }) - it('drops a discontinuous older page fail-soft (window unchanged, hasMore cleared)', async ({ mock, start }) => { + it('reports a discontinuous older page without claiming history exhaustion', async ({ mock, start }) => { const session = await sessionBench(mock, start, SID) mock.stream(FOLLOW, followScript(history(plainTurn(SessionSeq(10), 1, '新', '页'), true))) mock.remote.session.page.mockImplementation(pageRule(history(plainTurn(SessionSeq(0), 0, '断', '层'), true))) // tail seq 5, but baseSeq is 10 → hole @@ -229,7 +417,7 @@ describe('paging', () => { await session.loadOlder() const snapshot = session.getSnapshot() expect(session.eventSource.getSnapshot().entries).toEqual(windowBefore.entries) - expect(snapshot.hasMore).toBe(false) + expect(snapshot).toMatchObject({ hasMore: true, historyLoadStatus: 'error' }) } finally { errorSpy.mockRestore() } @@ -247,11 +435,11 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(request => (request.beforeSeq === 12 ? history(middle, true) : history(oldest)))) mock.remote.session.page.mockReturnValueOnce(gate.promise) const jump = session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(true) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'loading', loadingOlder: true }) gate.resolve(history(middle, true)) await jump const snapshot = session.getSnapshot() - expect(snapshot.loadingOlder).toBe(false) + expect(snapshot).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false }) expect(eventSeqs(session)).toEqual([...oldest, ...middle, ...newest].map(event => event.seq)) expect(mock.log.requests(PAGE)).toMatchObject([ { beforeSeq: 12, maxMessages: 500, turnWindow: { minMessages: 200, minTurns: 2 } }, @@ -325,7 +513,7 @@ describe('paging', () => { expect(changed).toHaveBeenCalledOnce() expect(eventSeqs(session)).toEqual([...middle, ...newest].map(event => event.seq)) - expect(session.getSnapshot()).toMatchObject({ loadingOlder: false, hasMore: true }) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false, hasMore: true }) }) it('discards buffered jump pages when the Session replaces its stream', async ({ mock, start }) => { @@ -430,7 +618,19 @@ describe('paging', () => { mock.remote.session.page.mockImplementation(pageRule(history([], true))) // empty page still claiming more history await session.open() await session.loadThrough(SessionSeq(0)) - expect(session.getSnapshot().loadingOlder).toBe(false) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'error', loadingOlder: false }) + expect(mock.log.requests(PAGE)).toHaveLength(1) + }) + + it('loadThrough treats a terminal empty page as exhaustion rather than an error', async ({ mock, start }) => { + const session = await sessionBench(mock, start, SID) + const newest = plainTurn(SessionSeq(12), 2, 'x', 'y') + mock.stream(FOLLOW, followScript(history(newest, true))) + mock.remote.session.page.mockImplementation(pageRule(history([], false))) + await session.open() + await session.loadThrough(SessionSeq(0)) + expect(session.getSnapshot()).toMatchObject({ historyLoadStatus: 'idle', loadingOlder: false, hasMore: false }) + expect(eventSeqs(session)).toEqual(newest.map(event => event.seq)) expect(mock.log.requests(PAGE)).toHaveLength(1) }) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index 2e047aefad..b17f85460e 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,8 +36,8 @@ en: e2b02942a55fb669 zh: a38bbee0cc69ae4e /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: dd4e69828096c3a0 - zh: 2a9bc370f44efcd7 + en: a8e5c51345ef61b9 + zh: 0e65169b79504da8 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 562ed7ebef..8df3db6b32 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -184,7 +184,9 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatViewport` owns turn-aware DOM reads, clamped writes, native events, and one retained paging anchor. For Load older, Node and Group seats mark eligible anchors from their existing disclosure state. The viewport selects the first nonempty, unhidden marker in transcript order without hit testing or geometry-based search, then measures that element and its scroll containers. It compensates the anchor's capped group first, then gives the remaining displacement to the transcript scrollport. An inner compensation write cancels that group's animation through its bound controller and pauses following; reader scrolling back to the bottom resumes it. Commits and later content resizes reuse that anchor; a remounted row is resolved by the same semantic key. Compensation stays within the actual scroll ranges without adding bottom space. -`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it; while a page is still loading, `scrollend` captures the reader's new position. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. +`useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it. A deferred history request captures its anchor at consumption rather than at request time. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. + +History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and inner scrolling retain automatic intent until release; active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation. Stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. At scrollTop ≤ 0.5, the first paging anchor supplies one content-displacement correction that retains intervening reader movement and then releases immediately. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 7696d53951..c2144fd861 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -184,7 +184,9 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatViewport` 负责识别轮次的 DOM 读取、限制范围后的写入、原生事件及一个持续保留的分页锚点。加载更早时,Node 与 Group 容器根据已有开合状态标记可选锚点。视口按正文顺序选择第一个非空、未隐藏的标记,不做命中测试或按几何位置搜索,再测量该元素及其滚动容器。先补偿锚点所在的限高组,再把剩余位移交给整段文本的滚动区域。内层补偿写入通过该组绑定的控制器取消动画并暂停跟随,读者滚回底部后恢复。提交和后续内容尺寸变化复用该锚点;消息行重挂载时按同一语义 key 重新定位。补偿限于实际可滚动范围,不增加底部空白。 -`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点;分页仍在加载时,`scrollend` 会记录读者的新位置。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 +`useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点。延迟消费的历史请求在消费时采集锚点,不在发请求时采集。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 + +历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和内层滚动保留自动意图至释放;动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。明确点击保留意图,直到消费、到头、失败或被新导航取代。静止消费使用保位,普通外层滚动使用浏览器锚定;scrollTop ≤ 0.5 时用首条分页锚点补偿一次内容位移,保留期间的读者滚动,随后立即释放。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 diff --git a/packages/client/ui-chat/src/client/apply.ts b/packages/client/ui-chat/src/client/apply.ts index 084e45e414..7e4a3a5f01 100644 --- a/packages/client/ui-chat/src/client/apply.ts +++ b/packages/client/ui-chat/src/client/apply.ts @@ -287,7 +287,8 @@ export function apply(ctx: Context): void { window.open(url, '_blank', 'noopener,noreferrer') } }, - loadOlder: () => { void session.loadOlder() }, + loadOlder: () => { void session.loadOlder({ deferConsumption: true }) }, + consumeOlder: () => session.consumeOlder(), loadThrough: seq => session.loadThrough(seq), loadImage: Object.assign( (attachment: ImageAttachmentRef) => ctx.uiConversation.imageUrl(sessionId, attachment), diff --git a/packages/client/ui-chat/src/client/chat/ChatView.module.css b/packages/client/ui-chat/src/client/chat/ChatView.module.css index 9929770b35..1f84e97842 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.module.css +++ b/packages/client/ui-chat/src/client/chat/ChatView.module.css @@ -37,6 +37,11 @@ container-type: inline-size; } +.scroll, +:global([data-conversation-scroll]):has(.root) { + overscroll-behavior-y: none; +} + .root[data-chat-following-tail] .scroll, :global([data-conversation-scroll]):has(.root[data-chat-following-tail]) { overflow-anchor: none; @@ -318,11 +323,15 @@ } .older { + overflow-anchor: none; display: flex; justify-content: center; } .older button { + display: grid; + line-height: 18px; + white-space: nowrap; border: none; border-radius: var(--dsw-radius-sm); padding: 4px 12px; @@ -332,6 +341,14 @@ cursor: pointer; } +.older button > span { + grid-area: 1 / 1; +} + +.historyHidden { + visibility: hidden; +} + .older button:disabled { cursor: default; opacity: 0.6; diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 48e081bfa8..8fa10ca0ec 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -63,7 +63,7 @@ const MOTION_TAIL_MS = 800 export function ChatView({ useSession, useChat, useConversation, useSessions, renderSlot, sessionId, openFile, openExternalLink, resolveFilePath, useContextMenu, - loadOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, + loadOlder, consumeOlder, loadThrough, loadImage, inspectCall, chatScroll, forkAt, usePresentation, useProjection, useInteractionIds, dispatchInteraction, t, fileDrag, }: ChatViewSlotProps) { const { getTriggerProps } = useContextMenu() @@ -136,6 +136,8 @@ export function ChatView({ const openError = useSession(s => s.openError) const hasMore = useSession(s => s.hasMore) const loadingOlder = useSession(s => s.loadingOlder) + const historyLoadStatus = useSession(s => s.historyLoadStatus) + const historyWasPartial = useSession(s => s.historyWasPartial) 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 @@ -211,8 +213,9 @@ export function ChatView({ const steeringId = latestSteering?.source.kind === 'user' && 'rpcId' in latestSteering.source ? latestSteering.source.rpcId : latestSteering?.id ?? null const scroll = useChatScroll({ - ready: openState === 'open', - order, firstSeq, lastKey, running, loadingOlder, hasMore, chatScroll, loadOlder, loadThrough, deferCompletedTurns, + isOpen: openState === 'open', + order, firstSeq, lastKey, running, loadingOlder, historyLoadStatus, hasMore, chatScroll, + loadOlder, consumeOlder, loadThrough, deferCompletedTurns, lastIsUser: lastKey !== null && nodeStore.get(lastKey)?.kind === 'user', steeringId, submissionId: visibleSubmissions.at(-1)?.requestId ?? null, @@ -247,10 +250,24 @@ export function ChatView({ {t('chat.loadError', { message: openError.message, code: openError.code })}
)} - {hasMore && ( -
-
)} diff --git a/packages/client/ui-chat/src/client/chat/flow-motion.ts b/packages/client/ui-chat/src/client/chat/flow-motion.ts index b34c1f2645..7deddd0e9a 100644 --- a/packages/client/ui-chat/src/client/chat/flow-motion.ts +++ b/packages/client/ui-chat/src/client/chat/flow-motion.ts @@ -72,6 +72,8 @@ export interface InputFoldDriver { /** Animation lifetime and fold coordination for one viewport. */ export interface FlowMotion extends FlowMotionRows { + /** @returns whether owned transitions or a scheduled, running, or settling batch remain active. */ + active(): boolean /** @returns whether a row owned by this viewport is closing. */ foldActive(): boolean /** @param listener - callback after the last fold. @returns cancellation for a pending callback. */ @@ -494,6 +496,7 @@ export function createFlowMotion( return { collapse, reveal, cancelMotion, foldActive, onFoldIdle, cancelInput, resumeInput, clear, hideNow, + active: () => running.size > 0 || batchScheduled || batch || settling, inputActive: () => batch || (batchScheduled && [...boxes.values()].some(box => box.closing && batchMember(box))), } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts index 84e2b3ec77..3d5dbed544 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-navigation.ts @@ -1,5 +1,6 @@ /** Turn jumps and history-prepend anchoring, independent of DOM measurement. */ import { useLayoutEffect, useState } from 'react' +import type { SessionSnapshot } from '@deepseek-ai/dsh-api-session-controller/client' import type { SessionSeq } from '@deepseek-ai/dsh-session/types' import type { ChatNode } from '../contract/chat-nodes.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -8,10 +9,12 @@ import type { ChatReading, ReadingSample } from './use-chat-reading.ts' import type { ChatViewport } from './use-chat-viewport.ts' /** History availability and loading operations for the committed Chat window. */ -export interface ChatNavigationInput extends Pick { +export interface ChatNavigationInput extends Pick { readonly firstSeq: ChatNode['anchorSeq'] | null readonly hasMore: boolean readonly loadingOlder: boolean + readonly historyLoadStatus: SessionSnapshot['historyLoadStatus'] + readonly isOpen: boolean } interface TurnJump { @@ -22,23 +25,34 @@ interface TurnJump { repageHead: ChatNavigationInput['firstSeq'] } +type HistoryIntent = 'none' | 'auto' | 'manual' + /** Owns one replaceable turn jump and the anchor retained while history loads. */ export class ChatNavigation { private jump: TurnJump | null = null private settleFrame: number | null = null + private historyFrame: number | null = null + private stopFoldWait: (() => void) | null = null + private historyIntent: HistoryIntent = 'none' + private historyRequested = false constructor( private readonly viewport: ChatViewport, private readonly reading: ChatReading, private input: ChatNavigationInput, private readonly onBusyTurn: (turn: number | null) => void, + private readonly onHistoryIntent: (intent: HistoryIntent) => void = () => {}, ) {} /** * Adopt committed history availability without starting a request. * @param input - history state from the latest committed render. */ - setInput(input: ChatNavigationInput): void { this.input = input } + setInput(input: ChatNavigationInput): void { + this.input = input + this.historyRequested = false + if (!input.isOpen || input.historyLoadStatus === 'error' || !input.hasMore) this.setHistoryIntent('none') + } /** Cancel navigation when opening a Chat view. */ reset(): void { @@ -48,10 +62,21 @@ export class ChatNavigation { /** Cancel local callbacks; late history completions cannot revive a task. */ dispose(): void { this.clearTask() + if (this.historyFrame !== null) cancelAnimationFrame(this.historyFrame) + this.historyFrame = null + this.stopFoldWait?.() + this.stopFoldWait = null } /** Release the jump, paging anchor, and busy indicator without cancelling shared history I/O. */ cancel(): void { + this.setHistoryIntent('none') + this.clearTask() + this.onBusyTurn(null) + } + + /** Release a jump after reader input without cancelling an accepted history click. */ + readerInteracted(): void { this.clearTask() this.onBusyTurn(null) } @@ -60,6 +85,7 @@ export class ChatNavigation { this.cancelFrame() this.jump = null this.viewport.stopPreserving() + this.viewport.cancelHistoryPrepend() } /** @@ -90,12 +116,99 @@ export class ChatNavigation { this.request(jump) } - /** Request one older page while retaining the current semantic position. */ + /** Request and consume one page, retaining the click until success, exhaustion, or failure. */ readonly loadEarlier = (): void => { this.cancel() - this.viewport.beginPaging() + this.setHistoryIntent('manual') this.reading.pauseFollowing() - this.input.loadOlder() + if (this.input.historyLoadStatus === 'error') { + this.historyRequested = true + this.input.loadOlder() + } else this.requestHistoryCheck() + } + + private setHistoryIntent(intent: HistoryIntent): void { + if (intent === this.historyIntent) return + this.historyIntent = intent + if (intent !== 'manual') { + this.stopFoldWait?.() + this.stopFoldWait = null + } + this.onHistoryIntent(intent) + } + + /** Coalesce event-driven checks; waiting never schedules its own next frame. */ + requestHistoryCheck(): void { + if (!this.input.isOpen || this.input.historyLoadStatus === 'error') return + if (this.historyIntent === 'none' && (this.input.historyLoadStatus !== 'idle' + || !this.input.hasMore || this.reading.followingTail)) return + if (this.historyFrame !== null || typeof requestAnimationFrame !== 'function') return + this.historyFrame = requestAnimationFrame(() => { + this.historyFrame = null + this.checkHistory() + }) + } + + private checkHistory(): void { + const input = this.input + if (!input.isOpen || this.jump !== null || this.historyRequested || input.loadingOlder) return + if (input.historyLoadStatus === 'error') return + if (input.historyLoadStatus === 'pendingConsumption') { + if (this.historyIntent === 'none') return + if (this.reading.followingTail && this.historyIntent === 'auto') { + this.setHistoryIntent('none') + return + } + const mode = this.viewport.historyConsumption() + switch (mode) { + case 'touch': + case 'inner-scroll': + return + case 'motion': + case 'pointer': + case 'unavailable': + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + else if (mode === 'motion' && this.viewport.motion.foldActive()) { + this.stopFoldWait ??= this.viewport.motion.onFoldIdle(() => { + this.stopFoldWait = null + this.requestHistoryCheck() + }) + } + return + case 'prepend': + if (!this.viewport.beginHistoryPrepend() && input.firstSeq !== null) { + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + return + } + break + case 'preserve': + case 'native': + break + } + if (mode === 'preserve') { + this.viewport.beginPreserving() + if (!this.viewport.preserving) this.viewport.beginPaging() + if (!this.viewport.preserving && input.firstSeq !== null) { + if (this.historyIntent === 'auto') this.setHistoryIntent('none') + return + } + this.reading.pauseFollowing() + } + this.historyRequested = true + const consumed = input.consumeOlder() + if (consumed) this.setHistoryIntent('none') + else { + this.historyRequested = false + if (mode === 'preserve') this.viewport.stopPreserving() + if (mode === 'prepend') this.viewport.cancelHistoryPrepend() + } + return + } + if (!input.hasMore || this.historyIntent !== 'manual' && (this.reading.followingTail + || !this.viewport.confirmHistoryStart())) return + if (this.historyIntent === 'none') this.setHistoryIntent('auto') + this.historyRequested = true + input.loadOlder() } /** @@ -120,13 +233,6 @@ export class ChatNavigation { return true } - /** Retarget a still-loading page only after inner or outer reader scrolling ends. */ - readerSettled(): void { - if (this.input.loadingOlder && this.jump === null && !this.viewport.preserving && !this.reading.followingTail) { - this.viewport.beginPreserving() - } - } - /** Land, retry, or complete the current jump against the committed window. */ reconcile(): void { const jump = this.jump @@ -197,10 +303,11 @@ export class ChatNavigation { */ export function useChatNavigation( viewport: ChatViewport, reading: ChatReading, input: ChatNavigationInput, -): { navigation: ChatNavigation; busyTurn: number | null } { +): { navigation: ChatNavigation; busyTurn: number | null; historyPending: boolean; historyProcessing: boolean } { const [busyTurn, setBusyTurn] = useState(null) - const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn)) + const [historyIntent, setHistoryIntent] = useState('none') + const [navigation] = useState(() => new ChatNavigation(viewport, reading, input, setBusyTurn, setHistoryIntent)) useLayoutEffect(() => { navigation.setInput(input) }, [navigation, input]) useLayoutEffect(() => () => { navigation.dispose() }, [navigation]) - return { navigation, busyTurn } + return { navigation, busyTurn, historyPending: historyIntent === 'manual', historyProcessing: historyIntent !== 'none' } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts index 7924a33e3f..c8254dc626 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-scroll.ts @@ -1,5 +1,5 @@ /** Composes viewport operations, reading policy, and history navigation for Chat. */ -import { useCallback, useLayoutEffect, useMemo, useRef, type RefObject } from 'react' +import { useCallback, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react' import type { TranscriptViewMode } from '../../chat-settings.ts' import type { ChatSnapshot } from '../contract/snapshot.ts' import type { ChatViewSlotProps } from '../contract/slots.ts' @@ -11,7 +11,6 @@ import type { FlowMotionRows } from './flow-motion.ts' /** Committed content and Session operations used to reconcile scroll ownership. */ export interface ChatScrollInput extends ChatNavigationInput { readonly chatScroll: ChatViewSlotProps['chatScroll'] - readonly ready: boolean readonly order: readonly string[] readonly lastKey: string | null readonly lastIsUser: boolean @@ -33,12 +32,16 @@ interface ChatScrollState extends ChatReadingState { readonly busyTurn: number | null readonly navigateToTurn: ChatNavigation['navigateToTurn'] readonly loadEarlier: ChatNavigation['loadEarlier'] + readonly historyInputHeld: boolean + readonly historyProcessing: boolean + readonly historyPending: boolean + readonly historyEdgeRef: (element: HTMLDivElement | null) => void readonly returnToBottom: () => void readonly motion: FlowMotionRows } /** - * Coordinate scroll policy after Chat content commits. Initial history must be ready + * Coordinate scroll policy after Chat content commits. Initial history must be available * before automatic scroll or resize handling can initialize reading state and fold motion. * New submitted input supersedes pending reader sampling. * @param input - current Chat content, scroll memory, and history operations. @@ -46,15 +49,17 @@ interface ChatScrollState extends ChatReadingState { */ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const { - ready, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, - deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, loadOlder, loadThrough, transcriptView, + isOpen, order, firstSeq, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, + deferCompletedTurns, loadedTurns, chatScroll, hasMore, loadingOlder, historyLoadStatus, + loadOlder, consumeOlder, loadThrough, transcriptView, } = input const { viewport, listRef, columnRef } = useChatViewport() + const [historyInputHeld, setHistoryInputHeld] = useState(false) const { reading, state } = useChatReading(viewport, chatScroll, loadedTurns.at(-1)?.turn ?? null) const navigationInput = useMemo(() => ({ - firstSeq, loadingOlder, hasMore, loadOlder, loadThrough, - }), [firstSeq, loadingOlder, hasMore, loadOlder, loadThrough]) - const { navigation, busyTurn } = useChatNavigation(viewport, reading, navigationInput) + firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough, + }), [firstSeq, loadingOlder, hasMore, historyLoadStatus, isOpen, loadOlder, consumeOlder, loadThrough]) + const { navigation, busyTurn, historyPending, historyProcessing } = useChatNavigation(viewport, reading, navigationInput) const content = useRef<{ input: ChatScrollInput; applied: ChatScrollInput | null; opened: boolean }>({ input, applied: null, opened: false, }) @@ -64,7 +69,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const processContent = useCallback(() => { const current = content.current.input - if (!current.ready && !content.current.opened) return + if (!current.isOpen && !content.current.opened) return const previous = content.current.applied const steeringInput = current.steeringId !== null && current.steeringId !== previous?.steeringId && current.steeringId !== previous?.submissionId @@ -73,7 +78,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const ownInput = (current.lastIsUser && current.lastKey !== previous?.lastKey) || steeringInput || submissionInput if (reading.pending && !ownInput) return content.current.applied = current - if (current.ready && !content.current.opened) { + if (current.isOpen && !content.current.opened) { content.current.opened = true navigation.reset() reading.restore() @@ -92,7 +97,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { navigation.reconcile() return } - const tipChanged = previous === null || current.ready !== previous.ready + const tipChanged = previous === null || current.isOpen !== previous.isOpen || current.firstSeq !== previous.firstSeq || current.lastKey !== previous.lastKey || current.order.length !== previous.order.length || current.running !== previous.running || current.steeringId !== previous.steeringId || current.submissionId !== previous.submissionId @@ -112,12 +117,17 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { }, scrollEnd: (outer) => { reading.onScrollEnd(outer) - navigation.readerSettled() + navigation.requestHistoryCheck() + }, + interact: () => { navigation.readerInteracted() }, + history: () => { + setHistoryInputHeld(viewport.historyInputHeld) + if (content.current.opened) navigation.requestHistoryCheck() }, - interact: () => { navigation.cancel() }, intent: () => { cancelPendingFollow(); reading.interruptFollow() }, resize: () => { if (!content.current.opened) return + navigation.requestHistoryCheck() if (navigation.contentCommitted()) { navigation.reconcile() return @@ -129,6 +139,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { const disconnectReading = reading.connect((sample) => { navigation.readerSampled(sample) processContent() + navigation.requestHistoryCheck() }) return () => { disconnectViewport() @@ -141,7 +152,7 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { useLayoutEffect(() => { const previous = content.current.input content.current.input = { - ready, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, + order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, ...navigationInput, } if (!deferCompletedTurns) { @@ -149,13 +160,18 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { reading.interruptFollow() } viewport.updateTurns(loadedTurns) - const layoutChanged = previous.order !== order || previous.ready !== ready - if (layoutChanged) viewport.invalidate() + const layoutChanged = previous.order !== order || previous.isOpen !== isOpen + if (layoutChanged) { + const landing = viewport.finishHistoryPrepend() + if (landing !== null) reading.preservePosition(landing) + viewport.invalidate() + } viewport.reclaimBelow() processContent() if (layoutChanged && content.current.opened) reading.refreshActiveTurn() + if (content.current.opened) navigation.requestHistoryCheck() }, [ - viewport, reading, processContent, navigationInput, ready, order, lastKey, lastIsUser, + viewport, reading, processContent, navigationInput, isOpen, order, lastKey, lastIsUser, steeringId, submissionId, submissionSteers, running, loadedTurns, chatScroll, deferCompletedTurns, transcriptView, cancelPendingFollow, ]) @@ -182,6 +198,10 @@ export function useChatScroll(input: ChatScrollInput): ChatScrollState { listRef, columnRef, ...state, busyTurn, motion: viewport.motion, navigateToTurn: navigation.navigateToTurn, loadEarlier: navigation.loadEarlier, + historyPending, + historyProcessing, + historyInputHeld, + historyEdgeRef: viewport.setHistoryEdge, returnToBottom, } } diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index b0dbf7528a..98c6ac2186 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -26,6 +26,8 @@ interface ViewportEvents { interact: () => void /** Any reading gesture, before paging ownership is consulted. */ intent?: () => void + /** Recheck a prepared history page after an input or transition settles. */ + history?: () => void } interface ViewportElements { @@ -65,7 +67,7 @@ interface ClosingLayout { interface PagingPosition { readonly row: HTMLElement readonly position: ChatScrollPosition - readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null + readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number; readonly scrollTop: number } | null } const READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const @@ -79,7 +81,13 @@ export class ChatViewport { private turns: ReturnType = [] private observation: { top: number; landing: ViewportLanding | null } = { top: 0, landing: null } private paging: PagingPosition | null = null + private historyPrepend: PagingPosition | null = null private reader: FoldReader | null = null + private historyEdge: HTMLElement | null = null + private historyHeight = 0 + private historyScrolling = new Set() + private historyPointer = false + private historyTouch = false /** Rows measured before an instant close; see {@link ChatViewport.keepAboveClosing}. */ private closing: ClosingLayout | null = null /** Discards a closing measurement that no size observation consumed by the end of its frame. */ @@ -114,18 +122,26 @@ export class ChatViewport { const elements = { list, column, scroller, composer, spacer } this.elements = elements if (spacer !== null) spacer.style.height = '' + scroller.addEventListener('scroll', this.onHistoryScroll, { passive: true, capture: true }) + scroller.addEventListener('pointerdown', this.onHistoryPointerDown, { passive: true, capture: true }) + scroller.addEventListener('touchstart', this.onHistoryTouch, { passive: true, capture: true }) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller.ownerDocument.addEventListener(type, this.onHistoryRelease, true) + } scroller.addEventListener('scroll', this.onScroll, { passive: true }) scroller.addEventListener('scrollend', this.onScrollEnd, { passive: true, capture: true }) for (const type of READING_INTENTS) scroller.addEventListener(type, this.onIntent, { passive: true, capture: true }) if (typeof ResizeObserver !== 'undefined') { - this.observer = new ResizeObserver(() => { + this.observer = new ResizeObserver((entries) => { if (this.elements !== elements) return // Read while layout is still clean, before this callback writes room or scroll positions. Those writes // leave the content height unchanged, so it is also the content this frame paints. + if (entries.some(entry => entry.target === elements.scroller)) this.historyHeight = elements.scroller.clientHeight this.settledContent = elements.scroller.scrollHeight - this.spacerHeight() this.keepAboveClosing() this.reclaimBelow() this.invalidate() + this.pruneHistoryScrolling() this.events?.resize() }) this.observer.observe(column) @@ -136,10 +152,22 @@ export class ChatViewport { /** Disconnect DOM resources and clear observations for the detached view. */ detach(): void { + this.historyPrepend = null this.stopPreserving() this.motion.clear() if (this.elements !== null) this.elements.scroller.style.overflowAnchor = '' this.dropClosing() + const scroller = this.elements?.scroller + scroller?.removeEventListener('scroll', this.onHistoryScroll, true) + scroller?.removeEventListener('pointerdown', this.onHistoryPointerDown, true) + scroller?.removeEventListener('touchstart', this.onHistoryTouch, true) + for (const type of ['pointerup', 'pointercancel', 'touchend', 'touchcancel', 'transitionend', 'transitioncancel']) { + scroller?.ownerDocument.removeEventListener(type, this.onHistoryRelease, true) + } + this.historyHeight = 0 + this.historyScrolling.clear() + this.historyPointer = false + this.historyTouch = false this.elements?.scroller.removeEventListener('scroll', this.onScroll) this.elements?.scroller.removeEventListener('scrollend', this.onScrollEnd, true) for (const type of READING_INTENTS) this.elements?.scroller.removeEventListener(type, this.onIntent, true) @@ -772,10 +800,14 @@ export class ChatViewport { /** Retain the first eligible transcript seat in DOM order; selection reads no geometry. */ beginPaging(): void { this.stopPreserving() - const row = this.elements?.list.querySelector( + const row = this.pagingAnchor() + if (row !== null) this.retain(row) + } + + private pagingAnchor(): HTMLElement | null { + return this.elements?.list.querySelector( '[data-chat-paging-anchor]:not(:empty):not([hidden]):not([hidden] *)', - ) - if (row != null) this.retain(row) + ) ?? null } /** @@ -790,18 +822,17 @@ export class ChatViewport { this.retain(row, position) } - private retain(row: HTMLElement, position?: ChatScrollPosition, groupTop?: number): PagingPosition | null { + private measurePaging(row: HTMLElement, position?: ChatScrollPosition, previousGroup?: PagingPosition['group']): PagingPosition | null { const elements = this.elements const key = row.dataset.chatAnchorKey if (elements === null || key === undefined) return null - const previous = this.paging?.group - if (previous != null) this.observer?.unobserve(previous.content) const top = row.getBoundingClientRect().top const body = row.closest('[data-step-process-body]') const content = body?.querySelector('[data-step-process-content]') const group = body === null || content == null ? null - : { body, content, top: groupTop ?? top - body.getBoundingClientRect().top } - this.paging = { + : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top, + scrollTop: previousGroup?.body === body ? previousGroup.scrollTop : body.scrollTop } + return { row, group, position: position ?? { anchorKey: key, @@ -809,8 +840,19 @@ export class ChatViewport { scrollTop: elements.scroller.scrollTop, }, } - if (group !== null) this.observer?.observe(group.content) - return this.paging + } + + private retain(row: HTMLElement, position?: ChatScrollPosition): PagingPosition | null { + const paging = this.measurePaging(row, position) + if (paging === null) return null + this.retainPaging(paging) + return paging + } + + private retainPaging(paging: PagingPosition): void { + this.stopPreserving() + this.paging = paging + if (paging.group !== null) this.observer?.observe(paging.group.content) } /** Release paging ownership and its content-size observation. */ @@ -832,28 +874,39 @@ export class ChatViewport { * @returns the actual landing, or null when no visible retained row remains. */ preserve(): ViewportLanding | null { - let paging = this.paging + const paging = this.resolvePaging(this.paging) + if (paging === null) { + this.stopPreserving() + return null + } + if (paging !== this.paging) this.retainPaging(paging) + return this.applyPaging(paging, false) + } + + private resolvePaging(paging: PagingPosition | null): PagingPosition | null { const elements = this.elements if (paging === null || elements === null) return null if (!elements.list.contains(paging.row)) { // Segmentation can remount the same semantic row under another group. const replacement = this.anchor(paging.position.anchorKey) - if (replacement === null) { - this.stopPreserving() - return null - } - paging = this.retain(replacement, paging.position, paging.group?.top) + if (replacement === null) return null + paging = this.measurePaging(replacement, paging.position, paging.group) if (paging === null) return null } + return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging + } + + /** Content correction includes reader movement since capture; screen preservation restores the captured position. */ + private applyPaging(paging: PagingPosition, preserveMovement: boolean): ViewportLanding | null { + const elements = this.elements + if (elements === null) return null const { row, group, position } = paging - if (row.closest('[hidden]') !== null || row.matches(':empty')) { - this.stopPreserving() - return null - } + let innerMovement = 0 if (group !== null && group.body.contains(row)) { const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top const metrics = scrollMetrics(group.body) - const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top)) + if (preserveMovement) innerMovement = metrics.top - group.scrollTop + const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top + innerMovement)) if (metrics.top !== target) { const follow = ScrollFollow.forElement(group.body) if (follow === undefined) group.body.scrollTop = target @@ -866,7 +919,8 @@ export class ChatViewport { const metrics = this.metrics() if (metrics === null) return null const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top - const target = metrics.top + top - position.anchorTop + const movement = preserveMovement ? metrics.top - position.scrollTop + innerMovement : 0 + const target = metrics.top + top - position.anchorTop + movement return this.write(target, metrics, null, { key: position.anchorKey, top }) } @@ -919,6 +973,111 @@ export class ChatViewport { return landing } + /** + * Track the history control for request-distance checks. + * @param element - stable history control, or null when its view unmounts. + */ + readonly setHistoryEdge = (element: HTMLDivElement | null): void => { + this.historyEdge = element + } + + private pruneHistoryScrolling(): void { + for (const target of this.historyScrolling) { + if (!(target instanceof HTMLElement) || this.elements?.scroller.contains(target) !== true) { + this.historyScrolling.delete(target) + } + } + } + + /** + * Confirm the actual history distance immediately before an automatic request. + * @returns whether the control is within two viewport heights. + */ + confirmHistoryStart(): boolean { + const scroller = this.elements?.scroller + if (scroller === undefined || this.historyEdge === null || this.historyHeight <= 0) return false + const distance = scroller.getBoundingClientRect().top - this.historyEdge.getBoundingClientRect().bottom + return distance <= this.historyHeight * 2 + } + + /** + * Expose held input to history status copy. + * @returns whether a touch or pointer remains down. + */ + get historyInputHeld(): boolean { return this.historyTouch || this.historyPointer } + + /** + * Expose reader activity that prevents stationary preservation. + * @returns whether input is held or scrolling has not ended. + */ + get historyReaderActive(): boolean { + this.pruneHistoryScrolling() + return this.historyTouch || this.historyPointer || this.historyScrolling.size > 0 + } + + /** + * Select consumption behavior from current input and motion state. + * @returns the blocker or positioning path for a prepared page. + */ + historyConsumption(): 'motion' | 'touch' | 'pointer' | 'inner-scroll' | 'unavailable' | 'native' | 'preserve' | 'prepend' { + const elements = this.elements + if (elements === null) return 'unavailable' + if (this.motion.active() || this.reader?.follow.animating) return 'motion' + if (this.historyTouch) return 'touch' + if (this.historyPointer) return 'pointer' + if (this.historyScrolling.size === 0) return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'preserve' + if (this.historyScrolling.size !== 1 || !this.historyScrolling.has(elements.scroller)) return 'inner-scroll' + if (this.preserving || typeof CSS === 'undefined' || !CSS.supports('overflow-anchor', 'auto')) return 'unavailable' + return elements.scroller.scrollTop <= 0.5 ? 'prepend' : 'native' + } + + /** + * Capture one top-edge prepend anchor without acquiring continuous scroll ownership. + * @returns whether an old paging row was captured. + */ + beginHistoryPrepend(): boolean { + const row = this.pagingAnchor() + this.historyPrepend = row === null ? null : this.measurePaging(row) + return this.historyPrepend !== null + } + + /** Clear an unapplied one-shot correction when its page was not consumed. */ + cancelHistoryPrepend(): void { this.historyPrepend = null } + + /** + * Correct a committed prepend once, then release positioning ownership. + * @returns the compensated landing for reading memory, or null when no anchor remains. + */ + finishHistoryPrepend(): ViewportLanding | null { + const pending = this.historyPrepend + this.historyPrepend = null + const paging = this.resolvePaging(pending) + return paging === null ? null : this.applyPaging(paging, true) + } + + private readonly onHistoryScroll = (event: Event): void => { + if (event.target === this.elements?.scroller || event.target instanceof HTMLElement + && event.target.hasAttribute('data-step-process-body')) { + this.historyScrolling.add(event.target) + } + } + + private readonly onHistoryPointerDown = (): void => { + this.historyPointer = true + this.events?.history?.() + } + private readonly onHistoryTouch = (): void => { + this.historyTouch = true + this.events?.history?.() + } + private readonly onHistoryRelease = (event: Event): void => { + if (event.type === 'pointerup' || event.type === 'pointercancel') this.historyPointer = false + if (event.type === 'touchend' || event.type === 'touchcancel') { + this.historyTouch = typeof TouchEvent !== 'undefined' && event instanceof TouchEvent && event.touches.length > 0 + } + this.events?.history?.() + } + private readonly onScroll = (event: Event): void => { if (this.elements === null || event.target !== this.elements.scroller) return if (this.observation.landing !== null && this.elements.scroller.scrollTop === this.observation.top) return @@ -932,6 +1091,8 @@ export class ChatViewport { } private readonly onScrollEnd = (event: Event): void => { + if (event.target !== null) this.historyScrolling.delete(event.target) + this.events?.history?.() if (event.target === this.elements?.scroller) { this.events?.scrollEnd(true) this.reclaimBelow() diff --git a/packages/client/ui-chat/src/client/contract/slots.ts b/packages/client/ui-chat/src/client/contract/slots.ts index ed89452f50..676bb3fb2d 100644 --- a/packages/client/ui-chat/src/client/contract/slots.ts +++ b/packages/client/ui-chat/src/client/contract/slots.ts @@ -347,7 +347,10 @@ export interface ChatViewInjected { /** Open one HTTP(S) message link at the selected destination, using an external tab if Sidebar Browser is unavailable. */ openExternalLink: (url: string) => void openFile: (path: string, options?: OpenFileOptions) => Promise + /** Prepare one older page without publishing it. */ loadOlder: () => void + /** Consume the prepared page synchronously; false when none is ready. */ + consumeOlder: () => boolean /** Jump loader: page history back through seq; resolves when the window covers it. */ loadThrough: (seq: SessionSeq) => Promise loadImage: MessageImageLoader diff --git a/packages/client/ui-chat/src/client/locale.ts b/packages/client/ui-chat/src/client/locale.ts index 0b2bc2151d..4d22cff80e 100644 --- a/packages/client/ui-chat/src/client/locale.ts +++ b/packages/client/ui-chat/src/client/locale.ts @@ -92,6 +92,10 @@ export const zh = { 'chat.loadingHistory': '载入历史…', 'chat.loadError': '历史加载失败:{message}({code})', 'chat.loadOlder': '加载更早', + 'chat.loadingOlder': '正在加载', + 'chat.processingOlder': '正在处理', + 'chat.retryOlder': '重新加载', + 'chat.historyStart': '已到会话开头', 'chat.toBottom': '回到底部', 'chat.deepDiving': '深度求索中', 'chat.deepDivingFor': '深度求索中,用时 {duration} ···', @@ -302,6 +306,10 @@ export const en = { 'chat.loadingHistory': 'Loading history…', 'chat.loadError': 'Failed to load history: {message} ({code})', 'chat.loadOlder': 'Load earlier', + 'chat.loadingOlder': 'Loading earlier', + 'chat.processingOlder': 'Processing', + 'chat.retryOlder': 'Retry loading', + 'chat.historyStart': 'Start of conversation', 'chat.toBottom': 'Back to bottom', 'chat.deepDiving': 'Deep diving', 'chat.deepDivingFor': 'Deep diving for {duration} ···', @@ -509,6 +517,10 @@ export const ja = { 'chat.loadingHistory': '履歴を読み込み中…', 'chat.loadError': '履歴の読み込みに失敗しました: {message}({code})', 'chat.loadOlder': '以前を読み込む', + 'chat.loadingOlder': '読み込み中', + 'chat.processingOlder': '処理中', + 'chat.retryOlder': '再読み込み', + 'chat.historyStart': '会話の先頭です', 'chat.toBottom': '最下部へ戻る', 'chat.deepDiving': '深掘り中', 'chat.deepDivingFor': '{duration} の間深く分析中 ···', @@ -716,6 +728,10 @@ export const es = { 'chat.loadingHistory': 'Cargando historial…', 'chat.loadError': 'No se pudo cargar el historial: {message} ({code})', 'chat.loadOlder': 'Cargar antes', + 'chat.loadingOlder': 'Cargando anteriores', + 'chat.processingOlder': 'Procesando', + 'chat.retryOlder': 'Reintentar carga', + 'chat.historyStart': 'Inicio de la conversación', 'chat.toBottom': 'Volver al fondo', 'chat.deepDiving': 'Razonamiento profundo', 'chat.deepDivingFor': 'Razonando a fondo durante {duration} ···', @@ -923,6 +939,10 @@ export const fr = { 'chat.loadingHistory': "Chargement de l'historique…", 'chat.loadError': "Échec du chargement de l'historique : {message} ({code})", 'chat.loadOlder': 'Charger plus tôt', + 'chat.loadingOlder': 'Chargement en cours', + 'chat.processingOlder': 'Traitement en cours', + 'chat.retryOlder': 'Réessayer', + 'chat.historyStart': 'Début de la conversation', 'chat.toBottom': 'Retour en bas', 'chat.deepDiving': 'Réflexion approfondie', 'chat.deepDivingFor': 'Réflexion approfondie depuis {duration} ···', @@ -1130,6 +1150,10 @@ export const de = { 'chat.loadingHistory': 'Verlauf wird geladen…', 'chat.loadError': 'Fehler beim Laden des Verlaufs: {message} ({code})', 'chat.loadOlder': 'Früher laden', + 'chat.loadingOlder': 'Wird geladen', + 'chat.processingOlder': 'Wird verarbeitet', + 'chat.retryOlder': 'Erneut laden', + 'chat.historyStart': 'Anfang der Unterhaltung', 'chat.toBottom': 'Zurück nach unten', 'chat.deepDiving': 'Gründliches Nachdenken', 'chat.deepDivingFor': 'Gründliches Nachdenken seit {duration} ···', @@ -1337,6 +1361,10 @@ export const ru = { 'chat.loadingHistory': 'Загрузка истории…', 'chat.loadError': 'Не удалось загрузить историю: {message} ({code})', 'chat.loadOlder': 'Загрузить раньше', + 'chat.loadingOlder': 'Загрузка истории', + 'chat.processingOlder': 'Обработка', + 'chat.retryOlder': 'Повторить загрузку', + 'chat.historyStart': 'Начало разговора', 'chat.toBottom': 'Вернуться к низу', 'chat.deepDiving': 'Глубокое размышление', 'chat.deepDivingFor': 'Глубокое размышление в течение {duration} ···', @@ -1544,6 +1572,10 @@ export const pt = { 'chat.loadingHistory': 'Carregando histórico…', 'chat.loadError': 'Falha ao carregar o histórico: {message} ({code})', 'chat.loadOlder': 'Carregar mais cedo', + 'chat.loadingOlder': 'Carregando anteriores', + 'chat.processingOlder': 'Processando', + 'chat.retryOlder': 'Tentar novamente', + 'chat.historyStart': 'Início da conversa', 'chat.toBottom': 'De volta ao fundo', 'chat.deepDiving': 'Raciocínio profundo', 'chat.deepDivingFor': 'Raciocínio profundo há {duration} ···', diff --git a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx index 8ee48b8f65..352e5d5042 100644 --- a/packages/client/ui-chat/tests/apply-inject.client.spec.tsx +++ b/packages/client/ui-chat/tests/apply-inject.client.spec.tsx @@ -253,7 +253,7 @@ describe('Chat inject API', () => { const b = await bench() const { injected } = b.chatViewApi(b.rootReference) injected.loadOlder() - expect(b.session.loadOlder).toHaveBeenCalledOnce() + expect(b.session.loadOlder).toHaveBeenCalledExactlyOnceWith({ deferConsumption: true }) void injected.loadThrough(SessionSeq(42)) expect(b.session.loadThrough).toHaveBeenCalledWith(42) diff --git a/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts new file mode 100644 index 0000000000..1ce525374b --- /dev/null +++ b/packages/client/ui-chat/tests/chat-history-intent.client.spec.ts @@ -0,0 +1,117 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { SessionSeq } from '@deepseek-ai/dsh-session/types' +import { ChatNavigation, type ChatNavigationInput } from '../src/client/chat/use-chat-navigation.ts' +import { ChatReading } from '../src/client/chat/use-chat-reading.ts' +import { ChatViewport } from '../src/client/chat/use-chat-viewport.ts' +import { ScrollFollow } from '../src/client/chat/use-scroll-follow.ts' + +function fixture() { + const viewport = new ChatViewport() + vi.spyOn(viewport, 'confirmHistoryStart').mockReturnValue(true) + const mode = vi.spyOn(viewport, 'historyConsumption').mockReturnValue('native') + const reading = new ChatReading(viewport, { read: () => null, save: () => {} }, { + initialized: true, followingTail: false, activeTurn: 1, + }, () => {}, new ScrollFollow(false, 24)) + const loadOlder = vi.fn() + const consumeOlder = vi.fn(() => true) + const onIntent = vi.fn() + let input: ChatNavigationInput = { + isOpen: true, firstSeq: SessionSeq(20), hasMore: true, loadingOlder: false, + historyLoadStatus: 'idle', loadOlder, consumeOlder, loadThrough: async () => {}, + } + const navigation = new ChatNavigation(viewport, reading, input, () => {}, onIntent) + const check = () => { + navigation.requestHistoryCheck() + vi.advanceTimersByTime(20) + } + const ready = () => { + input = { ...input, historyLoadStatus: 'pendingConsumption' } + navigation.setInput(input) + } + return { viewport, navigation, reading, mode, loadOlder, consumeOlder, onIntent, check, ready } +} + +beforeEach(() => { vi.useFakeTimers() }) +afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() }) + +describe('history consumption intent', () => { + it.each(['motion', 'pointer', 'unavailable'] as const)('leaves an automatic page for a click after %s', (blocker) => { + const h = fixture() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.mode.mockReturnValue('native') + h.ready() + h.check() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it.each(['touch', 'inner-scroll'] as const)('continues automatic consumption after %s ends', (blocker) => { + const h = fixture() + h.check() + h.ready() + h.mode.mockReturnValue(blocker) + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('auto') + expect(h.consumeOlder).not.toHaveBeenCalled() + h.mode.mockReturnValue('native') + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it('retains an explicit click until the fold ends without requesting the cached page again', () => { + const h = fixture() + h.ready() + h.mode.mockReturnValue('motion') + vi.spyOn(h.viewport.motion, 'foldActive').mockReturnValue(true) + let idle: (() => void) | undefined + const stop = vi.fn() + vi.spyOn(h.viewport.motion, 'onFoldIdle').mockImplementation((callback) => { idle = callback; return stop }) + h.navigation.loadEarlier() + h.check() + expect(h.onIntent).toHaveBeenLastCalledWith('manual') + expect(h.loadOlder).not.toHaveBeenCalled() + expect(h.consumeOlder).not.toHaveBeenCalled() + h.mode.mockReturnValue('native') + idle?.() + vi.advanceTimersByTime(20) + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) + + it('joins a pending automatic request when clicked and consumes once after it returns', () => { + const h = fixture() + h.check() + h.navigation.loadEarlier() + h.check() + expect(h.loadOlder).toHaveBeenCalledOnce() + h.ready() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(h.onIntent).toHaveBeenLastCalledWith('none') + h.navigation.dispose() + }) + + it('does not consume a cached page on a fresh view until clicked', () => { + const h = fixture() + h.ready() + h.check() + expect(h.consumeOlder).not.toHaveBeenCalled() + h.navigation.loadEarlier() + h.check() + expect(h.consumeOlder).toHaveBeenCalledOnce() + h.navigation.dispose() + }) +}) diff --git a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx index f0555f7fff..885b16e72c 100644 --- a/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-scroll.client.spec.tsx @@ -36,7 +36,7 @@ function ScrollHarness({ input, onMotion }: { function mountScroll(deferCompletedTurns = true, initial: Partial = {}) { let input: ChatScrollInput = { - ready: true, + isOpen: true, order: [], firstSeq: null, lastKey: null, @@ -49,7 +49,7 @@ function mountScroll(deferCompletedTurns = true, initial: Partial false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, @@ -116,9 +116,9 @@ function mountRows(heights: readonly number[]) { } vi.stubGlobal('ResizeObserver', Observer) const input: ChatScrollInput = { - ready: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: true, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: false, - transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'standard', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } const view = render( { callbacks.motion = motion }} @@ -287,9 +287,9 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea let motion: FlowMotionRows | undefined const onMotion = (value: FlowMotionRows): void => { motion = value } let input: ChatScrollInput = { - ready: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, + isOpen: false, order: [], firstSeq: null, lastKey: null, lastIsUser: false, steeringId: null, submissionId: null, submissionSteers: false, running: false, deferCompletedTurns: true, - transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, + transcriptView: 'detailed', loadedTurns: [], hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', consumeOlder: vi.fn(() => false), loadOlder: vi.fn(), loadThrough: vi.fn(async () => {}), chatScroll: { read: () => null, save: vi.fn() }, } vi.stubGlobal('matchMedia', vi.fn(() => ({ matches: reduced }))) @@ -328,7 +328,7 @@ function mountVisibleFold(test: typeof visibleFoldCases[number], reduced: boolea offsetHeight: { get: contentHeight }, getBoundingClientRect: { value: () => ({ top: -top, bottom: contentHeight() - top, height: contentHeight() }) }, }) - input = { ...input, ready: true } + input = { ...input, isOpen: true } view.rerender() top = test.top scrollTo.mockClear() @@ -495,7 +495,7 @@ it('keeps one active fold when the local echo becomes its durable input', async describe('Chat scroll collapse timing', () => { it.each(['resize', 'scroll', 'history', 'input', 'preference'] as const)( 'waits for initial history before initializing a running view after %s', (change) => { - const h = mountScroll(true, { ready: false, running: true }) + const h = mountScroll(true, { isOpen: false, running: true }) expect(h.scroller.dataset.initialized).toBe('false') if (change === 'resize') h.resize() else if (change === 'scroll') fireEvent.scroll(h.scroller) @@ -506,7 +506,7 @@ describe('Chat scroll collapse timing', () => { expect(h.scroller.scrollTop).toBe(0) expect(h.scrollTo).not.toHaveBeenCalled() - h.update({ ready: true }) + h.update({ isOpen: true }) expect(h.scroller.dataset.initialized).toBe('true') expect(h.scroller.scrollTop).toBe(600) expect(h.scrollTo).not.toHaveBeenCalled() 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 37011ab8bb..0d66887de6 100644 --- a/packages/client/ui-chat/tests/chat-view.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-view.client.spec.tsx @@ -107,6 +107,8 @@ function sessionSnapshot(overrides: Partial = {}): TestSess openError: null, hasMore: false, loadingOlder: false, + historyLoadStatus: 'idle', + historyWasPartial: overrides.hasMore ?? false, promptError: null, blank: false, subagent: null, @@ -421,7 +423,22 @@ function makeHarness( const openFile = vi.fn<(path: string) => Promise>().mockResolvedValue(undefined) const openUserFile = vi.fn<(path: string) => void>() const renderUserContent = createUserContentFixture({ openFile: openUserFile }) - const loadOlder = vi.fn() + let preparedOlder: (() => void) | null = null + const loadOlder = vi.fn(() => { + session.set({ loadingOlder: true, historyLoadStatus: 'loading' }) + }) + const consumeOlder = vi.fn(() => { + if (preparedOlder === null) return false + const consume = preparedOlder + preparedOlder = null + consume() + session.set({ loadingOlder: false, historyLoadStatus: 'idle' }) + return true + }) + const prepareOlder = (consume: () => void) => { + preparedOlder = consume + session.set({ loadingOlder: false, historyLoadStatus: 'pendingConsumption' }) + } const loadThrough = vi.fn<(seq: number) => Promise>().mockResolvedValue(undefined) // Mutable outline holder: tests swap the value and drive a re-render via set(). let outlineValue: unknown @@ -555,6 +572,7 @@ function makeHarness( openFile, openExternalLink: vi.fn(), loadOlder, + consumeOlder, loadThrough, loadImage: vi.fn(() => Promise.reject(new Error('not used'))), chatScroll, @@ -584,7 +602,7 @@ function makeHarness( return { set, setSession: session.set, setChat: chatSource.set, ChatView, props, setConnection: (state: ConnectionState) => { connection.set(state) }, - openFile, openUserFile, loadOlder, loadThrough, openView, + openFile, openUserFile, loadOlder, consumeOlder, prepareOlder, loadThrough, openView, setOutline: (value: unknown) => { outlineValue = value }, chatScroll, forkAt, toolOwners, fenceCalls, setPerformanceUsage: (mode: 'compact' | 'detailed') => { performanceUsage.set(mode) }, @@ -643,6 +661,11 @@ function readerScroll(element: HTMLElement, top: number): void { fireEvent(element, new Event('scrollend')) } +/** Let the public history scheduler run one frame, including React's commit of its updates. */ +async function historyFrame(): Promise { + await act(async () => { await new Promise(resolve => requestAnimationFrame(() => { resolve() })) }) +} + function turnProcessControl(container: HTMLElement): HTMLButtonElement | null { return container.querySelector('[data-turn-process]') } @@ -1537,6 +1560,19 @@ describe('ChatView', () => { await act(async () => { releaseJump?.() }) }) + it('keeps the history start marker across remounts from the Session fact', () => { + const h = makeHarness({ nodes: [user(1, 'prompt'), assistant(2, 'answer')] }, { + hasMore: false, historyWasPartial: true, + }) + const first = render() + expect(first.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + first.unmount() + const second = render() + expect(second.getByRole('button', { name: '已到会话开头' }).hasAttribute('disabled')).toBe(true) + act(() => { h.setSession({ historyWasPartial: false }) }) + expect(second.queryByRole('button', { name: '已到会话开头' })).toBeNull() + }) + it('holds a jump issued while a plain pull owns the pager and resumes it when the pull settles', async () => { const later = [userInTurn(8, 'third prompt', 3), assistant(9, 'third response', 3)] const h = makeHarness({ nodes: later }, { hasMore: true, loadingOlder: true }) @@ -1642,7 +1678,7 @@ describe('ChatView', () => { expect(h.toolOwners[0]).toMatchObject({ callId: 'w1', toolName: '' }) }) - it('prepend keeps the reader\'s latest pending-request scroll position anchored', () => { + it('prepend keeps the reader\'s latest pending-request scroll position anchored', async () => { const h = makeHarness( { nodes: [user(9, 'first visible'), user(10, 'next visible')] }, { hasMore: true }, @@ -1666,17 +1702,19 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) - act(() => { h.set({ loadingOlder: true }) }) + await historyFrame() // The reader moves after the request starts; this, not the click-time // row, is the intent the arriving page must preserve. firstTop = -200 nextTop = 60 readerScroll(scroller, 90) - Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) - nextTop = 560 - act(() => { - h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')], loadingOlder: false }) - }) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1300, writable: true }) + nextTop = 560 + h.set({ nodes: [assistant(2, 'older'), user(9, 'first visible'), user(10, 'next visible')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(590) // latest 90 + the anchored row's 500px prepend shift }) @@ -1685,7 +1723,7 @@ describe('ChatView', () => { { mode: 'detailed', anchor: 'group' }, { mode: 'compact', anchor: 'node' }, { mode: 'standard', anchor: 'node' }, { mode: 'detailed', anchor: 'node' }, ] as const)( - 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', ({ mode, anchor }) => { + 'keeps the first visible item in place when paging inserts a steering boundary ($mode, $anchor)', async ({ mode, anchor }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [tool(4, 'retained'), assistant(6, 'answer', 1, 2)], turnEnds: new Map([[1, 7]]) } let source = chatSnapshotFixture(initial) @@ -1726,14 +1764,17 @@ describe('ChatView', () => { expect(pinned.hasAttribute('data-chat-paging-anchor')).toBe(true) expect(controlSeat.hasAttribute('data-chat-paging-anchor')).toBe(false) expect(group.hasAttribute('data-chat-paging-anchor')).toBe(anchor !== 'node') - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { paged = true source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier'), steering(2, 'historical direction', 1), tool(3, 'before-retained'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(pinned.getBoundingClientRect().top).toBe(expectedTop) expect(scroller.scrollTop).toBe(expectedScroll) @@ -1757,7 +1798,7 @@ describe('ChatView', () => { { mode: 'compact', hasProcess: false, hasSteering: true }, { mode: 'standard', hasProcess: false, hasSteering: true }, { mode: 'detailed', hasProcess: false, hasSteering: true }, - ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', ({ mode, hasProcess, hasSteering }) => { + ] as const)('keeps the loaded message anchored when paging exposes steering inside a closed Turn ($mode, process=$hasProcess, steer=$hasSteering)', async ({ mode, hasProcess, hasSteering }) => { const tool = (seq: number, id: string) => ({ ...toolResult(seq, id), turn: 1 }) const initial = { nodes: [ @@ -1801,13 +1842,16 @@ describe('ChatView', () => { expect(control.hasAttribute('data-chat-paging-anchor')).toBe(false) fireEvent.click(view.getByText('加载更早')) - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { source = chatSnapshotFixture({ ...initial, nodes: [ tool(1, 'earlier-work'), steering(2, 'earlier direction', 1), tool(3, 'following-work'), ...initial.nodes, ] }, source) h.set({ chat: installGroupedSnapshot(builder, state, groups, source) }) h.setGrouped(groups) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() const steer = view.container.querySelector('[data-chat-node-key="fixture:steering:2"]')! const rows = visibleRows() @@ -1854,7 +1898,7 @@ describe('ChatView', () => { } }) - it('anchors the first transcript row for paging regardless of the viewport reading line', () => { + it('anchors the first transcript row for a prepared page consumed at the top without reading hit tests', async () => { const originalHitTest = Object.getOwnPropertyDescriptor(document, 'elementsFromPoint') const nodes = Array.from({ length: 16 }, (_, index) => user(20 + index, `row ${String(index)}`)) const h = makeHarness( @@ -1873,13 +1917,13 @@ describe('ChatView', () => { vi.spyOn(row, 'getBoundingClientRect').mockImplementation(() => { rowRectCalls += 1 const shift = prepended ? (index === 8 ? 400 : 500) : 0 - const top = 20 + (index - 8) * 60 + shift + const top = 20 + index * 60 + shift - scroller.scrollTop return { top, bottom: top + 40 } as DOMRect }) }) Object.defineProperty(scroller, 'scrollHeight', { value: 800, writable: true }) Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) - readerScroll(scroller, 50) + readerScroll(scroller, 0) const hitTest = vi.fn((_x: number, _y: number): Element[] => []) Object.defineProperty(document, 'elementsFromPoint', { @@ -1890,14 +1934,19 @@ describe('ChatView', () => { rowRectCalls = 0 fireEvent.click(view.getByText('加载更早')) expect(hitTest).not.toHaveBeenCalled() - expect(rowRectCalls).toBe(1) - - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - prepended = true - act(() => { + expect(rowRectCalls).toBe(0) + await historyFrame() + act(() => { h.prepareOlder(() => { + expect(hitTest).not.toHaveBeenCalled() + expect(rowRectCalls).toBe(1) + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + prepended = true h.setChat({ nodes: [assistant(2, 'older'), ...nodes] }) - }) - expect(scroller.scrollTop).toBe(550) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() + expect(scroller.scrollTop).toBe(500) + expect(rows[0]!.getBoundingClientRect().top).toBe(20) expect(h.chatScroll.read()?.anchorKey).toBe('fixture:user:20') } finally { if (originalHitTest !== undefined) { @@ -4060,7 +4109,7 @@ describe('ChatView', () => { expect(screen.queryByRole('dialog')).toBeNull() }) - it('prepend preserves a semantic row; a trailing user node force-scrolls', () => { + it('prepend preserves a semantic row; a trailing user node force-scrolls', async () => { const h = makeHarness( { nodes: [user(5, 'later'), assistant(6, 'a')] }, { hasMore: true }, @@ -4076,13 +4125,15 @@ describe('ChatView', () => { () => ({ top: anchoredTop, bottom: anchoredTop + 40 } as DOMRect), ) readerScroll(scroller, 80) - // Arm the paging anchor, then deliver an older page (head seq decreases). fireEvent.click(view.getByText('加载更早')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) - anchoredTop = 700 - act(() => { + await historyFrame() + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1600, writable: true }) + anchoredTop = 700 h.setChat({ nodes: [user(1, 'old'), assistant(2, 'b'), user(5, 'later'), assistant(6, 'a')] }) - }) + }) }) + await historyFrame() + expect(h.consumeOlder).toHaveBeenCalledOnce() expect(scroller.scrollTop).toBe(680) // reader offset 80 + the anchored row's 600px shift // A new trailing user bubble (own words) force-scrolls to the bottom. act(() => { @@ -4093,7 +4144,45 @@ describe('ChatView', () => { expect(scroller.scrollTop).toBe(1200) }) - it('back-to-bottom cancels an in-flight paging anchor', () => { + it('restores a one-shot prepend landing after immediate remount before scroll delivery', async () => { + const host = document.createElement('div') + host.dataset.conversationScroll = '' + document.body.append(host) + let paged = false + Object.defineProperties(host, { + clientHeight: { value: 200 }, + scrollHeight: { get: () => paged ? 1200 : 200 }, + }) + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (this === host) return new DOMRect(0, 0, 500, 200) + const offset = this.dataset.chatAnchorKey === 'fixture:user:5' ? 20 + (paged ? 200 : 0) : 0 + return new DOMRect(0, offset - host.scrollTop, 500, 40) + }) + try { + const h = makeHarness({ nodes: [user(5, 'retained prompt'), assistant(6, 'answer')] }, { hasMore: true }) + const view = render(, { container: host }) + expect(host.scrollTop).toBe(0) + expect(h.chatScroll.read()).toBeNull() + fireEvent.click(view.getByRole('button', { name: '加载更早' })) + await historyFrame() + act(() => { h.prepareOlder(() => { + paged = true + h.setChat({ nodes: [user(1, 'earlier'), assistant(2, 'old answer'), user(5, 'retained prompt'), assistant(6, 'answer')] }) + }) }) + await historyFrame() + expect(host.scrollTop).toBe(200) + // A navigation can remove the view before the browser delivers the scroll caused by compensation. + view.rerender(
) + host.scrollTop = 0 + view.rerender() + expect(host.scrollTop).toBe(200) + expect(h.chatScroll.read()).toMatchObject({ anchorKey: 'fixture:user:5', anchorTop: 20, scrollTop: 200 }) + } finally { + host.remove() + } + }) + + it('back-to-bottom cancels pending history consumption without reviving it when the page arrives', async () => { const h = makeHarness({ nodes: [user(9, 'late')] }, { hasMore: true }) const view = render() const scroller = view.container.querySelector('[data-chat-flow]')!.parentElement as HTMLDivElement @@ -4101,10 +4190,16 @@ describe('ChatView', () => { Object.defineProperty(scroller, 'clientHeight', { value: 200, writable: true }) readerScroll(scroller, 50) fireEvent.click(view.getByText('加载更早')) + await historyFrame() fireEvent.click(view.getByLabelText('回到底部')) - Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) - act(() => { h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) }) - expect(scroller.scrollTop).toBe(1_100) + act(() => { h.prepareOlder(() => { + Object.defineProperty(scroller, 'scrollHeight', { value: 1_300, writable: true }) + h.setChat({ nodes: [assistant(2, 'older'), user(9, 'late')] }) + }) }) + await historyFrame() + expect(h.consumeOlder).not.toHaveBeenCalled() + expect(scroller.scrollTop).toBe(600) + expect(view.queryByText('older')).toBeNull() expect(h.chatScroll.read()).toBeNull() }) @@ -4598,13 +4693,15 @@ describe('ChatView', () => { } }) - it('paging button loads older and shows its busy label', () => { + it('paging button schedules an older request and shows its loading label', async () => { const h = makeHarness({ nodes: [user(5, 'later')] }, { hasMore: true }) const view = render() fireEvent.click(view.getByText('加载更早')) + expect(h.loadOlder).not.toHaveBeenCalled() + expect(view.getByRole('button', { name: '正在处理' }).hasAttribute('disabled')).toBe(true) + await historyFrame() expect(h.loadOlder).toHaveBeenCalledTimes(1) - act(() => { h.setSession({ loadingOlder: true }) }) - expect(view.getByText('加载中…')).toBeTruthy() + expect(view.getByRole('button', { name: '正在加载' }).hasAttribute('disabled')).toBe(true) }) it('shows open error and loading states', () => { diff --git a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts index def772efb8..6149f9a89d 100644 --- a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts @@ -48,6 +48,100 @@ function fixture() { return { column, viewport, group, row, prepend: (height: number) => { prependedHeight += height } } } +it('updates history distance only from scrollport size observations before layout writes', () => { + let resize: ResizeObserverCallback | undefined + class Observer implements ResizeObserver { + constructor(callback: ResizeObserverCallback) { resize = callback } + observe(): void {} + unobserve(): void {} + disconnect(): void {} + } + vi.stubGlobal('ResizeObserver', Observer) + onTestFinished(() => { vi.unstubAllGlobals() }) + const h = fixture() + const edge = document.createElement('div') + h.column.prepend(edge) + const height = vi.fn(() => 300) + Object.defineProperty(h.column, 'clientHeight', { configurable: true, get: height }) + h.viewport.setHistoryEdge(edge) + expect(height).not.toHaveBeenCalled() + let afterWrite = false + vi.spyOn(h.viewport, 'reclaimBelow').mockImplementation(() => { afterWrite = true }) + height.mockImplementation(() => { + if (afterWrite) throw new Error('height read after a layout writer') + return 300 + }) + const entry: ResizeObserverEntry = { target: h.column, contentRect: new DOMRect(), + borderBoxSize: [], contentBoxSize: [], devicePixelContentBoxSize: [] } + const notify = resize + const observer = new Observer(() => {}) + notify?.([entry], observer) + height.mockClear() + notify?.([], observer) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -600, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(true) + vi.spyOn(edge, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, -700, 20, 10)) + expect(h.viewport.confirmHistoryStart()).toBe(false) + expect(height).not.toHaveBeenCalled() +}) + +it('uses the first paging anchor for one-shot history prepending without reading-position lookup', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + const scrollerRect = vi.spyOn(h.column, 'getBoundingClientRect') + const capture = vi.spyOn(h.viewport, 'capturePosition') + const query = vi.spyOn(h.column, 'querySelector') + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(capture).not.toHaveBeenCalled() + expect(query).toHaveBeenCalledTimes(1) + expect(scrollerRect).toHaveBeenCalledTimes(1) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(row.getBoundingClientRect().top).toBe(0) + h.prepend(30) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) +}) + +it('uses a collapsed group paging anchor when no ordinary content row is visible', () => { + const h = fixture() + const group = h.row(h.column, 'group', 0) + group.dataset.chatGroupKey = 'group' + const body = document.createElement('div') + body.hidden = true + group.append(body) + h.row(body, 'hidden-member', 20) + expect(h.viewport.capturePosition()).toBeNull() + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120) + expect(group.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('keeps reader movement during a one-shot prepend without retaining paging ownership', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(145) + expect(row.getBoundingClientRect().top).toBe(-25) + expect(h.viewport.preserving).toBe(false) +}) + +it('does not prepare a correction when no paging anchor exists', () => { + const h = fixture() + expect(h.viewport.beginHistoryPrepend()).toBe(false) + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(0) +}) + it.each([ { count: 64, slot: false }, { count: 4096, slot: false }, { count: 64, slot: true }, { count: 4096, slot: true }, @@ -440,6 +534,42 @@ it.each([ expect(h.row.getBoundingClientRect().top).toBe(top) }) +it('applies one-shot inner compensation without subscribing or undoing reader movement', () => { + const h = nestedFixture(600, 400) + h.scroller.scrollTop = 80 + h.body.scrollTop = 40 + const screenTop = h.row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + expect(h.viewport.preserving).toBe(false) + expect(h.observed.has(h.content)).toBe(false) + h.body.scrollTop = 60 + h.scroller.scrollTop = 90 + h.prepend(200) + h.viewport.finishHistoryPrepend() + expect(h.body.scrollTop).toBe(260) + expect(h.scroller.scrollTop).toBe(90) + expect(h.row.getBoundingClientRect().top).toBe(screenTop - 30) + expect(h.observed.has(h.content)).toBe(false) + h.prepend(20) + h.resize() + expect(h.body.scrollTop).toBe(260) + expect(h.scroller.scrollTop).toBe(90) +}) + +it('resolves a remounted one-shot anchor without entering retained paging', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + expect(h.viewport.beginHistoryPrepend()).toBe(true) + row.remove() + const replacement = h.row(h.column, 'old', 0) + h.column.scrollTop = 25 + h.prepend(120) + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(145) + expect(replacement.getBoundingClientRect().top).toBe(-25) + expect(h.viewport.preserving).toBe(false) +}) + it('gives paging compensation priority over an active inner follow animation', () => { const h = nestedFixture(600, 400) const follow = new ScrollFollow(true, 1) diff --git a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts index 9a53949566..9685b65f12 100644 --- a/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts +++ b/packages/client/ui-conversation/tests/conversation-registry.client.spec.ts @@ -39,7 +39,7 @@ function sessionSnapshot(): SessionSnapshot { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: true, lastAgentError: null, @@ -62,6 +62,7 @@ function fakeSession(): SessionFace { cancel: () => Promise.reject(new Error('unused fake Session operation')), rename: () => Promise.reject(new Error('unused fake Session operation')), loadOlder: () => Promise.reject(new Error('unused fake Session operation')), + consumeOlder: () => { throw new Error('unused fake Session operation') }, loadThrough: () => Promise.reject(new Error('unused fake Session operation')), command: () => Promise.reject(new Error('unused fake Session operation')), } diff --git a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx index 8a116a9a15..713c74df88 100644 --- a/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx +++ b/packages/client/ui-conversation/tests/queue-dock.client.spec.tsx @@ -56,7 +56,7 @@ interface TestSnapshot extends SessionSnapshot { function snapshotWith(queue: UserMessage[], nextStep: UserMessage[] = []): TestSnapshot { return { sessionId: SID, running: true, removed: false, openState: 'open', openError: null, - hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent: null, + hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, subagent: null, pendingSubmissions: [], lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false, testInbox: { 'next-turn': queue, 'next-step': nextStep }, diff --git a/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx b/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx index b6885853b4..8d670df9da 100644 --- a/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx +++ b/packages/client/ui-schedule/tests/schedule-catalog-action.client.spec.tsx @@ -117,7 +117,7 @@ function sessionSnapshot(openState: SessionSnapshot['openState']): SessionSnapsh openState, openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-session/tests/ui-session.client.spec.ts b/packages/client/ui-session/tests/ui-session.client.spec.ts index c12901a0d8..6afbe4be49 100644 --- a/packages/client/ui-session/tests/ui-session.client.spec.ts +++ b/packages/client/ui-session/tests/ui-session.client.spec.ts @@ -96,7 +96,7 @@ function createSessionsBench(ctx: Context): SessionsBench { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-trajectory/tests/views.client.spec.tsx b/packages/client/ui-trajectory/tests/views.client.spec.tsx index c6dfd004d4..e0ee44c80a 100644 --- a/packages/client/ui-trajectory/tests/views.client.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.client.spec.tsx @@ -126,7 +126,7 @@ function sessionSnapshot(nodes: LegacyConversationSlice['nodes']): SessionSnapsh openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: nodes.length === 0, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx index 41e0e6902f..31b9296885 100644 --- a/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/plan-review-panel.client.spec.tsx @@ -43,7 +43,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx index b3fdffda6b..3e924b4576 100644 --- a/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx +++ b/packages/client/ui-user-questions/tests/user-questions-composer.client.spec.tsx @@ -49,7 +49,7 @@ const sessionState: SessionState = { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts index 1d444f3c2f..4884a2c208 100644 --- a/packages/extensions/cordis-client-runner/src/client/api-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/api-catalog.ts @@ -677,7 +677,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ISession', - declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(): Promise;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', + declaration: 'export interface ISession {\n readonly sessionId: SessionId;\n readonly projections: ProjectionsFace;\n beginSubmission(input: BeginSubmissionInput): SubmissionHandle;\n prompt(content: PromptContentPart[], mode: \'queue\' | \'steer\', signal?: AbortSignal, requestId?: SessionRequestId): Promise>;\n readAttachment(attachment: ImageAttachmentRef): Promise>;\n updateQueue(itemId: MessageId, action: QueueAction): Promise>;\n cancel(): Promise>;\n rename(title: string): Promise>;\n loadOlder(options?: {\n deferConsumption?: boolean;\n }): Promise;\n consumeOlder(): boolean;\n loadThrough(seq: SessionSeq): Promise;\n command(line: string): Promise>;\n}', }, { name: 'ISessions', @@ -969,7 +969,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'SessionSnapshot', - declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly loadingOlder: boolean;\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', + declaration: 'export interface SessionSnapshot {\n readonly sessionId: SessionId;\n readonly pendingSubmissions: readonly PendingSubmission[];\n readonly running: boolean;\n readonly subagent: {\n readonly address: SubagentAddress;\n } | null;\n readonly removed: boolean;\n readonly openState: OpenState;\n readonly openError: RemoteFailure | null;\n readonly hasMore: boolean;\n readonly historyWasPartial: boolean;\n readonly loadingOlder: boolean;\n readonly historyLoadStatus: \'idle\' | \'loading\' | \'pendingConsumption\' | \'error\';\n readonly promptError: PromptError | null;\n readonly blank: boolean;\n readonly lastAgentError: string | null;\n readonly promptAttempted: boolean;\n readonly awaitingFirstTurn: boolean;\n}', }, { name: 'SessionStandardProps', 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 41f4010684..a882ea0ca9 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -278,7 +278,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:495', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:498', }, { key: 'conversation.chat.commandview', @@ -332,7 +332,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.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:477', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:480', }, { key: 'conversation.chat.flow', @@ -379,7 +379,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.flow\', () => ctx.slots.register(\n { name: \'conversation.chat.flow\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:436', }, { key: 'conversation.chat.markdown.fence', @@ -445,7 +445,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'wraps-owner-content', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.markdown.fence\', () => ctx.slots.register(\n { name: \'conversation.chat.markdown.fence\', id: \'my-layer\', order: 100 },\n ({ children }) => React.createElement(\'div\', null, children),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:430', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:433', }, { key: 'conversation.chat.message.images', @@ -492,7 +492,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.message.images\', () => ctx.slots.register(\n { name: \'conversation.chat.message.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:469', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:472', }, { key: 'conversation.chat.node', @@ -564,7 +564,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:445', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:448', }, { key: 'conversation.chat.reasoning.body', @@ -608,7 +608,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.reasoning.body\', () => ctx.slots.register(\n { name: \'conversation.chat.reasoning.body\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:483', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:486', }, { key: 'conversation.chat.text-interaction', @@ -660,7 +660,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.text-interaction\', () => ctx.slots.register(\n { name: \'conversation.chat.text-interaction\', key: \'\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:428', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:431', }, { key: 'conversation.chat.turnTail', @@ -727,7 +727,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:489', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:492', }, { key: 'conversation.chat.user.before', @@ -777,7 +777,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'conversation.chat.user.before\', () => ctx.slots.register(\n { name: \'conversation.chat.user.before\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:459', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:462', }, { key: 'conversation.chat.user.images', @@ -824,7 +824,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.user.images\', () => ctx.slots.register(\n { name: \'conversation.chat.user.images\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:471', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:474', }, { key: 'conversation.composer', @@ -4116,7 +4116,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'shell.quota-notice\', () => ctx.slots.register(\n { name: \'shell.quota-notice\', select: owner => null },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-chat/src/client/contract/slots.ts:503', + source: 'packages/client/ui-chat/src/client/contract/slots.ts:506', }, { key: 'sidebar', diff --git a/packages/session/message-quotes/tests/quote-selection.client.spec.tsx b/packages/session/message-quotes/tests/quote-selection.client.spec.tsx index 656f8909e3..d848a09db7 100644 --- a/packages/session/message-quotes/tests/quote-selection.client.spec.tsx +++ b/packages/session/message-quotes/tests/quote-selection.client.spec.tsx @@ -14,7 +14,7 @@ function props(enabled = true, subagent: SessionSnapshot['subagent'] = null) { const value = { trigger: 'selection', dismiss: vi.fn(), readText: vi.fn((): string | null => 'Hello world'), clearSelection: vi.fn(), - inputActions, useSession: selector => selector({ sessionId: SessionId('quote-selection'), pendingSubmissions: [], running: false, removed: !enabled, openState: 'open', openError: null, hasMore: false, loadingOlder: false, promptError: null, blank: false, subagent, lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false }), + inputActions, useSession: selector => selector({ sessionId: SessionId('quote-selection'), pendingSubmissions: [], running: false, removed: !enabled, openState: 'open', openError: null, hasMore: false, loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, subagent, lastAgentError: null, promptAttempted: true, awaitingFirstTurn: false }), t: () => 'Quote text', } as Props return { value, inputActions } diff --git a/packages/test-support/client-runtime/src/fixtures.ts b/packages/test-support/client-runtime/src/fixtures.ts index 21f4abef40..c103792d55 100644 --- a/packages/test-support/client-runtime/src/fixtures.ts +++ b/packages/test-support/client-runtime/src/fixtures.ts @@ -74,7 +74,7 @@ export function sessionSnapshot(sessionId: SessionId): SessionSnapshot { openState: 'open', openError: null, hasMore: false, - loadingOlder: false, + loadingOlder: false, historyLoadStatus: 'idle', historyWasPartial: false, promptError: null, blank: false, lastAgentError: null, diff --git a/packages/test-support/client-runtime/src/sessions.ts b/packages/test-support/client-runtime/src/sessions.ts index a9fadfe91b..0d5d70d0e2 100644 --- a/packages/test-support/client-runtime/src/sessions.ts +++ b/packages/test-support/client-runtime/src/sessions.ts @@ -162,6 +162,14 @@ export class FixtureSession implements SessionFace { throw new Error(`test session "${this.sessionId}": loadOlder is not stubbed — supply it on the fixture's session face`) } + /** + * Fail-loud stub; supply `consumeOlder` on the fixture's session face to exercise it. + * @returns never — always throws. + */ + consumeOlder(): never { + throw new Error(`test session "${this.sessionId}": consumeOlder is not stubbed — supply it on the fixture's session face`) + } + /** * Fail-loud stub; supply `loadThrough` on the fixture's session face to exercise it. * @returns never — always throws. From 33f5c3ba3e109a3a5270982da205c9c3045a96eb Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 6 Nov 2026 15:52:22 +0800 Subject: [PATCH 071/103] fix(ui-chat): reuse screen preservation for history prepends --- ...chat-history-consumption-details.i18n.yaml | 16 +++--- ...-11-06-chat-history-consumption-details.md | 8 +-- ...-06-chat-history-consumption-details.zh.md | 8 +-- ...6-11-06-chat-history-consumption.i18n.yaml | 8 +-- .../2026-11-06-chat-history-consumption.md | 4 +- .../2026-11-06-chat-history-consumption.zh.md | 4 +- packages/client/ui-chat/README.i18n.yaml | 4 +- packages/client/ui-chat/README.md | 2 +- packages/client/ui-chat/README.zh.md | 2 +- .../src/client/chat/use-chat-viewport.ts | 20 +++----- .../tests/chat-viewport.client.spec.ts | 51 +++++++++++++++---- 11 files changed, 78 insertions(+), 49 deletions(-) diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml index 4d1f5caf20..c0294f6e21 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml @@ -21,14 +21,14 @@ en: 993c2985bf6f3c8f zh: 8f88fb46584fb272 /agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads: - en: 2439cd4cb6a81bc4 - zh: 63b8c83897a88d2c + en: 3d59702a5b7021ea + zh: 25c9762647c7c0e0 /agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered: - en: 1b9b8eb12ee5dbd7 - zh: e4ecc3cdc3375438 + en: 7b3b9b0c7b8f293b + zh: e20045fc3080418f /agent-note-chat-history-consumption-classes-and-interactions/acceptance-criteria: - en: 8a51c549570a5e0d - zh: eb7b3c27b9dcd98c + en: 1b22cf3616302960 + zh: 418ead8421a91bee /agent-note-chat-history-consumption-classes-and-interactions/risks: - en: aee9f541d058818b - zh: 74e4b6098b9f4b46 + en: 29e718a7d1c07a68 + zh: a81e5bc6c84b0712 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md index ccc137d86b..a14fa89273 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md @@ -73,7 +73,7 @@ Prefetch reuses the existing 500ms reading sample, scrollend, content commits, a At `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`. -Persistent preservation restores the captured screen position. One-shot correction retains inner and outer scrolling since capture and compensates only layout displacement; it neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. +Persistent preservation and one-shot correction use the same `applyPaging()` formula to restore the captured screen position, compensating the inner scrollport before the outer one. They do not add changes in scrollTop since capture: native anchoring may have caused those changes. Their lifetimes differ: one-shot correction neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence. @@ -85,16 +85,18 @@ Distance confirmation still needs current geometry, and one-shot correction afte **Store separate coordinates and continuously track the first row for one-shot correction.** That duplicates existing paging anchors and can expand scroll ownership; share the position record and calculations while keeping lifetimes separate. +**Add captured-to-current scroll deltas through `preserveMovement`.** The deltas cannot distinguish reader input from native anchoring for the same prepend, so adding them can compensate twice. + ## Acceptance criteria - Default single-stage calls, deferred consumption, and Turn jumps coexist; an old request cannot consume or overwrite a new one. - Ordinary events do not revive automatic fallback; touch/inner-scroll continuation, manual completion, and unmount cleanup have focused verification. -- One-shot correction does not register persistent observation or undo intervening reader movement; existing persistent and inner preservation do not regress. +- One-shot correction uses the existing screen-restoration formula without persistent observation or duplicate native compensation; persistent and inner preservation do not regress. - Distance checks use cached viewport height; raw scroll listeners and consumption admission perform no layout reads. ## Risks -**Known issue: `preserveMovement` cannot distinguish native anchoring from reader input.** The shared correction adds changes in the outer and inner scroll positions since capture. A deterministic geometry model confirms duplicate compensation when the browser has already anchored the same prepend: an outer `scrollTop` of `0.5`, or outer `0` with inner `40`, enters the one-shot path and treats the native adjustment as movement to preserve. The resulting additional displacement is an algorithmic limitation, not evidence that every browser exhibits it. Code remains unchanged for this report-only finding; independent actual-browser verification is pending. +Screen restoration uses the measured residual displacement after native anchoring rather than adding scroll-position deltas. It does not preserve arbitrary input movement between capture and application or guarantee an uninterrupted momentum trajectory. Near-zero outer positions, native inner anchoring, and input arriving around the prepend require current-build browser verification. Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual intent can still wait if usable positioning never becomes available; actual views need cancellation, reconnect, and anchorless-structure verification. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md index 104b65e5a6..8cebfc2fa8 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md @@ -73,7 +73,7 @@ Session.consumeOlder 顶部 `scrollTop ≤ 0.5` 使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。 -持续保位恢复采集时的屏幕位置。一次补偿保留采集后发生的内外层滚动,只抵消布局位移;它不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 +持续保位和一次补偿用相同的 `applyPaging()` 公式恢复采集时的屏幕位置,先补内层、再补外层。计算不叠加采集后 scrollTop 的变化,因为这些变化可能已经来自原生锚定。两者只区分生命周期:一次补偿不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。 @@ -85,16 +85,18 @@ Session.consumeOlder **为一次补偿另存坐标并持续追踪首行。** 与既有分页锚点重复,并可能扩大滚动控制;共享位置记录和计算,只区分生命周期。 +**通过 `preserveMovement` 叠加采集后滚动增量。** 该增量无法区分读者输入与同一次前插的原生锚定,叠加后可能重复补偿。 + ## Acceptance criteria - 默认单阶段调用、延迟消费及 Turn 跳转共存,旧请求不能消费或覆盖新请求。 - auto 回退不会被普通事件恢复;触摸与内层滚动续接、manual 完成承诺和卸载清理都有定向验证。 -- 一次补偿不注册持续观察、不撤销期间的读者滚动;既有持续保位和内层补偿不退化。 +- 一次补偿使用既有屏幕位置恢复公式,不注册持续观察、不重复原生补偿;持续保位和内层补偿不退化。 - 距离读取使用缓存视口高度;原始滚动监听与消费准入不读取布局。 ## Risks -**已知问题:`preserveMovement` 无法区分原生锚定与读者输入。** 共享补偿计算会加上采集后内外层滚动位置的变化。确定性的几何模型已确认:浏览器已为同一次前插完成锚定时,外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40`,会进入一次补偿路径,把原生调整当成需要保留的移动,从而重复补偿。产生的额外位移是算法限制,不代表所有浏览器都会复现。本问题按仅报告处理,代码不变;独立真实浏览器验证仍待完成。 +屏幕位置恢复使用原生锚定后测得的剩余位移,而不是叠加滚动位置增量。它不保留采集到应用之间任意输入造成的移动,也不保证惯性轨迹连续。外层近零位置、内层原生锚定以及前插附近到达的输入,都需要当前构建的浏览器验证。 显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动操作若永远得不到可用定位条件仍可能等待;实际页面应验证取消、重连和无锚点结构。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml index 85c5633b69..06547f7c98 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml @@ -15,8 +15,8 @@ en: 2cbfd8cc05037895 zh: 024968506e2ac994 /agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation: - en: 1afb940b9b2a2fcc - zh: 8201614a80598e5b + en: 28d0c3b79f07ef07 + zh: b62ac1c02f23e4fe /agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions: en: dd4eeadd2fccab4b zh: e05d53e63cc44ddf @@ -27,5 +27,5 @@ en: b3005052df98ab10 zh: c4bdf2bed8d23550 /agent-note-chat-history-prefetch-and-safe-consumption/risks: - en: 2016c51019518572 - zh: e31e4e4ac09a2c5d + en: 4f1eac5c4dbd0b5e + zh: 9475ec9fa3bd9246 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md index bfe932f77b..778c11c43e 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md @@ -35,7 +35,7 @@ After fallback, scrolling, animation completion, and content notifications canno ### Position and status presentation -The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. A prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; persistent preservation elsewhere retains its existing lifetime. Reader movement during the correction interval is preserved rather than restoring the position from request time. +The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. A prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; persistent preservation elsewhere retains its existing lifetime. Both modes restore the screen position captured immediately before consumption with the same formula; they differ only in whether preservation remains active afterward. The one-shot path does not reconstruct intervening reader movement or restart momentum. The history control keeps the same height across states. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row. @@ -67,7 +67,7 @@ Do not add `flushSync` or change Conversation publication cadence, fold-batch ta ## Risks -**Known issue: duplicate anchoring compensation.** A deterministic geometry-model reproduction shows that one-shot correction can count native anchoring for the same page as reader movement and compensate twice: this occurs with an outer `scrollTop` of `0.5`, or with outer `0` and inner `40` when native anchoring has already moved the inner position. The algorithm is therefore not universally safe. This issue is recorded without a code fix; independent verification in actual browsers is pending. The mechanism is detailed in the [technical risks](2026-11-06-chat-history-consumption-details.md#risks). +One-shot correction restores a captured screen position rather than estimating reader velocity. Input or browser movement between capture and application can therefore affect the resulting motion; validation must cover the actual browser and input sequence. The shared formula does not add scroll-position deltas that could already include native anchoring. See the [technical risks](2026-11-06-chat-history-consumption-details.md#risks). CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. A stationary manual operation that can never obtain an anchor retains its completion intent and needs coverage for that structure. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md index 31787a81b7..d9f7c8e57a 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md @@ -35,7 +35,7 @@ Status: proposed ### 位置与状态展示 -会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;非顶部持续保位保持原生命周期。补偿期间发生的用户滚动保留,不把读者拉回请求发出时的位置。 +会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;非顶部持续保位保持原生命周期。两种模式用相同公式恢复消费前刚采集的屏幕位置,只区别于应用后是否继续保位。一次补偿不重建采集期间的读者移动,也不重新启动惯性。 历史控件各状态保持同高。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。 @@ -67,7 +67,7 @@ Status: proposed ## Risks -**已知问题:锚定重复补偿。** 确定性的几何模型复现表明,一次补偿可能把同一页已经发生的原生锚定当作读者移动,再补偿一次:外层 `scrollTop` 为 `0.5`,或外层为 `0`、内层为 `40` 且原生锚定已移动内层位置时会出现。该算法因此不能视为普遍安全。本问题仅记录,不修改代码;独立的真实浏览器验证仍待完成。机制见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。 +一次补偿恢复采集的屏幕位置,不估算读者速度。采集到应用之间的输入或浏览器移动可能影响最终运动,因此需要验证实际浏览器和输入序列。共享公式不叠加可能已包含原生锚定的滚动位置增量。见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。 原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。静止手动消费若始终无法获得锚点,完成意图仍会等待,需要覆盖该特殊结构。 diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index b17f85460e..dd8cf646da 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,8 +36,8 @@ en: e2b02942a55fb669 zh: a38bbee0cc69ae4e /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: a8e5c51345ef61b9 - zh: 0e65169b79504da8 + en: b26ab997d694ef90 + zh: 1f8a16ba02bab301 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index 8df3db6b32..e00a884771 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -186,7 +186,7 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it. A deferred history request captures its anchor at consumption rather than at request time. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. -History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and inner scrolling retain automatic intent until release; active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation. Stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. At scrollTop ≤ 0.5, the first paging anchor supplies one content-displacement correction that retains intervening reader movement and then releases immediately. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. +History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and inner scrolling retain automatic intent until release; active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation. Stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. At scrollTop ≤ 0.5, the first paging anchor uses the same captured-screen-position restoration as persistent preservation, once, then releases immediately; it does not add scroll-position deltas that native anchoring may already have applied. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index c2144fd861..29e8a373fa 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -186,7 +186,7 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点。延迟消费的历史请求在消费时采集锚点,不在发请求时采集。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 -历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和内层滚动保留自动意图至释放;动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。明确点击保留意图,直到消费、到头、失败或被新导航取代。静止消费使用保位,普通外层滚动使用浏览器锚定;scrollTop ≤ 0.5 时用首条分页锚点补偿一次内容位移,保留期间的读者滚动,随后立即释放。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 +历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和内层滚动保留自动意图至释放;动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。明确点击保留意图,直到消费、到头、失败或被新导航取代。静止消费使用保位,普通外层滚动使用浏览器锚定;scrollTop ≤ 0.5 时,首条分页锚点与持续保位共用采集屏幕位置的恢复公式,只应用一次便立即释放;不再叠加可能已由原生锚定产生的滚动位置增量。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 diff --git a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts index 98c6ac2186..e81ca93a6f 100644 --- a/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts +++ b/packages/client/ui-chat/src/client/chat/use-chat-viewport.ts @@ -67,7 +67,7 @@ interface ClosingLayout { interface PagingPosition { readonly row: HTMLElement readonly position: ChatScrollPosition - readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number; readonly scrollTop: number } | null + readonly group: { readonly body: HTMLElement; readonly content: HTMLElement; readonly top: number } | null } const READING_INTENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown', 'beforematch'] as const @@ -830,8 +830,7 @@ export class ChatViewport { const body = row.closest('[data-step-process-body]') const content = body?.querySelector('[data-step-process-content]') const group = body === null || content == null ? null - : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top, - scrollTop: previousGroup?.body === body ? previousGroup.scrollTop : body.scrollTop } + : { body, content, top: previousGroup?.top ?? top - body.getBoundingClientRect().top } return { row, group, position: position ?? { @@ -880,7 +879,7 @@ export class ChatViewport { return null } if (paging !== this.paging) this.retainPaging(paging) - return this.applyPaging(paging, false) + return this.applyPaging(paging) } private resolvePaging(paging: PagingPosition | null): PagingPosition | null { @@ -896,17 +895,15 @@ export class ChatViewport { return paging.row.closest('[hidden]') !== null || paging.row.matches(':empty') ? null : paging } - /** Content correction includes reader movement since capture; screen preservation restores the captured position. */ - private applyPaging(paging: PagingPosition, preserveMovement: boolean): ViewportLanding | null { + /** Restore the captured screen position; native anchoring already applied to this change needs no further correction. */ + private applyPaging(paging: PagingPosition): ViewportLanding | null { const elements = this.elements if (elements === null) return null const { row, group, position } = paging - let innerMovement = 0 if (group !== null && group.body.contains(row)) { const top = row.getBoundingClientRect().top - group.body.getBoundingClientRect().top const metrics = scrollMetrics(group.body) - if (preserveMovement) innerMovement = metrics.top - group.scrollTop - const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top + innerMovement)) + const target = Math.max(0, Math.min(metrics.floor, metrics.top + top - group.top)) if (metrics.top !== target) { const follow = ScrollFollow.forElement(group.body) if (follow === undefined) group.body.scrollTop = target @@ -919,8 +916,7 @@ export class ChatViewport { const metrics = this.metrics() if (metrics === null) return null const top = row.getBoundingClientRect().top - elements.scroller.getBoundingClientRect().top - const movement = preserveMovement ? metrics.top - position.scrollTop + innerMovement : 0 - const target = metrics.top + top - position.anchorTop + movement + const target = metrics.top + top - position.anchorTop return this.write(target, metrics, null, { key: position.anchorKey, top }) } @@ -1052,7 +1048,7 @@ export class ChatViewport { const pending = this.historyPrepend this.historyPrepend = null const paging = this.resolvePaging(pending) - return paging === null ? null : this.applyPaging(paging, true) + return paging === null ? null : this.applyPaging(paging) } private readonly onHistoryScroll = (event: Event): void => { diff --git a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts index 6149f9a89d..e3ed867df9 100644 --- a/packages/client/ui-chat/tests/chat-viewport.client.spec.ts +++ b/packages/client/ui-chat/tests/chat-viewport.client.spec.ts @@ -121,7 +121,7 @@ it('uses a collapsed group paging anchor when no ordinary content row is visible expect(h.viewport.preserving).toBe(false) }) -it('keeps reader movement during a one-shot prepend without retaining paging ownership', () => { +it('restores the captured screen position once without retaining paging ownership', () => { const h = fixture() const row = h.row(h.column, 'old', 0) expect(h.viewport.beginHistoryPrepend()).toBe(true) @@ -129,8 +129,8 @@ it('keeps reader movement during a one-shot prepend without retaining paging own h.column.scrollTop = 25 h.prepend(120) h.viewport.finishHistoryPrepend() - expect(h.column.scrollTop).toBe(145) - expect(row.getBoundingClientRect().top).toBe(-25) + expect(h.column.scrollTop).toBe(120) + expect(row.getBoundingClientRect().top).toBe(0) expect(h.viewport.preserving).toBe(false) }) @@ -534,7 +534,7 @@ it.each([ expect(h.row.getBoundingClientRect().top).toBe(top) }) -it('applies one-shot inner compensation without subscribing or undoing reader movement', () => { +it('restores the captured inner and outer screen position once without subscribing', () => { const h = nestedFixture(600, 400) h.scroller.scrollTop = 80 h.body.scrollTop = 40 @@ -546,14 +546,14 @@ it('applies one-shot inner compensation without subscribing or undoing reader mo h.scroller.scrollTop = 90 h.prepend(200) h.viewport.finishHistoryPrepend() - expect(h.body.scrollTop).toBe(260) - expect(h.scroller.scrollTop).toBe(90) - expect(h.row.getBoundingClientRect().top).toBe(screenTop - 30) + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(80) + expect(h.row.getBoundingClientRect().top).toBe(screenTop) expect(h.observed.has(h.content)).toBe(false) h.prepend(20) h.resize() - expect(h.body.scrollTop).toBe(260) - expect(h.scroller.scrollTop).toBe(90) + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(80) }) it('resolves a remounted one-shot anchor without entering retained paging', () => { @@ -565,8 +565,37 @@ it('resolves a remounted one-shot anchor without entering retained paging', () = h.column.scrollTop = 25 h.prepend(120) h.viewport.finishHistoryPrepend() - expect(h.column.scrollTop).toBe(145) - expect(replacement.getBoundingClientRect().top).toBe(-25) + expect(h.column.scrollTop).toBe(120) + expect(replacement.getBoundingClientRect().top).toBe(0) + expect(h.viewport.preserving).toBe(false) +}) + +it('does not repeat native outer anchoring during a near-zero one-shot prepend', () => { + const h = fixture() + const row = h.row(h.column, 'old', 0) + h.column.scrollTop = 0.5 + const top = row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(120) + // Model the browser's adjustment before the layout effect reads the new geometry. + h.column.scrollTop = 120.5 + h.viewport.finishHistoryPrepend() + expect(h.column.scrollTop).toBe(120.5) + expect(row.getBoundingClientRect().top).toBe(top) +}) + +it('does not repeat native inner anchoring when the outer scroller is at zero', () => { + const h = nestedFixture(600, 400) + h.body.scrollTop = 40 + const top = h.row.getBoundingClientRect().top + expect(h.viewport.beginHistoryPrepend()).toBe(true) + h.prepend(200) + // Same ordering as the Chromium regression: native inner adjustment precedes our correction. + h.body.scrollTop = 240 + h.viewport.finishHistoryPrepend() + expect(h.body.scrollTop).toBe(240) + expect(h.scroller.scrollTop).toBe(0) + expect(h.row.getBoundingClientRect().top).toBe(top) expect(h.viewport.preserving).toBe(false) }) From e48c9cc5291f376cc95b5bf26ec05463fa04dd48 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Fri, 6 Nov 2026 23:26:11 +0800 Subject: [PATCH 072/103] fix(ui-chat): keep manual history available and settle prepend anchors --- ...chat-history-consumption-details.i18n.yaml | 16 ++-- ...-11-06-chat-history-consumption-details.md | 21 ++--- ...-06-chat-history-consumption-details.zh.md | 21 ++--- ...6-11-06-chat-history-consumption.i18n.yaml | 16 ++-- .../2026-11-06-chat-history-consumption.md | 20 ++--- .../2026-11-06-chat-history-consumption.zh.md | 20 ++--- apps/web/tests/chat-scroll-contract.e2e.ts | 88 +++++++++++++------ packages/client/ui-chat/README.i18n.yaml | 8 +- packages/client/ui-chat/README.md | 4 +- packages/client/ui-chat/README.zh.md | 4 +- .../ui-chat/src/client/chat/ChatView.tsx | 2 +- .../src/client/chat/use-chat-navigation.ts | 44 +++++----- .../src/client/chat/use-chat-scroll.ts | 6 +- .../src/client/chat/use-chat-viewport.ts | 24 ++--- .../tests/chat-history-intent.client.spec.ts | 51 +++++++---- .../ui-chat/tests/chat-view.client.spec.tsx | 39 +++++++- 16 files changed, 236 insertions(+), 148 deletions(-) diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml index c0294f6e21..e921fbaeaf 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.i18n.yaml @@ -12,17 +12,17 @@ en: 5e5553981c48d0e2 zh: 1195ac8d64180451 /agent-note-chat-history-consumption-classes-and-interactions/proposal/owners-and-interfaces: - en: 58f6f76fd263cafb - zh: 13ac0a6259d30cda + en: efbe7ccc25cf1f42 + zh: 3bb8f803677824bd /agent-note-chat-history-consumption-classes-and-interactions/proposal/data-lifetimes: en: ffdbe0e796463624 zh: f10bd2ced5748017 /agent-note-chat-history-consumption-classes-and-interactions/proposal/consumption-intent-and-wakeups: - en: 993c2985bf6f3c8f - zh: 8f88fb46584fb272 + en: db8763250020e58c + zh: 4d9a17f1b209d4f2 /agent-note-chat-history-consumption-classes-and-interactions/proposal/shared-anchors-and-layout-reads: - en: 3d59702a5b7021ea - zh: 25c9762647c7c0e0 + en: 21df3db6bc83e702 + zh: 43b49ceb7407a422 /agent-note-chat-history-consumption-classes-and-interactions/alternatives-considered: en: 7b3b9b0c7b8f293b zh: e20045fc3080418f @@ -30,5 +30,5 @@ en: 1b22cf3616302960 zh: 418ead8421a91bee /agent-note-chat-history-consumption-classes-and-interactions/risks: - en: 29e718a7d1c07a68 - zh: a81e5bc6c84b0712 + en: 9a61970e311751ac + zh: b24d0eac7b12af62 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md index a14fa89273..b01a462712 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.md @@ -18,7 +18,7 @@ Session owns a history page's network lifetime, while Chat owns whether that pag |---|---| | [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` prepares and optionally consumes a page; `consumeOlder()` synchronously publishes a valid staged page; `historyLoadStatus` is idle/loading/pendingConsumption/error, and `loadingOlder` derives from loading, including Turn jumps | | Session request record | Holds generation, starting cursor, page entries, hasMore, Promise, and consumption/invalidation flags; staging does not advance the visible window cursor | -| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; waits or falls back by blocker; only manual consumption registers a fold-completion callback | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | Owns none/auto/manual consumption intent and request exclusion; automatic consumption waits or falls back by blocker, while manual consumption captures an anchor and consumes without blocker-wait subscriptions | | [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | Reads internal input/motion state and scrollTop, returns a blocker or native/preserve/prepend, and performs distance measurement and existing anchor algorithms | | [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | Connects existing reading, scroll, content, and size notifications to consumption checks and settles a pending one-shot correction during commit handling | | [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | Requests and consumes through injected callbacks and reads state through useSession; renders a fixed-height history control without retaining Session history data or accumulating historyWasPartial | @@ -26,13 +26,14 @@ Session owns a history page's network lifetime, while Chat owns whether that pag ```text ChatNavigation.checkHistory ├─ pendingConsumption + intent=none → retain page until clicked - ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption - │ ├─ touch/inner-scroll → retain consumption intent - │ ├─ motion/pointer/unavailable → auto falls back, manual waits + ├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder + ├─ pendingConsumption + intent=auto → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain automatic intent before checking motion + │ ├─ motion/pointer/unavailable → return to button │ ├─ native → consumeOlder │ ├─ prepend → capture paging position → consumeOlder → correct once after commit │ └─ preserve → beginPreserving → consumeOlder - ├─ loading → no duplicate request + ├─ loading → no duplicate request; a click records manual intent ├─ error → wait for explicit retry └─ idle + hasMore + (manual intent or near top without following) → request a page @@ -63,17 +64,17 @@ An ordinary request captures the transport page first. It can be consumed only a ### Consumption intent and wakeups -An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Motion, pointer, or unavailable positioning returns auto to none; touch and inner-scroll retain auto. Manual intent waits through these blockers rather than treating deferral as success. +An automatic request records auto intent; a click records manual intent. Successful consumption, failure, exhaustion, or navigation cancellation clears the intent. A cached page with none intent is neither measured nor consumed by ordinary events; its button records manual intent without requesting it again. Touch and actual inner-scroll retain auto before motion is evaluated; after release the current state is checked again. Motion, pointer, or unavailable positioning otherwise returns auto to none. Manual intent bypasses these automatic blockers once a page is available: `beginManualPaging()` uses `beginPaging()` at `scrollTop ≤ 0.5`; elsewhere it calls `beginPreserving()` with `beginPaging()` as fallback. Consumption proceeds even if no anchor is produced. Loading and processing clicks join the current request rather than duplicating it. Prefetch reuses the existing 500ms reading sample, scrollend, content commits, and size notifications, coalescing them into one rAF check. It uses no IntersectionObserver or additional sample timer and measures nothing in the raw scroll event. Only a ResizeObserver entry for the scroller itself refreshes cached clientHeight during the callback's read phase; column growth does not reread viewport height. Once internal state permits an automatic request, it reads the history control's distance from the viewport and compares it with two cached viewport heights. -`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained intent; fold-completion callbacks are registered only for manual intent. Without consumption intent, these notifications do not revive an abandoned automatic page. +`historyConsumption()` does not query DOM nodes or measure sizes. `FlowMotion.active()` exposes existing running, batchScheduled, batch, and settling state as a read-only query; passive listeners maintain input state. Size observation removes detached scrolling targets. Finger release, inner scroll completion, transition completion/cancellation, and existing notifications can wake retained automatic intent. Manual consumption has no fold-completion waiting subscription. Without consumption intent, these notifications do not revive an abandoned automatic page. ### Shared anchors and layout reads -At `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`. +For automatic consumption at `scrollTop ≤ 0.5`, selection uses `beginPaging`'s first paging-anchor rule without a reading-position hit test. `measurePaging()` only captures a `PagingPosition`; `retainPaging()` separately owns persistent preservation and inner-size observation. Stationary preservation and one-shot correction share remount resolution in `resolvePaging()` and inner/outer calculations in `applyPaging()`. -Persistent preservation and one-shot correction use the same `applyPaging()` formula to restore the captured screen position, compensating the inner scrollport before the outer one. They do not add changes in scrollTop since capture: native anchoring may have caused those changes. Their lifetimes differ: one-shot correction neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. +Persistent preservation and one-shot correction use the same `applyPaging()` formula to restore the captured screen position, compensating the inner scrollport before the outer one. They do not add changes in scrollTop since capture: native anchoring may have caused those changes. Their lifetimes differ: one-shot correction neither enters paging state nor subscribes to inner-size changes, and releases after one application. `finishHistoryPrepend()` returns the actual landing, and commit handling immediately saves it through `reading.preservePosition()` rather than waiting for a later scroll event. A committed transition from `pendingConsumption` to `idle` settles the one-shot record even when the visible Node order is unchanged; a closed view or `error` discards the record without applying it. Geometry invalidation remains conditional on the existing layout-change signal, and no new page token or React publication mechanism is introduced. The actual conversation scrollport uses `overscroll-behavior-y: none`, without creating smooth scrolling or a new momentum animation. Distance confirmation still needs current geometry, and one-shot correction after prepend still needs the new position. These reads serve correctness, but placement inside rAF, ResizeObserver, or commit handling alone does not prove they add no layout. Read frequency, read/write ordering, and actual Layout/Paint costs require separate verification; position stability is not performance evidence. @@ -98,6 +99,6 @@ Distance confirmation still needs current geometry, and one-shot correction afte Screen restoration uses the measured residual displacement after native anchoring rather than adding scroll-position deltas. It does not preserve arbitrary input movement between capture and application or guarantee an uninterrupted momentum trajectory. Near-zero outer positions, native inner anchoring, and input arriving around the prepend require current-build browser verification. -Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual intent can still wait if usable positioning never becomes available; actual views need cancellation, reconnect, and anchorless-structure verification. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build. +Explicit navigation and multiple views share a Session, so Chat's automatic waiting policy must not move into the global event source. Manual consumption establishes persistent preservation at consumption time; an already active touch can then enter the paging scroll branch instead of reader sampling, constraining movement until a new input releases the anchor. This [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work) remains unresolved. Manual consumption proceeds without preservation if no anchor can be captured, so that structure has no position-stability guarantee. Cancellation, reconnect, and removal of the selected anchor remain distinct lifecycle cases; a missing anchor cannot provide position preservation. One-shot geometry measurement, native inner anchoring, and asynchronous content growth need browser evidence from the current build. Reports must identify source/artifact versions, real or synthetic inputs, missing conditions, and cleanup results. V8 function or range hits are not TypeScript line/branch percentages; earlier iteration recordings, Chrome/Safari manual feedback, or a successful build do not establish a complete matrix pass for this proposal. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md index 8cebfc2fa8..ce9490648d 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption-details.zh.md @@ -18,7 +18,7 @@ Status: proposed |---|---| | [Session](../../../../packages/api/session-controller/src/client/sessions/session.ts) | `loadOlder({ deferConsumption?: boolean })` 准备并按选项消费一页;`consumeOlder()` 同步发布有效暂存页;`historyLoadStatus` 表达 idle/loading/pendingConsumption/error,`loadingOlder` 从 loading 派生并包含 Turn 跳转 | | Session 请求记录 | 保存 generation、请求前游标、页内容、hasMore、Promise 与消费/失效标记;缓存页不提前改变可见窗口游标 | -| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;按阻塞原因等待或退回按钮;仅手动消费注册折叠结束通知 | +| [ChatNavigation](../../../../packages/client/ui-chat/src/client/chat/use-chat-navigation.ts) | 保存 none/auto/manual 消费意图和请求互斥;自动按阻塞原因等待或退回按钮,手动采集锚点后消费,不注册阻塞结束等待 | | [ChatViewport](../../../../packages/client/ui-chat/src/client/chat/use-chat-viewport.ts) | 读取内部输入/动画状态与 scrollTop,报告阻塞原因或 native/preserve/prepend;执行距离测量和已有锚点算法 | | [useChatScroll](../../../../packages/client/ui-chat/src/client/chat/use-chat-scroll.ts) | 把既有阅读、滚动、内容及尺寸通知接到消费检查;在提交阶段结算待执行的一次补偿 | | [ChatView](../../../../packages/client/ui-chat/src/client/chat/ChatView.tsx) | 通过注入回调请求/消费,通过 useSession 读取状态;固定高度显示历史控件,不保存 Session 历史数据或累计 historyWasPartial | @@ -26,13 +26,14 @@ Status: proposed ```text ChatNavigation.checkHistory ├─ pendingConsumption + intent=none → retain page until clicked - ├─ pendingConsumption + intent=auto/manual → viewport.historyConsumption - │ ├─ touch/inner-scroll → retain consumption intent - │ ├─ motion/pointer/unavailable → auto falls back, manual waits + ├─ pendingConsumption + intent=manual → beginManualPaging → consumeOlder + ├─ pendingConsumption + intent=auto → viewport.historyConsumption + │ ├─ touch/inner-scroll → retain automatic intent before checking motion + │ ├─ motion/pointer/unavailable → return to button │ ├─ native → consumeOlder │ ├─ prepend → capture paging position → consumeOlder → correct once after commit │ └─ preserve → beginPreserving → consumeOlder - ├─ loading → no duplicate request + ├─ loading → no duplicate request; a click records manual intent ├─ error → wait for explicit retry └─ idle + hasMore + (manual intent or near top without following) → request a page @@ -63,17 +64,17 @@ Session.consumeOlder ### 消费意图与唤醒 -自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。motion、pointer 或 unavailable 使 auto 退回 none;touch 与 inner-scroll 保留 auto。manual 在这些阻塞下继续等待,不把暂缓当成成功。 +自动请求开始时登记 auto,点击登记 manual。消费成功、失败、耗尽或取消导航时清除意图。缓存存在但意图为 none 时,普通事件不测量或消费该缓存;按钮重新登记 manual,不重复取页。touch 与实际 inner-scroll 优先于 motion 判断保留 auto,释放后重新检查当前状态;其余 motion、pointer 或 unavailable 使 auto 退回 none。manual 在页面可用时绕过这些自动阻塞:`beginManualPaging()` 在 `scrollTop ≤ 0.5` 时调用 `beginPaging()`;其他位置调用 `beginPreserving()`,并以 `beginPaging()` 兜底。没有产生锚点时仍继续消费。加载和处理状态的点击加入当前请求,不重复请求。 历史预取复用已有 500ms 阅读采样、scrollend、内容提交和尺寸通知,并合并为一次 rAF 检查。不使用 IntersectionObserver,不新增采样计时器,不在原始 scroll 事件中测量。仅 scroller 自身的 ResizeObserver 条目在回调读阶段更新 clientHeight 缓存,column 增长不重新读取视口高度。内部状态允许自动请求时,读取历史控件相对视口的位置,与缓存的两屏高度比较。 -`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的意图;折叠结束回调只为 manual 注册。没有消费意图时这些通知不恢复已经放弃的自动页。 +`historyConsumption()` 不查询 DOM 或测量尺寸。`FlowMotion.active()` 从已有 running、batchScheduled、batch、settling 状态提供只读查询;输入状态来自被动事件监听。滚动目标失效的清理在尺寸观察处进行。手指释放、内层滚动结束、过渡结束/取消和既有通知可以唤醒保留的自动意图;手动消费不注册折叠结束等待。没有消费意图时这些通知不恢复已经放弃的自动页。 ### 锚点复用与布局读取 -顶部 `scrollTop ≤ 0.5` 使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。 +自动消费在顶部 `scrollTop ≤ 0.5` 时使用 `beginPaging` 的首条分页锚点规则,不先执行阅读位置命中检测。`measurePaging()` 只采集 `PagingPosition`;`retainPaging()` 单独拥有持续保位和内层尺寸观察。普通静止保位与一次补偿共用 `resolvePaging()` 的重挂载查找及 `applyPaging()` 的内外层计算。 -持续保位和一次补偿用相同的 `applyPaging()` 公式恢复采集时的屏幕位置,先补内层、再补外层。计算不叠加采集后 scrollTop 的变化,因为这些变化可能已经来自原生锚定。两者只区分生命周期:一次补偿不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 +持续保位和一次补偿用相同的 `applyPaging()` 公式恢复采集时的屏幕位置,先补内层、再补外层。计算不叠加采集后 scrollTop 的变化,因为这些变化可能已经来自原生锚定。两者只区分生命周期:一次补偿不进入 paging 状态、不注册内层尺寸观察,应用一次后释放。`finishHistoryPrepend()` 返回实际落点,提交处理立即通过 `reading.preservePosition()` 保存阅读位置,不依赖后续 scroll 事件。已提交的 `pendingConsumption` 到 `idle` 状态转换,即使可见 Node 顺序未变化,也会结算一次补偿记录;视图关闭或进入 `error` 时丢弃记录,不应用补偿。几何失效仍只由已有布局变化信号触发,不增加页 token 或 React 发布机制。会话实际滚动容器设置 `overscroll-behavior-y: none`,不创建平滑滚动或新的惯性动画。 距离检查仍需要当前几何;前插后的一次补偿仍需要读取新位置。这些读数有正确性用途,但不能仅凭位于 rAF、ResizeObserver 或提交回调中,就认定不会增加布局。读取频率、读写顺序及实际 Layout/Paint 成本分别验收;位置不漂移不能替代性能证明。 @@ -98,6 +99,6 @@ Session.consumeOlder 屏幕位置恢复使用原生锚定后测得的剩余位移,而不是叠加滚动位置增量。它不保留采集到应用之间任意输入造成的移动,也不保证惯性轨迹连续。外层近零位置、内层原生锚定以及前插附近到达的输入,都需要当前构建的浏览器验证。 -显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动操作若永远得不到可用定位条件仍可能等待;实际页面应验证取消、重连和无锚点结构。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。 +显式导航与多个视图共享 Session,不能把 Chat 的自动等待条件放进全局事件源。手动消费在消费时建立持续保位;已经进行的触摸随后可能进入 paging 滚动分支而非读者采样,移动受限直到新输入释放锚点。这项[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)仍未解决。手动消费在无法采集锚点时仍继续,因此该结构不保证位置稳定。取消、重连和所选锚点被移除属于不同生命周期情况;锚点缺失时无法提供位置保留。一次补偿的布局测量、内层浏览器锚定及异步内容增长需要当前构建的浏览器证据。 验收报告应列明源码/产物版本、真实或合成输入、未覆盖条件以及清理结果。V8 函数或区间命中不等于 TypeScript 行/分支百分比;早期迭代的录像、Chrome/Safari 手工体验和单个构建通过不能证明本提案的完整矩阵已通过。 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml index 06547f7c98..d0ee532e45 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.i18n.yaml @@ -12,11 +12,11 @@ en: bda6c4b3dfff143e zh: 4316f6dec6adaa50 /agent-note-chat-history-prefetch-and-safe-consumption/proposal/manual-and-automatic-loading: - en: 2cbfd8cc05037895 - zh: 024968506e2ac994 + en: 9f3707f7d6c3d98e + zh: f8903e2d1d652535 /agent-note-chat-history-prefetch-and-safe-consumption/proposal/position-and-status-presentation: - en: 28d0c3b79f07ef07 - zh: b62ac1c02f23e4fe + en: 33f2466b802f3957 + zh: 095227215a22b403 /agent-note-chat-history-prefetch-and-safe-consumption/proposal/scope-and-retained-decisions: en: dd4eeadd2fccab4b zh: e05d53e63cc44ddf @@ -24,8 +24,8 @@ en: 7c6d9d470c5b5c93 zh: dc12846ee0f56aae /agent-note-chat-history-prefetch-and-safe-consumption/acceptance-criteria: - en: b3005052df98ab10 - zh: c4bdf2bed8d23550 + en: f9efd25288474b8a + zh: 9271fde45be71de6 /agent-note-chat-history-prefetch-and-safe-consumption/risks: - en: 4f1eac5c4dbd0b5e - zh: 9475ec9fa3bd9246 + en: ff3b2da49f5fb541 + zh: b11afa7556f3f313 diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md index 778c11c43e..0e511c63a0 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.md @@ -14,7 +14,7 @@ Separate requesting history from consuming it. The Client Session retains at mos ### Manual and automatic loading -A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. A temporary blocker does not complete the click; the operation ends with effective consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent. +A manual click retains one loading intent: consume an existing page, join an in-flight request, or request a page. Once data is available, the click bypasses automatic motion and input blockers: it uses the first paging anchor at the top, or captures the current reading anchor elsewhere with the paging anchor as fallback, and consumes through existing preservation without waiting for an animation callback. If neither anchor is available, consumption still proceeds without a position guarantee. The operation ends with consumption, confirmed exhaustion, or an explicit failure. A newer Turn jump, return to bottom, view closure, or other navigation or lifecycle change can cancel the earlier reading intent. Automatic loading requests history after the reader leaves tail following and comes within two viewport heights of the history control. It reuses the existing 500ms reading sample, scroll completion, content commits, and size notifications, without another polling loop or IntersectionObserver. Detection can therefore wait until the next existing sample. @@ -22,12 +22,12 @@ A cached page and an intent to continue automatically are separate facts. Automa | State when data is ready | Automatic intent | Manual intent | |---|---|---| -| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume with native browser anchoring | +| Ordinary outer momentum, with other conditions satisfied | Consume with native browser anchoring | Consume through current-anchor preservation | | Stationary reading away from the top | Consume with existing reading preservation | Consume with existing reading preservation | -| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Reuse the paging anchor and correct once after prepend | -| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Retain intent until completion | -| A finger held down or actual inner scrolling | Retain intent and continue afterward | Retain intent and continue afterward | -| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Retain intent until usable | +| `scrollTop ≤ 0.5`, with other conditions satisfied | Reuse the paging anchor and correct once after prepend | Consume through current-anchor preservation | +| Folding, revealing, or an existing follow animation | Keep the page and return to the button | Consume the available page through existing preservation | +| A finger held down or actual inner scrolling | Retain intent before testing motion blockers; recheck afterward | Consume the available page through existing preservation | +| A held mouse pointer, scrollbar dragging, or temporarily unavailable positioning | Keep the page and return to the button | Consume the available page; no anchor means no position guarantee | | Tail following resumes after automatic prefetch | Keep the page and cancel automatic consumption | The click has paused tail following | | Streaming continues at the tail | Does not itself block consumption | Does not itself block consumption | @@ -35,9 +35,9 @@ After fallback, scrolling, animation completion, and content notifications canno ### Position and status presentation -The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. A prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; persistent preservation elsewhere retains its existing lifetime. Both modes restore the screen position captured immediately before consumption with the same formula; they differ only in whether preservation remains active afterward. The one-shot path does not reconstruct intervening reader movement or restart momentum. +The actual conversation scrollport uses `overscroll-behavior-y: none` to suppress vertical boundary bounce and scroll chaining, without implementing a different momentum animation. An automatic prepend at the top reuses the existing paging-position record and correction calculation, applies it once, and releases it; manual consumption and stationary preservation retain their existing persistent lifetime. Both modes restore the screen position captured immediately before consumption with the same formula; they differ only in whether preservation remains active afterward. The one-shot path does not reconstruct intervening reader movement or restart momentum. Consumption completion also settles and clears the one-shot record when the visible Node order does not change; view closure or history failure discards it without applying it. -The history control keeps the same height across states. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row. +The history control keeps the same height across states. Loading and Processing remain clickable to join the current request or consume the cached page; only confirmed exhaustion disables the button. A network request shows Loading earlier; an active consumption intent without a held input shows Processing; automatic fallback or a held input shows Load earlier; failure shows Retry loading; consuming the final page shows Start of conversation. The control is excluded from native anchoring. Session `historyWasPartial` records that this instance has displayed incomplete history and survives component remounts and reconnects; a short Session that opens complete has no history row. ### Scope and retained decisions @@ -61,7 +61,7 @@ Do not add `flushSync` or change Conversation publication cadence, fold-batch ta - Requests, staging, and consumption never duplicate a page request; tail streaming continues. - Ordinary events do not revive automatic fallback; touch, inner scrolling, and manual clicks retain their specified continuation. -- Stationary and top-edge prepends preserve old content position; ordinary momentum consumption adds no outer JS scroll write. +- Stationary and top-edge prepends preserve old content position; ordinary automatic momentum consumption adds no outer JS scroll write. - Failure, no progress, exhaustion, reconnect, and explicit navigation have defined outcomes without request loops or stale-page consumption. - Control states have equal height; existing fold-driver behavior is retained, and browser evidence identifies the current build, simulated inputs, and missing cases. @@ -69,6 +69,6 @@ Do not add `flushSync` or change Conversation publication cadence, fold-batch ta One-shot correction restores a captured screen position rather than estimating reader velocity. Input or browser movement between capture and application can therefore affect the resulting motion; validation must cover the actual browser and input sequence. The shared formula does not add scroll-position deltas that could already include native anchoring. See the [technical risks](2026-11-06-chat-history-consumption-details.md#risks). -CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. A stationary manual operation that can never obtain an anchor retains its completion intent and needs coverage for that structure. +CSS feature support alone does not establish that native anchoring can act. Automatic prefetch waits for the first size observation, and the 500ms sample can let fast scrolling reach the top first. The synchronous geometry read after insertion is a cost of one-shot correction; its call site alone does not prove that it adds no layout. Manual consumption without a usable anchor can move visible content. It can also establish persistent preservation during an already active touch gesture, constraining that gesture or its momentum until a new reading input releases the anchor; see the [manual paging limitation](../../../../packages/client/ui-chat/README.md#known-limitations-and-deferred-work). Audit and measurement are ongoing, so this record remains proposed. Earlier Chrome/Safari manual feedback and headless results from different iterations do not establish a complete matrix pass for the final source; actual scrollbar dragging, same-document reconnect, cross-platform input, and exceptional cleanup paths require separately attributed evidence. diff --git a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md index d9f7c8e57a..1279f75c51 100644 --- a/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md +++ b/.agents/notes/proposed/feature/2026-11-06-chat-history-consumption.zh.md @@ -14,7 +14,7 @@ Status: proposed ### 手动与自动加载 -手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。暂时不安全不算点击完成;该操作以有效消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。 +手动点击保留一次加载意图:已有缓存就消费缓存,有在途请求就等待该请求,否则请求一页。数据可用后,点击绕过自动路径的动画和输入阻塞:在顶部使用首条分页锚点,其他位置采集当前阅读锚点并以分页锚点兜底,再通过既有保位路径消费,不等待动画回调。两个锚点都不存在时仍消费,但不保证位置稳定。该操作以消费、确认到头或明确失败结束。显式 Turn 跳转、返回底部、会话关闭等新的导航或生命周期变化可以取消原阅读意图。 自动加载在读者离开底部跟随、进入距历史控件两屏以内时请求。它复用已有 500ms 阅读采样及滚动结束、内容提交、尺寸通知,不新增轮询或 IntersectionObserver。代价是发现进入预取范围可能延后至下一次已有采样。 @@ -22,12 +22,12 @@ Status: proposed | 数据就绪时的状态 | 自动意图 | 手动意图 | |---|---|---| -| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 浏览器原生锚定,消费 | +| 普通外层惯性,其他条件允许 | 浏览器原生锚定,消费 | 通过当前锚点保位消费 | | 非顶部静止阅读 | 既有阅读保位,消费 | 既有阅读保位,消费 | -| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 复用分页锚点,前插后补偿一次 | -| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 保留意图,等待结束 | -| 手指按住或实际内层滚动 | 保留意图,结束后继续 | 保留意图,结束后继续 | -| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 保留意图,等待可用 | +| `scrollTop ≤ 0.5`,其他条件允许 | 复用分页锚点,前插后补偿一次 | 通过当前锚点保位消费 | +| 折叠、展开或已有跟随动画 | 保留缓存,退回按钮 | 数据可用即通过既有保位消费 | +| 手指按住或实际内层滚动 | 优先于动画判断保留意图,结束后重查 | 数据可用即通过既有保位消费 | +| 鼠标按住、滚动条拖动或定位能力暂不可用 | 保留缓存,退回按钮 | 消费可用页;没有锚点时不保证位置稳定 | | 自动预取后恢复底部跟随 | 保留缓存,取消自动消费 | 点击已暂停底部跟随 | | 底部继续流式输出 | 本身不阻止消费 | 本身不阻止消费 | @@ -35,9 +35,9 @@ Status: proposed ### 位置与状态展示 -会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;非顶部持续保位保持原生命周期。两种模式用相同公式恢复消费前刚采集的屏幕位置,只区别于应用后是否继续保位。一次补偿不重建采集期间的读者移动,也不重新启动惯性。 +会话实际滚动容器设置 `overscroll-behavior-y: none`,关闭纵向边界回弹和滚动传递,不实现另一套惯性动画。自动顶部前插复用既有分页位置记录和补偿计算,只应用一次并释放;手动消费和静止保位保持原有持续保位生命周期。两种模式用相同公式恢复消费前刚采集的屏幕位置,只区别于应用后是否继续保位。一次补偿不重建采集期间的读者移动,也不重新启动惯性。即使可见 Node 顺序未变化,消费完成也会结算并清除一次补偿记录;视图关闭或历史失败时直接丢弃,不再应用。 -历史控件各状态保持同高。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。 +历史控件各状态保持同高。“正在加载”和“正在处理”仍可点击,以加入当前请求或消费缓存;只有确认到头才禁用按钮。网络请求显示“正在加载”;仍有消费意图且未按住输入时显示“正在处理”;自动回退或输入按住时显示“加载更早”;失败显示“重新加载”;最后一页消费完成后显示“已到会话开头”。控件不参与原生锚定。Session 的 `historyWasPartial` 记录本实例曾显示不完整历史,组件重挂载和重连保留此事实;首次打开即完整的短会话不添加历史行。 ### 范围与既有决策 @@ -61,7 +61,7 @@ Status: proposed - 请求、暂存与消费期间不重复取页;尾部流式继续更新。 - 自动退回按钮后不会被普通事件恢复;触摸、内层滚动和手动点击保留约定的续接。 -- 静止和顶部前插保持旧内容位置;普通惯性消费不新增 JS 外层滚动写入。 +- 静止和顶部前插保持旧内容位置;普通自动惯性消费不新增 JS 外层滚动写入。 - 页面失败、无进展、到头、重连和显式导航均有明确结果,不循环请求或消费过期页。 - 控件各状态同高;既有折叠驱动保持行为,真实浏览器验收区分当前构建、输入模拟和未覆盖情况。 @@ -69,6 +69,6 @@ Status: proposed 一次补偿恢复采集的屏幕位置,不估算读者速度。采集到应用之间的输入或浏览器移动可能影响最终运动,因此需要验证实际浏览器和输入序列。共享公式不叠加可能已包含原生锚定的滚动位置增量。见[技术风险](2026-11-06-chat-history-consumption-details.zh.md#risks)。 -原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。静止手动消费若始终无法获得锚点,完成意图仍会等待,需要覆盖该特殊结构。 +原生锚定适用性不能只由 CSS 支持检查保证。首次尺寸观察前不会自动预取;500ms 采样可能使高速滚动先到顶部。前插后的同步几何读取是一次补偿的成本,不能仅凭调用位置保证没有额外布局。没有可用锚点的手动消费可能移动可见内容。手动消费也可能在已有触摸手势进行中建立持续保位,约束该手势或其惯性,直到新的阅读输入释放锚点;见[手动分页限制](../../../../packages/client/ui-chat/README.zh.md#known-limitations-and-deferred-work)。 审计与测量尚在进行,本记录保持 proposed。此前 Chrome/Safari 手工反馈和不同迭代的 headless 结果不等同于最终源码的全矩阵通过;真实滚动条拖动、同页面重连、多平台输入和异常清理分支应按实际证据单独报告。 diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index fd5f778c1e..4b76660b22 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -6,7 +6,7 @@ import { access, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { fileURLToPath } from 'node:url' -import type { Browser, Page } from 'playwright' +import type { Browser, Page, Route } from 'playwright' import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it } from 'vitest' import type { StreamChunk } from '@deepseek-ai/dsh-llm' @@ -476,23 +476,41 @@ async function expectMarkerAboveComposer(page: Page, marker: string): Promise { - await wheelToHistoryStart(page) - const older = page.getByRole('button', { name: 'Load earlier', exact: true }) - const loading = page.getByRole('button', { name: 'Loading…', exact: true }) - await older.waitFor({ timeout: 10_000 }) - const anchor = await visibleFlowAnchor(page) - const before = await loadedFlowRows(page) - await older.click() - await expect.poll(async () => ( - await loadedFlowRows(page) > before && await loading.count() === 0 - ), { timeout: 30_000 }).toBe(true) - await nextPaint(page) - if (await page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) { - expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0) - return +async function loadEarlierWithAnchor(page: Page): Promise { + // Auto-prefetch may start while scrolling to the button. Hold its response until the reading anchor is captured. + const gate = Promise.withResolvers() + const pending = new Set>() + const hold = (route: Route): Promise => { + const work = gate.promise.then(() => route.continue()) + pending.add(work) + return work.finally(() => { pending.delete(work) }) + } + await page.route('**/api/session/page', hold) + try { + await wheelToHistoryStart(page) + const history = page.locator('[data-chat-history]') + const older = history.getByRole('button') + await older.waitFor({ timeout: 10_000 }) + if (await older.isDisabled()) return false + const anchor = await visibleFlowAnchor(page) + const before = await loadedFlowRows(page) + await older.click() + gate.resolve(undefined) + await expect.poll(async () => ( + await loadedFlowRows(page) > before && await history.getAttribute('data-chat-history') === 'idle' + ), { timeout: 30_000 }).toBe(true) + await nextPaint(page) + if (await older.isDisabled()) { + expect(await page.locator('[data-turn-process][aria-expanded="false"]').count()).toBeGreaterThan(0) + return true + } + await expectSameFlowTop(page, anchor) + return true + } finally { + gate.resolve(undefined) + await page.unroute('**/api/session/page', hold) + await Promise.all([...pending]) } - await expectSameFlowTop(page, anchor) } async function fileExists(path: string): Promise { @@ -1300,6 +1318,8 @@ describe('web e2e: long Chat scroll contract', () => { let releaseHistory = (): void => {} let held = false + let historyRequests = 0 + const heldContinued = Promise.withResolvers() let releaseGate: (() => void) | undefined const gate = new Promise((resolve) => { releaseGate = resolve }) releaseHistory = () => { releaseGate?.() } @@ -1308,12 +1328,17 @@ describe('web e2e: long Chat scroll contract', () => { method?: string payload?: { args?: { request?: { beforeSeq?: number } } } } - if (!held && request.method === 'session/page' - && request.payload?.args?.request?.beforeSeq !== undefined) { + const historyRequest = request.method === 'session/page' && request.payload?.args?.request?.beforeSeq !== undefined + if (historyRequest) historyRequests += 1 + if (!held && historyRequest) { held = true await gate - } - await route.continue() + try { + await route.continue() + } finally { + heldContinued.resolve(undefined) + } + } else await route.continue() }) const settled = world.scaffold.whenTurnSettled(60_000) @@ -1325,8 +1350,12 @@ describe('web e2e: long Chat scroll contract', () => { await world.page.getByText(LIVE_TEXT_FIRST, { exact: false }).last().waitFor({ timeout: 15_000 }) await wheelToHistoryStart(world.page) const beforeRows = await loadedFlowRows(world.page) - await world.page.getByRole('button', { name: 'Load earlier', exact: true }).click() await expect.poll(() => held, { timeout: 10_000 }).toBe(true) + const history = world.page.locator('[data-chat-history]') + await expect.poll(() => history.getAttribute('data-chat-history')).toBe('loading') + // The upward gesture already requested the page. A click joins that request even though its label is loading. + await history.getByRole('button').click() + expect(historyRequests).toBe(1) await wheelTranscript(world.page, 420) const readerAnchor = await visibleFlowAnchor(world.page) @@ -1344,6 +1373,9 @@ describe('web e2e: long Chat scroll contract', () => { } finally { releaseText() releaseHistory() + if (held) await heldContinued.promise + // Release both producers before disposing the Session even if an assertion above fails. + await settled } await settled @@ -1353,10 +1385,10 @@ describe('web e2e: long Chat scroll contract', () => { let additionalPages = 0 while (additionalPages < 8) { - await wheelToHistoryStart(world.page) - if (await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count() === 0) break - await loadEarlierWithAnchor(world.page) - additionalPages += 1 + const before = await loadedFlowRows(world.page) + const consumed = await loadEarlierWithAnchor(world.page) + if (consumed || await loadedFlowRows(world.page) > before) additionalPages += 1 + if (await world.page.locator('[data-chat-history]').getByRole('button').isDisabled()) break } expect(additionalPages).toBeGreaterThan(0) // The whole log is loaded: turn 1's unique marker renders in the @@ -1364,7 +1396,9 @@ describe('web e2e: long Chat scroll contract', () => { // page remains. expect(await world.page.locator('[data-conversation-scroll]') .getByText(HISTORY_FIXTURE.markers.user(1), { exact: false }).count()).toBe(1) - expect(await world.page.getByRole('button', { name: 'Load earlier', exact: true }).count()).toBe(0) + const history = world.page.locator('[data-chat-history]') + expect(await history.getAttribute('data-chat-history')).toBe('idle') + expect(await history.getByRole('button', { name: 'Start of conversation', exact: true }).isDisabled()).toBe(true) assertClean(world) }) }, 180_000) diff --git a/packages/client/ui-chat/README.i18n.yaml b/packages/client/ui-chat/README.i18n.yaml index dd8cf646da..0ea68825c1 100644 --- a/packages/client/ui-chat/README.i18n.yaml +++ b/packages/client/ui-chat/README.i18n.yaml @@ -36,8 +36,8 @@ en: e2b02942a55fb669 zh: a38bbee0cc69ae4e /deepseek-ai-dsh-client-ui-chat/scroll-ownership: - en: b26ab997d694ef90 - zh: 1f8a16ba02bab301 + en: 1b12aa6c505dde3b + zh: 88e1654dd63816d7 /deepseek-ai-dsh-client-ui-chat/model-experience: en: c17b4dd43a61c569 zh: f7414309810c3a08 @@ -45,8 +45,8 @@ en: 15a7151ff9268f15 zh: 6eae68c718be579b /deepseek-ai-dsh-client-ui-chat/known-limitations-and-deferred-work: - en: 811787a5d2feaa90 - zh: 3f1697bbc1fc7691 + en: b3b03e8e2fe371a1 + zh: c5eb8b7205e0e880 /deepseek-ai-dsh-client-ui-chat/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: e88aeb617ffb74ea diff --git a/packages/client/ui-chat/README.md b/packages/client/ui-chat/README.md index e00a884771..672da9097d 100644 --- a/packages/client/ui-chat/README.md +++ b/packages/client/ui-chat/README.md @@ -186,7 +186,7 @@ Within a process group, wheel, touchstart, and any pointerdown interrupt an acti `useChatReading` owns follow policy, sampled reader input, and semantic memory; `useChatNavigation` owns turn jumps and requests preservation from the viewport. Reading gestures release the paging anchor, but composer clicks, typing, and non-scrolling keys retain it. A deferred history request captures its anchor at consumption rather than at request time. `useChatScroll` coordinates their committed inputs. Explicit navigation carries its measured landing into reading policy, so it does not rediscover the known target with a hit test. -History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and inner scrolling retain automatic intent until release; active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation. Stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. At scrollTop ≤ 0.5, the first paging anchor uses the same captured-screen-position restoration as persistent preservation, once, then releases immediately; it does not add scroll-position deltas that native anchoring may already have applied. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. +History prefetch uses the existing 500ms reading sample and content/size notifications, with one distance check before requesting within two viewport heights. At most one page waits for consumption. Touch and actual inner scrolling retain automatic intent before motion blockers are evaluated, then recheck after release; other active motion, pointer holds, or an unavailable anchor return automatic loading to the button without retrying the cached page. Loading and processing buttons remain clickable, joining the current request without duplication. Explicit clicks retain intent until consumption, exhaustion, failure, or superseding navigation; once a page is available they bypass automatic blockers, use the first paging anchor at the top or the current reading anchor elsewhere with a paging fallback, and consume through existing preservation without waiting for animation completion. If no anchor is available, manual consumption still proceeds without a position guarantee. Automatic stationary consumption uses retained positioning; ordinary outer scrolling uses browser anchoring. For automatic consumption at scrollTop ≤ 0.5, the first paging anchor uses the same captured-screen-position restoration as persistent preservation, once, then releases immediately; it does not add scroll-position deltas that native anchoring may already have applied. The one-shot record is settled on history consumption completion even when the visible Node order stays unchanged; view closure or history failure discards it without application. The actual Chat scrollport disables vertical overscroll bounce, without adding a scrolling animation. The history row keeps its height through loading, processing, retry, and exhaustion; initially complete Sessions omit it. Active-Turn highlighting is approximate: `readVisibleTurn` binary-searches the flow slot's direct Node/Group boxes (or the column's in standalone rendering) and retains the preceding candidate in gaps. It neither hit-tests the document nor searches Group members or all Turn markers. Empty Seats retain zero-height in-flow boxes so outer positions remain ordered without extra spacing. This lookup does not change semantic position capture or paging compensation. @@ -213,6 +213,8 @@ None; Chat presentation does not assemble or mutate provider requests. +- **Manual paging during an active gesture** — manual consumption captures a persistent anchor when its page arrives, even if a touch gesture is already in progress. Subsequent movement can be restored to that anchor, constraining the gesture or its momentum until a new reading input releases it. The automatic touch deferral does not protect this explicit manual path. + - **Running-icon resolution** — the animated whale uses a 28×28 image at a default 14×14 CSS size. Larger content fonts or device pixel ratios above 2 can soften the raster stroke; the static fallback remains vector-based. Browser image caching owns the animation clock, so remounting does not guarantee playback restarts at the first frame. - **Tool-change presentation** — The `developer-message` Definition shares context presentation with `input-message`. Tool-only developer messages name a single added or removed tool inline without expansion. Multiple changes show added/removed counts and expand to comma-separated tool lists, one line per change kind. Mixed content uses the generic context presentation. diff --git a/packages/client/ui-chat/README.zh.md b/packages/client/ui-chat/README.zh.md index 29e8a373fa..29a1951662 100644 --- a/packages/client/ui-chat/README.zh.md +++ b/packages/client/ui-chat/README.zh.md @@ -186,7 +186,7 @@ Chat 会在历史前插与 renderer 重新挂载时恢复语义锚点,并且 `useChatReading` 负责跟随策略、读者输入采样和语义位置记忆;`useChatNavigation` 负责轮次跳转,并向视口请求位置保持。阅读手势释放分页锚点,composer 内的点击、打字和非滚动按键则保留锚点。延迟消费的历史请求在消费时采集锚点,不在发请求时采集。`useChatScroll` 协调已提交的输入。显式导航把测得的落点交给阅读策略,因此无需通过命中测试重新寻找已知目标。 -历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和内层滚动保留自动意图至释放;动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。明确点击保留意图,直到消费、到头、失败或被新导航取代。静止消费使用保位,普通外层滚动使用浏览器锚定;scrollTop ≤ 0.5 时,首条分页锚点与持续保位共用采集屏幕位置的恢复公式,只应用一次便立即释放;不再叠加可能已由原生锚定产生的滚动位置增量。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 +历史预取复用已有 500ms 阅读采样及内容/尺寸通知,在请求前确认距顶部两屏以内,最多一页等待消费。触摸和实际内层滚动优先于动画阻塞判断保留自动意图,释放后重查;其余动画、指针按住或无法取得锚点使自动加载退回按钮,不自动重试缓存页。加载和处理状态的按钮仍可点击,加入当前请求而不重复请求。明确点击保留意图,直到消费、到头、失败或被新导航取代;页面可用后绕过自动阻塞,在顶部使用首条分页锚点,其他位置使用当前阅读锚点并以分页锚点兜底,通过既有保位消费,不等待动画结束。没有可用锚点时手动消费仍继续,但不保证位置稳定。自动静止消费使用保位,普通外层滚动使用浏览器锚定;自动消费在 scrollTop ≤ 0.5 时,首条分页锚点与持续保位共用采集屏幕位置的恢复公式,只应用一次便立即释放;不再叠加可能已由原生锚定产生的滚动位置增量。历史消费完成时,即使可见 Node 顺序未变化,也会结算一次补偿记录;视图关闭或历史失败时丢弃记录,不应用补偿。实际 Chat 滚动区关闭纵向越界回弹,不新增滚动动画。历史行在加载、处理、重试和到头时保持高度,首次打开就完整的 Session 不显示该行。 活跃轮次高亮采用近似定位:`readVisibleTurn` 对 flow 插槽的直属 Node/Group 布局盒二分(独立渲染时使用正文容器的直属布局盒),落在间隙时保留前方候选。它不做文档命中测试,也不查询 Group 成员或全部 Turn 标记。空 Seat 保留零高度的流内布局盒,使外层位置有序且不增加间距。这种定位不改变语义位置捕获或分页补偿。 @@ -213,6 +213,8 @@ Markdown 文件、链接、图片、引用 chip 和工具文件控件将明确 +- **进行中手势遇到手动分页**——手动消费在页面到达时采集持续保位锚点,即使触摸手势已经开始。随后移动可能被恢复到该锚点,约束手势或其惯性,直到新的阅读输入释放锚点。自动路径的触摸延迟不保护这一明确的手动路径。 + - **运行图标分辨率**——动态鲸鱼使用 28×28 图片,默认 CSS 尺寸为 14×14。较大的正文字号或大于 2 的设备像素比可能使位图描边变模糊;静态回退图标仍为矢量图。浏览器图片缓存管理动画时钟,因此重新挂载不保证从第一帧重新播放。 - **工具变更展示** — `developer-message` Definition 与 `input-message` 共用上下文展示。仅包含工具变更的 developer 消息在单个工具新增或移除时直接显示工具名,不提供展开操作。多个变更显示新增、移除数量,展开后按变更类型分别以逗号分隔显示一行工具列表。混合内容使用通用上下文展示。 diff --git a/packages/client/ui-chat/src/client/chat/ChatView.tsx b/packages/client/ui-chat/src/client/chat/ChatView.tsx index 8fa10ca0ec..c9143248a1 100644 --- a/packages/client/ui-chat/src/client/chat/ChatView.tsx +++ b/packages/client/ui-chat/src/client/chat/ChatView.tsx @@ -252,7 +252,7 @@ export function ChatView({ )} {(hasMore || historyWasPartial) && (
- + + )} +

+ )} + {result.truncated && ( +

{t('search.truncated', { count: String(result.count) })}

+ )} + {result.incomplete &&

{t('search.incomplete')}

} + + ) +} + +/** + * What the results area shows for a search the Host could not run: why, and a control that runs it again. + * @param props.failure - the failed search's Remote failure. + * @param props.onRetry - runs the search again. + * @param props.t - namespace-bound translate. + * @returns the notice. + */ +function SearchFailure({ failure, onRetry, t }: { + readonly failure: RemoteFailure + readonly onRetry: () => void + readonly t: TranslateNS<'sidebarFiles'> +}): ReactNode { + return ( +
+

{t('search.failed', { message: failureLine(t, failure) })}

+ +
+ ) +} + /** * The navigator Factory's component. * @param props - the tab it is drawn for, the pane's store records, the tree's face, and copy. * @returns the navigator, or nothing while hidden or without a workspace. */ export function FileNavigator({ - useTabInfo, page, onOpen, sessionId, useSessions, useStore, actions, useRowWidth, useCanOpen, - attach, placeBeside, hold, toggle, scrolled, bodyDrawn, currentDrawn, navigatorDrawn, t, renderFactorySlot, useContextMenu, + useTabInfo, page, onOpen, sessionId, useSessions, useStore, actions, useRowWidth, useCanOpen, useSearchPreferences, + attach, placeBeside, hold, toggle, scrolled, bodyDrawn, currentDrawn, navigatorDrawn, + setQuery, toggleSearch, retrySearch, setSearchPreferences, searchDrawn, t, renderFactorySlot, useContextMenu, }: FactoryComponentPropsOf<'sidebar.files.navigator'>): ReactNode { const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const paneId = panel.id + // A Session's working directory comes from its header and never changes once + // known, so every search result the pane's store holds is rooted at it. const cwd = useSessions(sessions => sessions.byId[sessionId]?.cwd) const state = useStore(store => store.byPane[paneId]) const rowWidth = useRowWidth(paneId) @@ -83,17 +179,38 @@ export function FileNavigator({ // Measured by the face; the viewport rule is CSS's, read again when a file opens. const mode = navigatorMode(rowWidth) const tree = state?.tree?.root === cwd ? state?.tree : undefined + // The face resolves every key to a source, so the renderer never reports one unavailable. + /* v8 ignore next -- the fallback only satisfies the keyed hook's optional snapshot type. */ + const preferences: WorkspaceSearchPreferences = useSearchPreferences(cwd ?? '') ?? defaultSearchPreferences() + const { showHidden } = preferences + const query = state?.query ?? '' + const searchBarOpen = !page || state?.searchBarOpen === true + const search = state?.search + const pending = search?.pending === true + const result = search?.result + const found = result?.kind === 'found' ? result : undefined const [dragging, setDragging] = useState(false) + const [draft, setDraft] = useState(undefined) + const settings = draft !== undefined const drag = useRef<{ readonly x: number; readonly width: number } | undefined>(undefined) + const input = useRef(null) + const trigger = useRef(null) // Stable, so each element registers once per drawing rather than on every render. const navigatorRef = useCallback( (element: HTMLElement | null) => { navigatorDrawn(paneId, element, !page) }, [navigatorDrawn, paneId, page], ) + // Also new when the container switches between the tree and the results, so + // the face restores that view's scroll offset once its rows are drawn. + const resultsShown = search !== undefined const bodyRef = useCallback( (body: HTMLDivElement | null) => { bodyDrawn(paneId, tab.contentId, body) }, - [bodyDrawn, paneId, tab.contentId], + [bodyDrawn, paneId, tab.contentId, resultsShown], ) + const inputRef = useCallback((element: HTMLInputElement | null) => { + input.current = element + searchDrawn(paneId, element) + }, [searchDrawn, paneId]) const currentRef = useCallback((row: HTMLElement | null) => { currentDrawn(paneId, row) }, [currentDrawn, paneId]) useEffect(() => attach(paneId, tab.id, tab.signal), [attach, paneId, tab.id, tab.signal]) @@ -109,13 +226,23 @@ export function FileNavigator({ const root = tree?.root const levels = tree?.levels const expanded = tree?.expanded - const entries = useMemo(() => levels === undefined ? undefined : workspaceEntries(levels), [levels]) + const entries = useMemo(() => levels === undefined ? undefined : workspaceEntries(levels, showHidden), [levels, showHidden]) const directories = useMemo( () => root === undefined || levels === undefined || expanded === undefined ? undefined - : workspaceDirectories({ root, levels, expanded }, t), - [root, levels, expanded, t], + : workspaceDirectories({ root, levels, expanded }, t, showHidden), + [root, levels, expanded, t, showHidden], ) + const resultTree = found !== undefined && found.count > 0 ? found.tree : undefined + const resultCurrent = useMemo( + () => resultTree === undefined || relativePath === undefined ? undefined : locateFile(resultTree, relativePath).current, + [resultTree, relativePath], + ) + const resultEntries = useMemo( + () => resultTree === undefined ? undefined : workspaceEntries(resultTree.levels, showHidden), + [resultTree, showHidden], + ) + const resultDirectories = useMemo(() => resultTree === undefined ? undefined : searchDirectories(resultTree), [resultTree]) // Kept between renders, so the tree redraws only when what it shows changes, // not on every measure of the row or render of the host. const view = useMemo(() => { @@ -131,12 +258,27 @@ export function FileNavigator({ : { kind, value: { sessionId, path: entry.path, paneId } }), } }, [tree, paneId, sessionId, toggle, canOpen, onOpen, getTriggerProps]) + // The results keep their own expansion; every other gesture acts as on the tree. + const resultView = useMemo(() => view === undefined || resultTree === undefined ? undefined : { + ...view, + expanded: resultTree.expanded, + onToggle: (entry: TreeEntry) => { toggleSearch(paneId, entry.path) }, + }, [view, resultTree, toggleSearch, paneId]) + const closeSettings = useCallback((rules: readonly ExclusionRule[], refocus: boolean) => { + setDraft(undefined) + if (refocus) trigger.current?.focus() + if (cwd !== undefined && rules !== preferences.rules) setSearchPreferences(cwd, { rules }) + }, [cwd, preferences.rules, setSearchPreferences]) if (cwd === undefined || !open) return null const geometry = navigatorGeometry(rowWidth, state?.width ?? DEFAULT_NAVIGATOR_WIDTH) // The page's tree always fills the page; a preview's follows its row. const shown = page ? undefined : mode const clamp = (next: number): number => Math.min(Math.max(next, geometry.minimum), geometry.maximum) + const clear = (): void => { + setQuery(paneId, cwd, '') + input.current?.focus() + } return ( ) } diff --git a/packages/client/ui-sidebar-files/src/client/FileTree.module.css b/packages/client/ui-sidebar-files/src/client/FileTree.module.css index d7bd27a608..fe7cf766fc 100644 --- a/packages/client/ui-sidebar-files/src/client/FileTree.module.css +++ b/packages/client/ui-sidebar-files/src/client/FileTree.module.css @@ -111,3 +111,9 @@ color: var(--dsw-alias-label-tertiary); font-size: 12px; } + +/* The occurrences of the highlighted text in a name. */ +.match { + color: var(--dsw-alias-state-business-primary); + background: transparent; +} diff --git a/packages/client/ui-sidebar-files/src/client/FileTree.tsx b/packages/client/ui-sidebar-files/src/client/FileTree.tsx index 7a9b129896..30516ba28e 100644 --- a/packages/client/ui-sidebar-files/src/client/FileTree.tsx +++ b/packages/client/ui-sidebar-files/src/client/FileTree.tsx @@ -5,7 +5,8 @@ * path, adds the directories the paths imply, orders every drawn level, and * draws the rows and their icons. It redraws when its * props or the occurrence's local selection change, and orders a drawn level - * again only when the names or directory kinds in that level change. + * again only when the names or directory kinds in that level change. Given a + * query to highlight, it marks each occurrence of the query inside a name. */ import { memo, useMemo } from 'react' import type { ReactNode } from 'react' @@ -14,6 +15,7 @@ import type { FactoryComponentPropsOf } from '@deepseek-ai/dsh-client-ui-slots' import type { ContextMenuTriggerProps } from '@deepseek-ai/dsh-client-ui-context-menu/client' import { FileTypeIcon, classifyFileType, IconFolderCloseRegular, IconFolderOpenRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type {} from './locales.ts' +import { matchRanges } from './search-tree.ts' import css from './FileTree.module.css' /** What a row is: a directory toggles, a file opens, and anything else is listed without either. */ @@ -51,6 +53,13 @@ export interface TreeDirectoryState { readonly failure?: string /** Entries are missing from the listing. */ readonly truncated?: true + /** + * The caller left entries out, which changes what the directory says while + * none is drawn: `hidden` says that its hidden entries are not shown, and + * `unmatched`, for entries that are a selection such as search matches, says + * nothing instead of that it is empty. + */ + readonly omitted?: 'hidden' | 'unmatched' } /** The `sidebar.files.tree` Factory's input: data and callbacks only. */ @@ -70,6 +79,8 @@ export interface FileTreeInput { readonly expanded: readonly string[] /** Listing state by directory key, root included; a directory absent here is listed and complete. */ readonly directories?: Readonly> | undefined + /** Text whose occurrences inside each name are highlighted, ignoring case; nothing is highlighted without it. */ + readonly highlight?: string | undefined /** Key of the file to mark as current, when it is drawn. */ readonly current?: string | undefined /** Receives the current file's main button while drawn. @param row - the button, or `null` once it goes. */ @@ -190,12 +201,27 @@ interface TreeContext { readonly Accessory: ReturnType['useFactorySlot']> } +/** One entry's name, with the occurrences of the text to highlight marked. */ +function Name({ name, highlight }: { name: string; highlight: string | undefined }): ReactNode { + const ranges = highlight === undefined ? [] : matchRanges(name, highlight) + if (ranges.length === 0) return {name} + const parts: ReactNode[] = [] + let at = 0 + for (const [start, end] of ranges) { + if (start > at) parts.push(name.slice(at, start)) + parts.push({name.slice(start, end)}) + at = end + } + if (at < name.length) parts.push(name.slice(at)) + return {parts} +} + /** One entry's row, and its children when it is an expanded directory. */ function Entry({ node, tree }: { node: TreeNode; tree: TreeContext }): ReactNode { const { input, Accessory } = tree const { entry, kind } = node const hidden = entry.meta?.hidden === true && css.hidden - const label = {entry.name} + const label = if (kind === 'directory') { const expanded = tree.expanded.has(entry.path) return ( @@ -260,7 +286,11 @@ function Level({ path, tree }: { path: string; tree: TreeContext }): ReactNode { return ( <> {state?.failure !== undefined &&
  • {state.failure}
  • } - {level.length === 0 && state?.failure === undefined &&
  • {t('empty')}
  • } + {level.length === 0 && state?.failure === undefined && state?.omitted !== 'unmatched' && ( + state?.omitted === 'hidden' + ?
  • {t('emptyHidden')}
  • + :
  • {t('empty')}
  • + )} {order.map(index => level[index]).filter(node => node !== undefined) .map(node => )} {state?.truncated === true &&
  • {t('truncated')}
  • } diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css index 383ecfa47d..4bddc11bb1 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.module.css +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.module.css @@ -36,6 +36,8 @@ height: 100%; min-width: 0; min-height: 0; + /* The search bar's height, which also places the settings panel below it. */ + --files-search-bar-height: 42px; color: var(--dsw-alias-label-primary); font-size: var(--dsh-content-font-size-secondary, 13px); line-height: 1.5; @@ -198,6 +200,23 @@ font-size: 12px; } +/* "No matches" with the information button whose tooltip names the filters. */ +.emptyNote { + display: flex; + align-items: center; + gap: 2px; +} + +/* The information button keeps the note's line height. */ +.infoButton { + flex: none; + width: 20px; + height: 20px; + margin-block: -2px; + padding: 0; + color: var(--dsw-alias-label-caption); +} + .status { display: flex; flex-direction: column; @@ -252,3 +271,262 @@ .titleIcon { flex: none; } + +/* The navigator's search bar above the tree: the settings control, the + field, the hidden-entry control, and the clear control in one bordered box, + drawn like the shared `Input` atom. */ +.searchBar { + flex: 0 0 auto; + box-sizing: border-box; + height: var(--files-search-bar-height); + padding: 8px 8px 4px; +} + +.searchField { + display: flex; + gap: 2px; + align-items: center; + box-sizing: border-box; + height: 100%; + padding: 0 2px; + background: var(--dsw-alias-bg-layer-1); + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-md); +} + +.searchField:focus-within { + border-color: var(--dsw-alias-state-business-primary); +} + +/* The bar's icon controls: the header tool at a size that fits inside the field. */ +.searchTool { + width: 24px; + height: 24px; + padding: 4px; +} + +.searchTool svg { + width: 14px; + height: 14px; +} + +.searchInput { + flex: 1 1 auto; + min-width: 0; + padding: 0 4px; + color: var(--dsw-alias-label-primary); + font: inherit; + background: transparent; + border: none; + outline: none; +} + +.searchInput::placeholder { + color: var(--dsw-alias-label-dimmed); +} + +/* The bar's own clear control replaces the browser's. */ +.searchInput::-webkit-search-cancel-button { + display: none; +} + +/* The results status between the bar and the results: the count, and a spinner while a search is under way. */ +.searchStatus { + display: flex; + flex: 0 0 auto; + gap: 6px; + align-items: center; + min-height: 18px; + margin: 0; + padding: 2px 18px 0; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); +} + +/* One sentence of the results status: the count. */ +.searchStatusLine { + display: block; + min-width: 0; +} + +.searchSpinner { + flex: none; +} + +/* A failed search in the results' place: the reason, and the retry control below it on the note's inset. */ +.searchFailure { + display: flex; + flex-direction: column; + gap: 6px; + align-items: flex-start; + padding-bottom: 6px; +} + +.searchRetry { + margin-left: 10px; +} + +/* The `.gitignore` choice above the add field, at a rule's height. */ +.settingsOption { + border-top: none; +} + +/* The live region stays mounted while the query is blank, without taking room. */ +.searchStatusIdle { + min-height: 0; + padding: 0; +} + +/* The settings panel floats over the tree below the search bar, inside the navigator. */ +.settings { + position: absolute; + top: var(--files-search-bar-height); + right: 8px; + bottom: 8px; + left: 8px; + z-index: 3; + display: flex; + flex-direction: column; + min-height: 0; + padding: 6px 4px 6px 10px; + background: var(--dsw-alias-bg-base); + border-radius: var(--dsw-radius-lg); + outline: none; + box-shadow: var(--dsw-elevation-prominent); +} + +.settingsHeader { + display: flex; + flex: 0 0 auto; + gap: 2px; + align-items: center; +} + +.settingsTitle { + flex: 1 1 auto; + min-width: 0; + font-weight: 500; +} + +.settingsDescription { + flex: 0 0 auto; + margin: 0 0 4px; + padding-right: 6px; + color: var(--dsw-alias-label-tertiary); + font: var(--dsw-font-xxs-12); +} + +/* One rule, and the add field above them at the same height. */ +.rule { + display: flex; + flex: 0 0 auto; + gap: 6px; + align-items: center; + box-sizing: border-box; + min-height: 32px; + margin: 0; + padding: 0 0 0 2px; + border-top: 0.5px solid var(--dsw-alias-border-l3); +} + +.addRule { + padding-right: 6px; +} + +/* The add row's plus glyph rides the tertiary ink, as the tree's folder glyph does. */ +.addRule .icon { + flex: 0 0 auto; + color: var(--dsw-alias-label-tertiary); +} + +/* The add field draws no box of its own, so its row's rule marks where typing goes. */ +.addRule:focus-within { + border-top-color: var(--dsw-alias-state-business-primary); +} + +.ruleInput { + flex: 1 1 auto; + min-width: 0; + padding: 0; + color: var(--dsw-alias-label-primary); + font: inherit; + background: transparent; + border: none; + outline: none; +} + +.ruleInput::placeholder { + color: var(--dsw-alias-label-dimmed); +} + +.settingsError { + flex: 0 0 auto; + margin: 0 0 4px; + color: var(--dsw-alias-state-error-primary); + font: var(--dsw-font-xxs-12); +} + +/* Only the list scrolls; the header and the add field stay put. */ +.rules { + flex: 1 1 auto; + min-height: 0; + margin: 0; + padding: 0; + overflow-y: auto; + list-style: none; + overscroll-behavior: contain; +} + +.ruleLabel { + display: flex; + flex: 1 1 auto; + gap: 6px; + align-items: center; + min-width: 0; + cursor: pointer; +} + +.ruleCheck { + flex: 0 0 auto; + width: 14px; + height: 14px; + margin: 0 1px; + accent-color: var(--dsw-alias-state-business-primary); +} + +.ruleCheck:focus-visible { + outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); + outline-offset: 2px; +} + +.ruleName { + min-width: 0; + padding: 6px 0; + overflow-wrap: anywhere; +} + +/* A rule the reader turned off stays listed, in the tertiary ink. */ +.ruleOff .ruleName { + color: var(--dsw-alias-label-tertiary); +} + +@media (pointer: coarse) { + .searchTool { + width: 32px; + height: 32px; + } + + .navigator { + --files-search-bar-height: 50px; + } + + .rule { + min-height: 44px; + } + + /* Below 16px, mobile browsers zoom the page when a field takes focus. */ + .searchInput, + .ruleInput { + font-size: 16px; + } +} diff --git a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx index b1361cf415..f7f5ae385f 100644 --- a/packages/client/ui-sidebar-files/src/client/FilesBody.tsx +++ b/packages/client/ui-sidebar-files/src/client/FilesBody.tsx @@ -1,10 +1,9 @@ /** * The `files` page: a file browser with no file chosen yet. * - * Its header spans the page: the workspace root's path, the tree's reload and - * the directory actions, in the order a preview's header ends with its own - * reload and file actions. The pane's navigator fills the page below it and - * stays shown, so the page draws no toggle; picking a file leaves this page as + * Its header spans the page: the workspace root's path, the tree's reload, + * the search-bar toggle, and the directory actions. The pane's navigator fills the page below it and + * stays shown, so the page draws no navigator toggle; picking a file leaves this page as * it is and opens the file where the right Sidebar places it by default * (`FileNavigator`). */ @@ -15,7 +14,7 @@ import type { InjectFace, PropsLocale, PropsRenderFactories, PropsRenderSlots, PropsRuntime, PropsStore, } from '@deepseek-ai/dsh-client-ui-slots' import { - IconPauseOutlineRegular, IconPlayOutlineRegular, IconRefreshOutlineRegular, PathLabel, Tooltip, + IconPauseOutlineRegular, IconPlayOutlineRegular, IconRefreshOutlineRegular, IconSearchOutlineRegular, PathLabel, Tooltip, } from '@deepseek-ai/dsh-client-ui-primitives' import type { FilesInjected } from './face.ts' import type {} from './FileNavigator.tsx' @@ -38,7 +37,10 @@ export type FilesBodyProps = * @returns the header above the pane's navigator, or the workspace line. */ export function FilesBody(props: FilesBodyProps): ReactNode { - const { useTabInfo, sessionId, useSessions, useStore, refresh, setAutoRefresh, renderSlot, renderFactorySlot, t, useContextMenu } = props + const { + useTabInfo, sessionId, useSessions, useStore, actions, refresh, focus, placeBeside, + setAutoRefresh, renderSlot, renderFactorySlot, t, useContextMenu, + } = props const { tab, panel } = useTabInfo() const { getTriggerProps } = useContextMenu() const onOpen = useCallback((address: string): void => { @@ -55,6 +57,8 @@ export function FilesBody(props: FilesBodyProps): ReactNode { const tree = store.byPane[panel.id]?.tree return tree?.root === cwd ? tree?.autoRefresh : undefined }) + const searchBarOpen = useStore(store => store.byPane[panel.id]?.searchBarOpen) === true + useEffect(() => cwd === undefined ? undefined : placeBeside(tab.id), [cwd, placeBeside, tab.id]) if (cwd === undefined) { return ( @@ -90,6 +94,23 @@ export function FilesBody(props: FilesBodyProps): ReactNode { + + + {renderSlot('sidebar.right.tab.files.actions', { absolutePath: cwd })}
    {navigator}
    diff --git a/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx b/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx new file mode 100644 index 0000000000..8ab9bd5ef6 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/SearchSettings.tsx @@ -0,0 +1,155 @@ +/** + * The search settings panel edits the navigator's draft of excluded directories. + * The navigator saves it when the panel closes, including through the magnifier. + * The `.gitignore` choice above the list is saved as soon as it changes, as + * the hidden-entry control in the search bar is. + * + * It floats over the navigator below the search field. The field that adds a + * directory stays above the list, which alone scrolls; a new rule goes to the + * top. The header's restore control appears while the list differs from the + * default list in any way, order included, and replaces it with that list. The close control, Escape, and focus leaving the panel request + * closure; focus moving to the magnifier leaves closure to its click. + */ +import { useId, useRef, useState } from 'react' +import type { ReactNode, RefObject } from 'react' +import clsx from 'clsx' +import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' +import { + IconCloseOutlineRegular, IconPlusOutlineRegular, IconRefreshOutlineRegular, IconTrashOutlineRegular, Tooltip, +} from '@deepseek-ai/dsh-client-ui-primitives' +import type {} from './locales.ts' +import { + addRule, defaultRules, isDefaultRules, removeRule, setRuleEnabled, type ExclusionRule, type RuleInvalidReason, +} from './search-rules.ts' +import css from './FilesBody.module.css' + +/** + * The settings panel. + * @param props.rules - the navigator's current draft. + * @param props.respectGitignore - whether the workspace's search leaves out entries `.gitignore` ignores. + * @param props.onRespectGitignore - saves a new `.gitignore` choice at once. + * @param props.trigger - the control that opens and closes the panel; focus moving to it leaves the closing to its click. + * @param props.onChange - replaces the draft without saving preferences. + * @param props.onClose - saves and closes the draft, returning focus to the trigger when requested. + * @param props.t - namespace-bound translate. + * @returns the panel. + */ +export function SearchSettings({ rules, respectGitignore, onRespectGitignore, trigger, onChange, onClose, t }: { + readonly rules: readonly ExclusionRule[] + readonly respectGitignore: boolean + readonly onRespectGitignore: (respectGitignore: boolean) => void + readonly trigger: RefObject + readonly onChange: (rules: readonly ExclusionRule[]) => void + readonly onClose: (refocus: boolean) => void + readonly t: TranslateNS<'sidebarFiles'> +}): ReactNode { + const [text, setText] = useState('') + const [invalid, setInvalid] = useState(undefined) + const add = useRef(null) + const title = useId() + const error = useId() + // A control that is about to disappear hands the keyboard to the add field first, so the panel keeps it. + const keepFocus = (): void => { add.current?.focus() } + return ( +
    { + if (event.key !== 'Escape' || event.nativeEvent.isComposing) return + // Kept from the navigator's own Escape and the overlay's close on the document. + event.preventDefault() + event.stopPropagation() + onClose(true) + }} + onBlur={(event) => { + const next = event.relatedTarget + if (next instanceof Node && (event.currentTarget.contains(next) || trigger.current?.contains(next) === true)) return + onClose(false) + }} + > +
    + {t('settings.title')} + {!isDefaultRules(rules) && ( + + + + )} + + + +
    +

    {t('settings.description')}

    +
    + +
    +
    + + { + setText(event.target.value) + setInvalid(undefined) + }} + onKeyDown={(event) => { + if (event.key !== 'Enter' || event.nativeEvent.isComposing) return + event.preventDefault() + const added = addRule(rules, text) + if (added.kind === 'invalid') { + setInvalid(added.reason) + return + } + onChange(added.rules) + setText('') + }} + /> +
    + {invalid !== undefined && } +
      + {rules.map(rule => ( +
    • + + + + +
    • + ))} +
    +
    + ) +} diff --git a/packages/client/ui-sidebar-files/src/client/face.ts b/packages/client/ui-sidebar-files/src/client/face.ts index 0957339723..3bdccb9337 100644 --- a/packages/client/ui-sidebar-files/src/client/face.ts +++ b/packages/client/ui-sidebar-files/src/client/face.ts @@ -1,11 +1,17 @@ /** * The navigator's half outside React. The injected face (`filesFace`) lists * directories into the store through its own actions, reveals the tab's file, - * carries scroll and keyboard focus between drawings of a pane's tree, and - * measures the navigator's row. The component never awaits or observes - * anything: it registers what it draws and calls the face. The per-pane - * lifetimes are stated on `attach` and `hold`. Beside the face live its - * inputs: the Remote listing and watch bindings and `canOpenOf`. + * carries scroll and keyboard focus between drawings of a pane's tree, runs + * each pane's search, and measures the navigator's row. The component never + * awaits or observes anything: it registers what it draws and calls the face. + * The per-pane lifetimes are stated on `attach` and `hold`. A search asks the + * Host whenever the query or the workspace's search preferences change; each + * pane runs one search at a time, a newer one aborting the older, whose answer + * is dropped. It writes its pending state and its result to the store, and the + * results keep a scroll offset apart from the tree's. The workspace's search + * preferences come from a book shared by every Session. Beside the face live + * its inputs: the Remote listing and watch bindings, and `canOpenOf`; the + * search's binding lives in `search-workspace.ts`. */ import type { ClientRemote, RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store' @@ -13,11 +19,15 @@ import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { SidebarRightTabDefinition, SidebarRightTabNavigation } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' import type { SessionId } from '@deepseek-ai/dsh-session/types' -import { childPath, locateFile, relativeFileOf, type DirLevel, type FilesStoreInstance } from './store.ts' +import { childPath, locateFile, relativeFileOf, type DirLevel, type FilesSearchResult, type FilesStoreInstance } from './store.ts' import type { WorkspaceFileWatchFrame } from '@deepseek-ai/dsh-api-workspace-files/types' import { RemoteError } from '@deepseek-ai/dsh-typert-protocol' import { DirectoryNode } from './directory-node.ts' import { FILL_BELOW, FULLSCREEN_QUERY } from './navigator-layout.ts' +import type { WorkspaceSearchPreferenceBook } from './search-preferences.ts' +import { enabledPaths, type WorkspaceSearchPreferences } from './search-rules.ts' +import type { SearchWorkspace } from './search-workspace.ts' +import { buildSearchTree } from './search-tree.ts' /** * The box an element is laid out in: its nearest ancestor that generates one, @@ -140,7 +150,11 @@ export interface FilesInjected { * @returns the release; the listing closes once no hold remains when the current task ends. */ readonly hold: (paneId: PaneId, root: string) => () => void - /** Refresh the open directory tree. @param paneId - owning pane. */ + /** + * Refresh the open directory tree, and run the pane's search again when it + * has a query, since its results are a snapshot of one search. + * @param paneId - owning pane. + */ readonly refresh: (paneId: PaneId) => void /** Control automatic rereads without closing watches. @param paneId - owning pane. @param enabled - automatic-refresh setting. */ readonly setAutoRefresh: (paneId: PaneId, enabled: boolean) => void @@ -153,7 +167,8 @@ export interface FilesInjected { */ readonly toggle: (paneId: PaneId, parentPath: string, path: string, expanded: readonly string[]) => void /** - * Record where a pane's tree is scrolled to, without rendering anything. + * Record where a pane's tree, or its search results while they are shown, + * is scrolled to, without rendering anything. * @param paneId - the pane being drawn. * @param scrollTop - the scroll offset in px. */ @@ -165,17 +180,61 @@ export interface FilesInjected { */ readonly hide: (paneId: PaneId) => void /** - * Show a pane's navigator and give its tree keyboard focus now, or when it - * is next drawn; a pane drawn but not yet attached shows it once attached. + * Show a pane's navigator and its search bar, and give the field keyboard focus now, + * or when it is next drawn; a pane drawn but not yet attached shows it once attached. + * Focusing the always-visible files page leaves the pane's preview-navigator show choice unchanged. * A pane with no drawing recorded is left alone. - * @param paneId - the pane whose tree takes focus. + * @param paneId - the pane whose search field takes focus. */ readonly focus: (paneId: PaneId) => void + /** + * Record an attached pane's search text. Text with more than whitespace + * searches the whole workspace with the workspace's current preferences, + * aborting the pane's running search and dropping its answer; while it holds + * such text, a change to those preferences searches again. Blank text ends + * the search, aborting a running one, and the pane draws its tree again. + * @param paneId - the pane being drawn. + * @param cwd - the Session's working directory, the search's root; fixed for the Session once known, so a + * result always shares the pane's tree root. + * @param query - the text as typed. + */ + readonly setQuery: (paneId: PaneId, cwd: string, query: string) => void + /** + * Open or collapse one directory of a pane's search results, leaving the tree's own expansion alone. + * @param paneId - the pane being drawn. + * @param path - absolute directory path. + */ + readonly toggleSearch: (paneId: PaneId, path: string) => void + /** + * Run an attached pane's search again with its current query and the + * workspace's current preferences, as after a failure; a pane without a + * query is left alone. + * @param paneId - the pane being drawn. + */ + readonly retrySearch: (paneId: PaneId) => void + /** + * Change the search preferences of a workspace for every Session and pane + * rooted there. Only the fields the patch names change; the others keep + * their value at the time of the call, not at the time the caller read them. + * @param cwd - the Session's working directory. + * @param patch - any of the exclusion rules, the hidden-entry choice, and the `.gitignore` choice. + */ + readonly setSearchPreferences: (cwd: string, patch: Partial) => void + /** + * Register the drawn search field, or with `null` as gone. Drawing takes + * keyboard focus that `focus` asked for, or that the previous drawing's + * field held when it went in the same task. + * @param paneId - the pane being drawn. + * @param input - the field, or `null` once it is removed. + */ + readonly searchDrawn: (paneId: PaneId, input: HTMLElement | null) => void /** * Register the tree's scroll container as drawn for one tab, or with `null` - * as gone. Drawing restores the pane's scroll offset, takes keyboard focus - * that the previous drawing held when it went or that `focus` asked for, and - * reveals the tab's file unless the pane revealed it last. + * as gone. Drawing restores the pane's scroll offset for what it shows — the + * tree, or the search results, each with its own offset — takes keyboard + * focus that the previous drawing held when it went, and reveals the tab's + * file in the tree unless the pane revealed it last. A drawing registers + * again when it switches between the tree and the results. * @param paneId - the pane being drawn. * @param address - the tab's content address. * @param body - the scroll container, or `null` once it is removed. @@ -216,6 +275,8 @@ export interface FilesInjected { readonly keyedHooks: { /** The measured width of the row a pane's navigator is laid out in, in CSS pixels, keyed by pane id; `undefined` until measured. */ readonly rowWidth: (paneId: string) => HostObservable + /** A workspace's search preferences, keyed by the Session's working directory; shared by every Session rooted there. */ + readonly searchPreferences: (cwd: string) => HostObservable } } @@ -264,6 +325,16 @@ interface PaneRecord { root: DirectoryNode | undefined /** Where the tree was last scrolled to, in px. */ scrollTop: number + /** Where the search results were last scrolled to, in px. */ + searchScrollTop: number + /** The trimmed query the pane's search asks for; empty while no search is shown. */ + searchQuery: string + /** The preferences the pane's search follows, while its query is not blank. */ + following: { readonly cwd: string; readonly stop: () => void } | undefined + /** The running search, whose answer the pane draws only while it is still this one. */ + searching: AbortController | undefined + /** The drawn search field. */ + input: HTMLElement | undefined /** The file whose row was revealed last, so a remount does not reveal it again. */ revealed: string | undefined /** The file whose row a reveal is walking to. */ @@ -274,8 +345,8 @@ interface PaneRecord { current: HTMLElement | undefined /** A completed reveal waits for its row to be drawn. */ scrollToCurrent: boolean - /** Who asked for keyboard focus at the tree's next drawing. */ - focus: object | undefined + /** Who asked for keyboard focus at the next drawing, and whether the tree or the search field takes it. */ + focus: { readonly target: 'tree' | 'search' } | undefined /** `focus` asked to show the navigator before the pane attached; attaching shows it. */ show: boolean /** The measured width of the row the navigator shares with the preview or the page's line. */ @@ -299,8 +370,8 @@ interface TabHome { readonly navigation: HostObservable } -/** `focus` asked for the tree's keyboard focus. */ -const REQUESTED = {} +/** `focus` asked for the search field's keyboard focus. */ +const REQUESTED = { target: 'search' } as const /** * Place a face beside a tab's content, where the workspace command finds it, @@ -312,11 +383,13 @@ const REQUESTED = {} export type PlaceFace = (tabId: TabId, face: FilesInjected) => () => void /** - * Bind the tree's face to one directory listing. + * Bind the tree's face to one directory listing and one workspace search. * @param list - the bound `workspaceFiles.list` call. * @param watch - target-scoped directory observation. * @param canOpen - whether some tab type can open an address. * @param navigationOf - the attached tab's navigation; subscriptions end with this plugin or their disposer. + * @param search - the workspace search. + * @param preferences - every workspace's search preferences, shared by every Session. * @returns the face factory: session, its store instance, and where to place the face beside tabs in, face out. */ export function filesFace( @@ -324,6 +397,8 @@ export function filesFace( watch: WatchWorkspaceDirectory, canOpen: HostObservable<(address: string) => boolean>, navigationOf: (sessionId: SessionId, tabId: TabId) => HostObservable, + search: SearchWorkspace, + preferences: WorkspaceSearchPreferenceBook, ): ( sessionId: SessionId, store: Pick, @@ -337,6 +412,7 @@ export function filesFace( if (pane === undefined) { pane = { lifetime: undefined, mounts: 0, tabs: new Set(), holds: 0, root: undefined, scrollTop: 0, + searchScrollTop: 0, searchQuery: '', following: undefined, searching: undefined, input: undefined, revealed: undefined, revealing: undefined, drawn: undefined, current: undefined, scrollToCurrent: false, focus: undefined, show: false, width: createSnapshotStore(undefined), @@ -353,6 +429,7 @@ export function filesFace( void pane.root?.close() pane.root = undefined pane.unobserve?.() + endSearch(pane) panes.delete(paneId) actions.forget(paneId) } @@ -425,8 +502,73 @@ export function filesFace( }) reveal() } + const resultsShown = (paneId: PaneId): boolean => store.getSnapshot().byPane[paneId]?.search !== undefined + const endSearch = (pane: PaneRecord): void => { + pane.searchQuery = '' + // The next search's results start at their top, even before its answer arrives. + pane.searchScrollTop = 0 + pane.following?.stop() + pane.following = undefined + pane.searching?.abort() + pane.searching = undefined + } + const runSearch = (paneId: PaneId, pane: PaneRecord, cwd: string): void => { + pane.searching?.abort() + const controller = new AbortController() + pane.searching = controller + const query = pane.searchQuery + const { rules, showHidden, respectGitignore } = preferences.source(cwd).getSnapshot() + const excludedPaths = enabledPaths(rules) + actions.searching(paneId) + const settle = (result: FilesSearchResult): void => { + // A newer search, the end of the search, or the pane's end replaced this one. + if (pane.searching !== controller) return + pane.searching = undefined + // New results start at their top; the tree drawn in their place keeps its offset. + pane.searchScrollTop = 0 + if (pane.drawn !== undefined) pane.drawn.body.scrollTop = 0 + actions.searched(paneId, result) + } + search(sessionId, { query, excludedPaths, includeHidden: showHidden, respectGitignore }, controller.signal).then((answer) => { + settle(answer.ok + ? { + kind: 'found', query, tree: buildSearchTree(cwd, answer.value.matches), count: answer.value.matches.length, + truncated: answer.value.truncated, incomplete: answer.value.incomplete, + hiddenLeftOut: !showHidden, excluded: excludedPaths.length > 0, ignored: respectGitignore, + } + : { kind: 'failed', query, failure: answer.error }) + }).catch((error: unknown) => { + // A Remote call rejects only on an assembly fault, and drawing the answer + // fails only on a defect; the pane reports either rather than wait forever. + settle({ kind: 'failed', query, failure: new RemoteError('gateway/internal', error instanceof Error ? error.message : String(error), {}) }) + }) + } + /** Run an attached pane's search again with its current query; a pane without a query is left alone. */ + const searchAgain = (paneId: PaneId): void => { + const pane = panes.get(paneId) + if (pane?.following === undefined) return + runSearch(paneId, pane, pane.following.cwd) + } + const follow = (paneId: PaneId, pane: PaneRecord, cwd: string): void => { + if (pane.following?.cwd === cwd) return + pane.following?.stop() + const source = preferences.source(cwd) + let seen = source.getSnapshot() + const stop = source.subscribe(() => { + const now = source.getSnapshot() + if (now === seen) return + seen = now + runSearch(paneId, pane, cwd) + }) + pane.following = { cwd, stop } + } + const focusInput = (pane: PaneRecord): void => { + pane.focus = undefined + // As for the tree: the dock's inert host lifts later in this commit. + queueMicrotask(() => { pane.input?.focus() }) + } const focusTree = (pane: PaneRecord): void => { - const handoff = {} + const handoff = { target: 'tree' } as const pane.focus = handoff // The dock keeps a newly shown tab's host inert until its own layout // effect, later in this drawing's commit, and the tab's body may draw the @@ -521,7 +663,8 @@ export function filesFace( pane.lifetime ??= new AbortController() if (pane.show) { pane.show = false - actions.shown(paneId, true) + if (pane.navigator === undefined || pane.closable) actions.shown(paneId, true) + else actions.searchBarShown(paneId, true) } pane.mounts += 1 let home = homes.get(tabId) @@ -571,7 +714,11 @@ export function filesFace( }) } }, - refresh: (paneId) => { void panes.get(paneId)?.root?.refreshTree() }, + refresh: (paneId) => { + const pane = panes.get(paneId) + void pane?.root?.refreshTree() + searchAgain(paneId) + }, setAutoRefresh: (paneId, enabled) => { actions.autoRefresh(paneId, enabled) panes.get(paneId)?.root?.setAutomatic(enabled) @@ -579,7 +726,9 @@ export function filesFace( toggle: (paneId, parentPath, path, expanded) => { expand(paneId, parentPath, path, expanded, true) }, scrolled: (paneId, scrollTop) => { const pane = panes.get(paneId) - if (pane?.lifetime !== undefined) pane.scrollTop = scrollTop + if (pane?.lifetime === undefined) return + if (resultsShown(paneId)) pane.searchScrollTop = scrollTop + else pane.scrollTop = scrollTop }, hide(paneId) { const pane = panes.get(paneId) @@ -600,9 +749,46 @@ export function filesFace( const pane = panes.get(paneId) if (pane === undefined) return if (pane.lifetime === undefined) pane.show = true - else actions.shown(paneId, true) - if (pane.drawn === undefined) pane.focus = REQUESTED - else focusTree(pane) + else { + if (pane.navigator === undefined || pane.closable) actions.shown(paneId, true) + else actions.searchBarShown(paneId, true) + } + if (pane.input === undefined) pane.focus = REQUESTED + else focusInput(pane) + }, + setQuery(paneId, cwd, query) { + const pane = panes.get(paneId) + if (pane?.lifetime === undefined) return + actions.queried(paneId, query) + const trimmed = query.trim() + if (trimmed === '') { + endSearch(pane) + return + } + // Whitespace around the text does not change what the search matches. + if (pane.searchQuery === trimmed && pane.following?.cwd === cwd) return + pane.searchQuery = trimmed + follow(paneId, pane, cwd) + runSearch(paneId, pane, cwd) + }, + toggleSearch: (paneId, path) => { actions.searchToggled(paneId, path) }, + retrySearch: searchAgain, + setSearchPreferences: (cwd, patch) => { preferences.update(cwd, patch) }, + searchDrawn(paneId, input) { + if (input === null) { + const pane = panes.get(paneId) + if (pane === undefined) return + const gone = pane.input + pane.input = undefined + if (gone === undefined || gone.ownerDocument.activeElement !== gone) return + const handoff = { target: 'search' } as const + pane.focus = handoff + queueMicrotask(() => { if (pane.focus === handoff) pane.focus = undefined }) + return + } + const pane = record(paneId) + pane.input = input + if (pane.focus?.target === 'search') focusInput(pane) }, bodyDrawn(paneId, address, body) { if (body === null) { @@ -616,15 +802,15 @@ export function filesFace( drop(paneId) if (gone?.contains(gone.ownerDocument.activeElement) !== true) return // Only a drawing in the same commit, the next tab's, takes the keyboard over. - const handoff = {} + const handoff = { target: 'tree' } as const pane.focus = handoff queueMicrotask(() => { if (pane.focus === handoff) pane.focus = undefined }) return } const pane = record(paneId) pane.drawn = { body, address } - body.scrollTop = pane.scrollTop - if (pane.focus !== undefined) focusTree(pane) + body.scrollTop = resultsShown(paneId) ? pane.searchScrollTop : pane.scrollTop + if (pane.focus?.target === 'tree') focusTree(pane) pane.revealing = pane.revealed === address ? undefined : address step(paneId, pane) }, @@ -762,7 +948,7 @@ export function filesFace( drop(paneId) }, hooks: { canOpen }, - keyedHooks: { rowWidth: paneId => record(paneId as PaneId).width }, + keyedHooks: { rowWidth: paneId => record(paneId as PaneId).width, searchPreferences: cwd => preferences.source(cwd) }, } return face } diff --git a/packages/client/ui-sidebar-files/src/client/index.ts b/packages/client/ui-sidebar-files/src/client/index.ts index 050f59caae..95acbdde1b 100644 --- a/packages/client/ui-sidebar-files/src/client/index.ts +++ b/packages/client/ui-sidebar-files/src/client/index.ts @@ -3,7 +3,9 @@ import type {} from '@deepseek-ai/dsh-client-ui-context-menu/client' * Browser half: register `files` as a right-Sidebar tab type, and the * workspace navigator beside every file preview. The navigator, the page body, * and the toggle share one store and one face per store instance. The package - * README lists the registrations. + * README lists the registrations. Search lives in `search-workspace.ts`, which + * binds the Host's workspace search, `search-rules.ts`, `search-tree.ts`, + * `search-preferences.ts`, and `SearchSettings.tsx`. */ import type { ShortcutCommandId } from '@deepseek-ai/dsh-client-shortcuts/client' import type { Context as ClientContext } from '@deepseek-ai/cordis' @@ -11,22 +13,27 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client' import type {} from '@deepseek-ai/dsh-client-ui-renderer/client' import type {} from '@deepseek-ai/dsh-client-ui-session/client' import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' -import type { BoundActions } from '@deepseek-ai/dsh-client-store' +import { createSnapshotStore, type BoundActions } from '@deepseek-ai/dsh-client-store' import type { TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { SessionId } from '@deepseek-ai/dsh-session/types' import { FILES_ID, FILES_KIND, filesDefinition } from './definition.tsx' import { canOpenOf, createList, createWatch, filesFace, type FilesInjected } from './face.ts' +import { createSearch } from './search-workspace.ts' import { FileTree } from './FileTree.tsx' import { FileNavigator } from './FileNavigator.tsx' import { FilesBody } from './FilesBody.tsx' import { FilesTitle } from './FilesTitle.tsx' import { en, ja, es, fr, de, ru, pt, zh } from './locales.ts' import { NavigatorToggle } from './NavigatorToggle.tsx' +import { createSearchPreferenceBook, SEARCH_PREFERENCES_KEY } from './search-preferences.ts' import { createFilesStore } from './store.ts' export type { SidebarFilesKey } from './locales.ts' -export type { DirLevel, FilesPaneState, FilesState, FilesTreeState, LevelState } from './store.ts' +export type { DirLevel, FilesPaneState, FilesSearchResult, FilesSearchState, FilesState, FilesTreeState, LevelState } from './store.ts' export type { FilesInjected, ListWorkspaceDirectory, WorkspaceFilesListRemote } from './face.ts' +export type { SearchWorkspace, WorkspaceFilesSearchRemote, WorkspaceSearchAnswer, WorkspaceSearchRequest } from './search-workspace.ts' +export type { SearchMatch } from './search-tree.ts' +export type { ExclusionRule, WorkspaceSearchPreferences } from './search-rules.ts' export type { FilesBodyProps } from './FilesBody.tsx' // Also keeps the Factory declaration in this entry's emitted types, which an `import type {}` would not. export type { TreeEntry, TreeEntryMeta, TreeEntryKind, TreeDirectoryState, FileTreeInput } from './FileTree.tsx' @@ -65,6 +72,8 @@ export const inject = ['slots', 'locale', 'sidebarRightTabs', 'sidebarRight', 'r export function apply(ctx: ClientContext): void { const t = ctx.locale.bind(NS) const handle = createFilesStore() + // One book for the plugin, not per Session: Sessions rooted at the same workspace share its preferences. + const preferences = createSearchPreferenceBook(createSnapshotStore({}, { persist: { name: SEARCH_PREFERENCES_KEY } })) const face = filesFace(createList(ctx.remote), createWatch(ctx.remote), canOpenOf(ctx.sidebarRightTabs), (sessionId, tabId) => { const source = ctx.sidebarRight.tabDomain.occurrence(sessionId, { id: tabId }).navigation return { @@ -78,7 +87,7 @@ export function apply(ctx: ClientContext): void { return () => { active = false; unsubscribe() } }, 'ui-sidebar-files: tab navigation'), } - }) + }, createSearch(ctx.remote), preferences) // A Factory runs its inject per occurrence, so each store instance gets its // one face when it is minted. The shortcut, which acts outside any body, finds // the face placed beside the target tab; a tab's loading and loaded drawings @@ -136,7 +145,8 @@ export function apply(ctx: ClientContext): void { if (target === undefined) return { status: 'blocked', reason: t('shortcut.noSession') } /* jscpd:ignore-end */ return { status: 'handled', run: () => { - // A docked tab with a navigator beside its content that can draw a tree keeps it: the navigator is shown and takes the keyboard. + // A docked tab with a navigator beside its content that can draw a tree keeps it: + // the navigator is shown and its search field takes the keyboard. const placed = target.tabId === undefined ? undefined : beside.get(target.sessionId)?.get(target.tabId) if (target.host === 'dock' && placed !== undefined) { if (!ctx.sidebarRight.isExpanded()) ctx.sidebarRight.toggleExpanded() diff --git a/packages/client/ui-sidebar-files/src/client/locales.ts b/packages/client/ui-sidebar-files/src/client/locales.ts index 065d408e65..968d61ead9 100644 --- a/packages/client/ui-sidebar-files/src/client/locales.ts +++ b/packages/client/ui-sidebar-files/src/client/locales.ts @@ -26,6 +26,7 @@ export const zh = { 'guide.description': '浏览会话工作区的文件', loading: '正在读取…', empty: '空目录', + emptyHidden: '隐藏项未显示', truncated: '条目太多,只显示了一部分。', noWorkspace: '这个会话没有工作区目录。', reload: '重新读取', @@ -41,6 +42,37 @@ export const zh = { 'error.outsideWorkspace': '这个目录在工作区之外,侧栏不会读取它。', 'error.notDirectory': '这不是一个目录。', 'error.unavailable': '读取失败:{message}', + 'search.placeholder': '搜索文件', + 'search.settings': '搜索设置', + 'search.clear': '清空搜索', + 'search.showHidden': '显示隐藏项', + 'search.results': '{count} 个结果', + 'search.empty': '没有匹配项', + 'search.emptyHint.hidden': '隐藏项不会显示。', + 'search.emptyHint.excluded': '排除的文件和目录不会显示。', + 'search.emptyHint.both': '隐藏项以及排除的文件和目录不会显示。', + 'search.emptyHint.ignored': '被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.hiddenIgnored': '隐藏项,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.excludedIgnored': '排除的文件和目录,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.all': '隐藏项、排除的文件和目录,以及被忽略文件(如 .gitignore)忽略的文件和目录不会显示。', + 'search.emptyHint.label': '为什么没有匹配项', + 'search.truncated': '只显示前 {count} 个结果,请缩小搜索范围。', + 'search.incomplete': '文件数超过搜索上限,或部分目录未能读取,因此结果可能不完整。', + 'search.failed': '搜索失败:{message}', + 'search.retry': '重试', + 'settings.title': '排除的文件和目录', + 'settings.description': '只影响搜索结果,不影响文件树。', + 'settings.respectGitignore': '尊重忽略文件(.gitignore 等)', + 'settings.add': '添加文件或目录', + 'settings.close': '关闭', + 'settings.restore': '还原默认列表', + 'settings.remove': '删除 {path}', + 'settings.toggle': '排除 {path}', + 'settings.invalid.empty': '请输入名称或相对路径。', + 'settings.invalid.nul': '路径不能包含 NUL 字符。', + 'settings.invalid.absolute': '请使用相对于工作区的路径。', + 'settings.invalid.parent': '路径不能包含 . 或 .. 段。', + 'settings.invalid.glob': '路径不能包含通配符 * ? [ ] { } !。', } satisfies Record /** Files dictionary key union. */ @@ -54,6 +86,7 @@ export const en = { 'guide.description': 'Browse files in this session\'s workspace', loading: 'Reading…', empty: 'Empty directory', + emptyHidden: 'Hidden entries are not shown', truncated: 'Too many entries, showing only some of them.', noWorkspace: 'This session has no workspace directory.', reload: 'Reload', @@ -69,6 +102,37 @@ export const en = { 'error.outsideWorkspace': 'That directory is outside the workspace, so the sidebar will not read it.', 'error.notDirectory': 'That is not a directory.', 'error.unavailable': 'Read failed: {message}', + 'search.placeholder': 'Search files', + 'search.settings': 'Search settings', + 'search.clear': 'Clear search', + 'search.showHidden': 'Show hidden entries', + 'search.results': 'Results: {count}', + 'search.empty': 'No matches', + 'search.emptyHint.hidden': 'Hidden entries are not shown.', + 'search.emptyHint.excluded': 'Excluded files and directories are not shown.', + 'search.emptyHint.both': 'Hidden entries and excluded files and directories are not shown.', + 'search.emptyHint.ignored': 'Files and directories ignored by ignore files such as .gitignore are not shown.', + 'search.emptyHint.hiddenIgnored': 'Hidden entries, and files and directories ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.excludedIgnored': 'Excluded files and directories, and those ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.all': 'Hidden entries, excluded files and directories, and those ignored by ignore files such as .gitignore, are not shown.', + 'search.emptyHint.label': 'Why there are no matches', + 'search.truncated': 'Showing only the first {count} results. Narrow the search to see the rest.', + 'search.incomplete': 'The search passed its file limit, or some directories could not be read, so results may be incomplete.', + 'search.failed': 'Search failed: {message}', + 'search.retry': 'Retry', + 'settings.title': 'Excluded files and directories', + 'settings.description': 'Only affects search results, not the file tree.', + 'settings.respectGitignore': 'Respect ignore files (.gitignore, etc.)', + 'settings.add': 'Add file or directory', + 'settings.close': 'Close', + 'settings.restore': 'Restore default list', + 'settings.remove': 'Remove {path}', + 'settings.toggle': 'Exclude {path}', + 'settings.invalid.empty': 'Enter a name or relative path.', + 'settings.invalid.nul': 'The path cannot contain a NUL character.', + 'settings.invalid.absolute': 'Use a path relative to the workspace.', + 'settings.invalid.parent': 'The path cannot contain . or .. segments.', + 'settings.invalid.glob': 'The path cannot contain wildcards * ? [ ] { } !.', } satisfies Record /** Japanese copy, checked against the English keys. */ @@ -79,6 +143,7 @@ export const ja = { 'guide.description': 'このセッションのワークスペース内のファイルを参照', 'loading': '読み取り中…', 'empty': '空のディレクトリ', + 'emptyHidden': '隠し項目は表示されていません', 'truncated': 'エントリが多すぎるため、一部のみ表示しています。', 'noWorkspace': 'このセッションにはワークスペースディレクトリがありません。', 'reload': '再読み込み', @@ -94,6 +159,37 @@ export const ja = { 'error.outsideWorkspace': 'そのディレクトリはワークスペース外のため、サイドバーでは読み取りません。', 'error.notDirectory': 'それはディレクトリではありません。', 'error.unavailable': '読み取りに失敗しました: {message}', + 'search.placeholder': 'ファイルを検索', + 'search.settings': '検索設定', + 'search.clear': '検索をクリア', + 'search.showHidden': '隠し項目を表示', + 'search.results': '結果: {count} 件', + 'search.empty': '一致する項目はありません', + 'search.emptyHint.hidden': '隠し項目は表示されません。', + 'search.emptyHint.excluded': '除外したファイルとディレクトリは表示されません。', + 'search.emptyHint.both': '隠し項目と、除外したファイルとディレクトリは表示されません。', + 'search.emptyHint.ignored': '.gitignore などの無視ファイルで無視されたファイルとディレクトリは表示されません。', + 'search.emptyHint.hiddenIgnored': '隠し項目と、.gitignore などの無視ファイルで無視されたファイルとディレクトリは表示されません。', + 'search.emptyHint.excludedIgnored': '除外したファイルとディレクトリ、および .gitignore などの無視ファイルで無視された項目は表示されません。', + 'search.emptyHint.all': '隠し項目、除外したファイルとディレクトリ、および .gitignore などの無視ファイルで無視された項目は表示されません。', + 'search.emptyHint.label': '一致する項目がない理由', + 'search.truncated': '最初の {count} 件のみ表示しています。検索範囲を絞り込んでください。', + 'search.incomplete': 'ファイル数が検索上限を超えたか、一部のディレクトリを読み取れなかったため、結果が不完全な可能性があります。', + 'search.failed': '検索に失敗しました: {message}', + 'search.retry': '再試行', + 'settings.title': '除外するファイルとディレクトリ', + 'settings.description': '検索結果にのみ適用され、ファイルツリーには影響しません。', + 'settings.respectGitignore': '無視ファイル(.gitignore など)に従う', + 'settings.add': 'ファイルまたはディレクトリを追加', + 'settings.close': '閉じる', + 'settings.restore': '既定のリストに戻す', + 'settings.remove': '{path} を削除', + 'settings.toggle': '{path} を除外', + 'settings.invalid.empty': '名前または相対パスを入力してください。', + 'settings.invalid.nul': 'パスに NUL 文字は使用できません。', + 'settings.invalid.absolute': 'ワークスペースからの相対パスを使用してください。', + 'settings.invalid.parent': 'パスに . や .. のセグメントは使用できません。', + 'settings.invalid.glob': 'パスにワイルドカード * ? [ ] { } ! は使用できません。', } satisfies Record /** Spanish dictionary, checked against the English keys. */ @@ -103,10 +199,11 @@ export const es = { 'guide.title': 'Archivos de espacio de trabajo', 'guide.description': 'Explorar archivos en el espacio de trabajo de esta sesión', loading: 'Leyendo…', - empty: 'directorio vacio', + empty: 'Directorio vacío', + emptyHidden: 'Las entradas ocultas no se muestran', truncated: 'Demasiadas entradas y solo se muestran algunas de ellas.', noWorkspace: 'Esta sesión no tiene ningún directorio de espacio de trabajo.', - reload: 'recargar', + reload: 'Recargar', autoRefresh: 'Actualización automática', 'autoRefresh.enable': 'Habilitar actualización automática', 'autoRefresh.disable': 'Deshabilitar la actualización automática', @@ -119,6 +216,37 @@ export const es = { 'error.outsideWorkspace': 'Ese directorio está fuera del espacio de trabajo, por lo que la barra lateral no lo leerá.', 'error.notDirectory': 'Eso no es un directorio.', 'error.unavailable': 'Error de lectura: {message}', + 'search.placeholder': 'Buscar archivos', + 'search.settings': 'Configuración de búsqueda', + 'search.clear': 'Borrar búsqueda', + 'search.showHidden': 'Mostrar entradas ocultas', + 'search.results': 'Resultados: {count}', + 'search.empty': 'Sin coincidencias', + 'search.emptyHint.hidden': 'No se muestran las entradas ocultas.', + 'search.emptyHint.excluded': 'No se muestran los archivos ni los directorios excluidos.', + 'search.emptyHint.both': 'No se muestran las entradas ocultas ni los archivos y directorios excluidos.', + 'search.emptyHint.ignored': 'No se muestran los archivos ni los directorios que ignoran los archivos de exclusión como .gitignore.', + 'search.emptyHint.hiddenIgnored': 'No se muestran las entradas ocultas ni los archivos y directorios que ignoran los archivos de exclusión como .gitignore.', + 'search.emptyHint.excludedIgnored': 'No se muestran los archivos ni los directorios excluidos o ignorados por archivos de exclusión como .gitignore.', + 'search.emptyHint.all': 'No se muestran las entradas ocultas, los archivos y directorios excluidos ni los ignorados por archivos de exclusión como .gitignore.', + 'search.emptyHint.label': 'Por qué no hay coincidencias', + 'search.truncated': 'Solo se muestran los primeros {count} resultados. Acote la búsqueda para ver el resto.', + 'search.incomplete': 'La búsqueda superó su límite de archivos o no se pudieron leer algunos directorios, por lo que los resultados pueden estar incompletos.', + 'search.failed': 'Error de búsqueda: {message}', + 'search.retry': 'Reintentar', + 'settings.title': 'Archivos y directorios excluidos', + 'settings.description': 'Solo afecta a los resultados de búsqueda, no al árbol de archivos.', + 'settings.respectGitignore': 'Respetar archivos de exclusión (.gitignore, etc.)', + 'settings.add': 'Añadir archivo o directorio', + 'settings.close': 'Cerrar', + 'settings.restore': 'Restaurar la lista predeterminada', + 'settings.remove': 'Eliminar {path}', + 'settings.toggle': 'Excluir {path}', + 'settings.invalid.empty': 'Introduzca un nombre o una ruta relativa.', + 'settings.invalid.nul': 'La ruta no puede contener el carácter NUL.', + 'settings.invalid.absolute': 'Use una ruta relativa al espacio de trabajo.', + 'settings.invalid.parent': 'La ruta no puede contener segmentos «.» ni «..».', + 'settings.invalid.glob': 'La ruta no puede contener comodines * ? [ ] { } !.', } satisfies Record /** French dictionary, checked against the English keys. */ @@ -129,6 +257,7 @@ export const fr = { 'guide.description': "Parcourir les fichiers dans l'espace de travail de cette session", loading: 'Lecture…', empty: 'Répertoire vide', + emptyHidden: 'Les entrées masquées ne sont pas affichées', truncated: "Trop d'entrées, n'en affichant que certaines.", noWorkspace: "Cette session n'a pas de répertoire d'espace de travail.", reload: 'Recharger', @@ -144,6 +273,37 @@ export const fr = { 'error.outsideWorkspace': 'Ce répertoire se trouve en dehors de l’espace de travail, donc la barre latérale ne le lira pas.', 'error.notDirectory': "Ce n'est pas un répertoire.", 'error.unavailable': 'Échec de lecture : {message}', + 'search.placeholder': 'Rechercher des fichiers', + 'search.settings': 'Paramètres de recherche', + 'search.clear': 'Effacer la recherche', + 'search.showHidden': 'Afficher les entrées masquées', + 'search.results': 'Résultats : {count}', + 'search.empty': 'Aucune correspondance', + 'search.emptyHint.hidden': 'Les entrées masquées ne sont pas affichées.', + 'search.emptyHint.excluded': 'Les fichiers et répertoires exclus ne sont pas affichés.', + 'search.emptyHint.both': 'Les entrées masquées et les fichiers et répertoires exclus ne sont pas affichés.', + 'search.emptyHint.ignored': 'Les fichiers et répertoires ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.hiddenIgnored': 'Les entrées masquées et les fichiers et répertoires ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.excludedIgnored': 'Les fichiers et répertoires exclus ou ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.all': 'Les entrées masquées, les fichiers et répertoires exclus et ceux ignorés par des fichiers d’exclusion comme .gitignore ne sont pas affichés.', + 'search.emptyHint.label': 'Pourquoi aucune correspondance', + 'search.truncated': 'Seuls les {count} premiers résultats sont affichés. Affinez la recherche pour voir les autres.', + 'search.incomplete': 'La recherche a dépassé sa limite de fichiers, ou certains répertoires n’ont pas pu être lus, les résultats peuvent donc être incomplets.', + 'search.failed': 'Échec de la recherche : {message}', + 'search.retry': 'Réessayer', + 'settings.title': 'Fichiers et répertoires exclus', + 'settings.description': 'Concerne uniquement les résultats de recherche, pas l’arborescence des fichiers.', + 'settings.respectGitignore': 'Respecter les fichiers d’exclusion (.gitignore, etc.)', + 'settings.add': 'Ajouter un fichier ou un répertoire', + 'settings.close': 'Fermer', + 'settings.restore': 'Restaurer la liste par défaut', + 'settings.remove': 'Supprimer {path}', + 'settings.toggle': 'Exclure {path}', + 'settings.invalid.empty': 'Saisissez un nom ou un chemin relatif.', + 'settings.invalid.nul': 'Le chemin ne peut pas contenir de caractère NUL.', + 'settings.invalid.absolute': 'Utilisez un chemin relatif à l’espace de travail.', + 'settings.invalid.parent': 'Le chemin ne peut pas contenir de segments « . » ou « .. ».', + 'settings.invalid.glob': 'Le chemin ne peut pas contenir les caractères génériques * ? [ ] { } !.', } satisfies Record /** German dictionary, checked against the English keys. */ @@ -154,6 +314,7 @@ export const de = { 'guide.description': 'Durchsuchen Sie die Dateien im Arbeitsbereich dieser Sitzung', loading: 'Lesen…', empty: 'Leeres Verzeichnis', + emptyHidden: 'Versteckte Einträge werden nicht angezeigt', truncated: 'Zu viele Einträge, es werden nur einige davon angezeigt.', noWorkspace: 'Diese Sitzung hat kein Arbeitsbereichsverzeichnis.', reload: 'Neu laden', @@ -169,6 +330,37 @@ export const de = { 'error.outsideWorkspace': 'Dieses Verzeichnis liegt außerhalb des Arbeitsbereichs und wird daher von der Seitenleiste nicht gelesen.', 'error.notDirectory': 'Das ist kein Verzeichnis.', 'error.unavailable': 'Lesen fehlgeschlagen: {message}', + 'search.placeholder': 'Dateien suchen', + 'search.settings': 'Sucheinstellungen', + 'search.clear': 'Suche löschen', + 'search.showHidden': 'Versteckte Einträge anzeigen', + 'search.results': 'Ergebnisse: {count}', + 'search.empty': 'Keine Treffer', + 'search.emptyHint.hidden': 'Versteckte Einträge werden nicht angezeigt.', + 'search.emptyHint.excluded': 'Ausgeschlossene Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.both': 'Versteckte Einträge sowie ausgeschlossene Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.ignored': 'Von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.hiddenIgnored': 'Versteckte Einträge sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.excludedIgnored': 'Ausgeschlossene sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.all': 'Versteckte Einträge, ausgeschlossene sowie von Ignore-Dateien wie .gitignore ignorierte Dateien und Verzeichnisse werden nicht angezeigt.', + 'search.emptyHint.label': 'Warum es keine Treffer gibt', + 'search.truncated': 'Nur die ersten {count} Ergebnisse werden angezeigt. Grenzen Sie die Suche ein, um weitere zu sehen.', + 'search.incomplete': 'Die Suche hat ihr Dateilimit überschritten oder einige Verzeichnisse konnten nicht gelesen werden, daher sind die Ergebnisse möglicherweise unvollständig.', + 'search.failed': 'Suche fehlgeschlagen: {message}', + 'search.retry': 'Erneut versuchen', + 'settings.title': 'Ausgeschlossene Dateien und Verzeichnisse', + 'settings.description': 'Wirkt sich nur auf Suchergebnisse aus, nicht auf den Dateibaum.', + 'settings.respectGitignore': 'Ignore-Dateien beachten (.gitignore usw.)', + 'settings.add': 'Datei oder Verzeichnis hinzufügen', + 'settings.close': 'Schließen', + 'settings.restore': 'Standardliste wiederherstellen', + 'settings.remove': '{path} entfernen', + 'settings.toggle': '{path} ausschließen', + 'settings.invalid.empty': 'Geben Sie einen Namen oder relativen Pfad ein.', + 'settings.invalid.nul': 'Der Pfad darf kein NUL-Zeichen enthalten.', + 'settings.invalid.absolute': 'Verwenden Sie einen Pfad relativ zum Arbeitsbereich.', + 'settings.invalid.parent': 'Der Pfad darf keine Segmente . oder .. enthalten.', + 'settings.invalid.glob': 'Der Pfad darf keine Platzhalter * ? [ ] { } ! enthalten.', } satisfies Record /** Russian dictionary, checked against the English keys. */ @@ -179,6 +371,7 @@ export const ru = { 'guide.description': 'Просмотр файлов в рабочей области этого сеанса', loading: 'Чтение…', empty: 'Пустой каталог', + emptyHidden: 'Скрытые записи не показаны', truncated: 'Слишком много записей, показаны только некоторые из них.', noWorkspace: 'В этом сеансе нет каталога рабочей области.', reload: 'Перезагрузить', @@ -194,6 +387,37 @@ export const ru = { 'error.outsideWorkspace': 'Этот каталог находится за пределами рабочей области, поэтому боковая панель его не читает.', 'error.notDirectory': 'Это не каталог.', 'error.unavailable': 'Не удалось прочитать: {message}.', + 'search.placeholder': 'Поиск файлов', + 'search.settings': 'Настройки поиска', + 'search.clear': 'Очистить поиск', + 'search.showHidden': 'Показывать скрытые записи', + 'search.results': 'Результаты: {count}', + 'search.empty': 'Совпадений нет', + 'search.emptyHint.hidden': 'Скрытые записи не показываются.', + 'search.emptyHint.excluded': 'Исключённые файлы и каталоги не показываются.', + 'search.emptyHint.both': 'Скрытые записи, а также исключённые файлы и каталоги не показываются.', + 'search.emptyHint.ignored': 'Файлы и каталоги, игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.hiddenIgnored': 'Скрытые записи, а также файлы и каталоги, игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.excludedIgnored': 'Исключённые файлы и каталоги, а также игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.all': 'Скрытые записи, исключённые файлы и каталоги, а также игнорируемые файлами исключений (например, .gitignore), не показываются.', + 'search.emptyHint.label': 'Почему нет совпадений', + 'search.truncated': 'Показаны только первые {count} результатов. Уточните запрос, чтобы увидеть остальные.', + 'search.incomplete': 'Поиск превысил лимит файлов или часть каталогов не удалось прочитать, поэтому результаты могут быть неполными.', + 'search.failed': 'Не удалось выполнить поиск: {message}', + 'search.retry': 'Повторить', + 'settings.title': 'Исключённые файлы и каталоги', + 'settings.description': 'Влияет только на результаты поиска, не на дерево файлов.', + 'settings.respectGitignore': 'Учитывать файлы исключений (.gitignore и др.)', + 'settings.add': 'Добавить файл или каталог', + 'settings.close': 'Закрыть', + 'settings.restore': 'Восстановить список по умолчанию', + 'settings.remove': 'Удалить {path}', + 'settings.toggle': 'Исключить {path}', + 'settings.invalid.empty': 'Введите имя или относительный путь.', + 'settings.invalid.nul': 'Путь не может содержать символ NUL.', + 'settings.invalid.absolute': 'Укажите путь относительно рабочей области.', + 'settings.invalid.parent': 'Путь не может содержать сегменты «.» или «..».', + 'settings.invalid.glob': 'Путь не может содержать подстановочные знаки * ? [ ] { } !.', } satisfies Record /** Portuguese dictionary, checked against the English keys. */ @@ -204,6 +428,7 @@ export const pt = { 'guide.description': 'Procure arquivos no espaço de trabalho desta sessão', loading: 'Lendo…', empty: 'Diretório vazio', + emptyHidden: 'Entradas ocultas não são mostradas', truncated: 'Muitas entradas, mostrando apenas algumas delas.', noWorkspace: 'Esta sessão não possui diretório de espaço de trabalho.', reload: 'Recarregar', @@ -219,4 +444,35 @@ export const pt = { 'error.outsideWorkspace': 'Esse diretório está fora da área de trabalho, portanto a barra lateral não o lerá.', 'error.notDirectory': 'Isso não é um diretório.', 'error.unavailable': 'Falha na leitura: {message}', + 'search.placeholder': 'Pesquisar arquivos', + 'search.settings': 'Configurações de pesquisa', + 'search.clear': 'Limpar pesquisa', + 'search.showHidden': 'Mostrar entradas ocultas', + 'search.results': 'Resultados: {count}', + 'search.empty': 'Nenhuma correspondência', + 'search.emptyHint.hidden': 'Entradas ocultas não são mostradas.', + 'search.emptyHint.excluded': 'Arquivos e diretórios excluídos não são mostrados.', + 'search.emptyHint.both': 'Entradas ocultas e arquivos e diretórios excluídos não são mostrados.', + 'search.emptyHint.ignored': 'Arquivos e diretórios ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.hiddenIgnored': 'Entradas ocultas e arquivos e diretórios ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.excludedIgnored': 'Arquivos e diretórios excluídos ou ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.all': 'Entradas ocultas, arquivos e diretórios excluídos e os ignorados por arquivos de exclusão como .gitignore não são mostrados.', + 'search.emptyHint.label': 'Por que não há correspondências', + 'search.truncated': 'Mostrando apenas os primeiros {count} resultados. Refine a pesquisa para ver o restante.', + 'search.incomplete': 'A pesquisa ultrapassou seu limite de arquivos ou alguns diretórios não puderam ser lidos, então os resultados podem estar incompletos.', + 'search.failed': 'Falha na pesquisa: {message}', + 'search.retry': 'Tentar novamente', + 'settings.title': 'Arquivos e diretórios excluídos', + 'settings.description': 'Afeta apenas os resultados da pesquisa, não a árvore de arquivos.', + 'settings.respectGitignore': 'Respeitar arquivos de exclusão (.gitignore etc.)', + 'settings.add': 'Adicionar arquivo ou diretório', + 'settings.close': 'Fechar', + 'settings.restore': 'Restaurar a lista padrão', + 'settings.remove': 'Remover {path}', + 'settings.toggle': 'Excluir {path}', + 'settings.invalid.empty': 'Digite um nome ou um caminho relativo.', + 'settings.invalid.nul': 'O caminho não pode conter o caractere NUL.', + 'settings.invalid.absolute': 'Use um caminho relativo ao espaço de trabalho.', + 'settings.invalid.parent': 'O caminho não pode conter segmentos “.” ou “..”.', + 'settings.invalid.glob': 'O caminho não pode conter curingas * ? [ ] { } !.', } satisfies Record diff --git a/packages/client/ui-sidebar-files/src/client/search-preferences.ts b/packages/client/ui-sidebar-files/src/client/search-preferences.ts new file mode 100644 index 0000000000..6afb25a0e0 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-preferences.ts @@ -0,0 +1,116 @@ +/** + * The search preferences of every workspace, kept in browser storage and + * shared by every Session and pane whose workspace root is the same. + * + * The storage value maps a normalized workspace root to the fields the reader + * changed there. A field equal to its default is left out of the entry, a root + * the reader never changed has no entry, and a change back to the defaults + * removes its entry, so the defaults of a later build reach every field the + * reader left alone. Storage + * holds whatever an earlier build or the reader wrote: each entry is read + * through {@link readSearchPreferences} rather than trusted. + */ +import type { SnapshotStore } from '@deepseek-ai/dsh-client-store' +import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots' +import { + changedSearchPreferences, defaultSearchPreferences, readSearchPreferences, type WorkspaceSearchPreferences, +} from './search-rules.ts' + +/** + * The localStorage key the preferences of every workspace are stored under. + * + * Each entry holds whichever of `rules`, `showHidden`, and `respectGitignore` + * differ from their defaults. Every field is optional on read: + * {@link readSearchPreferences} gives a missing or mistyped one its current + * default and reads the others as usual. A change that an earlier build would + * misread takes a new key. + */ +export const SEARCH_PREFERENCES_KEY = 'dsh.sidebar-files.workspace-search.v1' + +/** + * The storage key of one workspace root: the root as the Host reports it, with + * trailing `/` and `\` removed except the one that makes a filesystem root + * (`/`, `C:\`, `C:/`). Case and separators are otherwise kept, so two + * spellings of one directory keep separate preferences. + * @param cwd - the Session's working directory. + * @returns the key its preferences are stored under. + */ +export function workspaceKey(cwd: string): string { + const trimmed = cwd.replace(/[/\\]+$/, '') + if (trimmed === '') return cwd.slice(0, 1) + if (/^[A-Za-z]:$/.test(trimmed) && cwd.length > trimmed.length) return cwd.slice(0, 3) + return trimmed +} + +/** + * One stored entry, without trusting the stored value's type. + * @param stored - the storage value, as rehydrated. + * @param key - a workspace key. + * @returns the entry's value, or `undefined` when the value is not an object or has no such entry. + */ +function storedEntry(stored: unknown, key: string): unknown { + if (typeof stored !== 'object' || stored === null || Array.isArray(stored) || !Object.hasOwn(stored, key)) return undefined + return Object.getOwnPropertyDescriptor(stored, key)?.value +} + +/** The search preferences of every workspace root. */ +export interface WorkspaceSearchPreferenceBook { + /** + * Observe one root's preferences. The same root, by its {@link workspaceKey}, + * gets the same source, and its snapshot keeps its reference until that + * root's preferences change. + * @param cwd - the Session's working directory. + * @returns the source. + */ + readonly source: (cwd: string) => HostObservable + /** + * Change the reader's choice for one root: the fields the patch names + * replace those of the root's current preferences, read at the call; the + * entry keeps only the fields that differ from the defaults, and is removed + * when none does. + * @param cwd - the Session's working directory. + * @param patch - any of the exclusion rules, the hidden-entry choice, and the `.gitignore` choice. + */ + readonly update: (cwd: string, patch: Partial) => void +} + +/** + * Keep the preferences of every workspace root in one persisted store. + * @param store - the persisted store; its rehydrated value may be anything JSON can hold. + * @returns the preferences by workspace root. + */ +export function createSearchPreferenceBook(store: SnapshotStore): WorkspaceSearchPreferenceBook { + const sources = new Map>() + const source = (cwd: string): HostObservable => { + const key = workspaceKey(cwd) + const known = sources.get(key) + if (known !== undefined) return known + let seen: { readonly raw: unknown; readonly preferences: WorkspaceSearchPreferences } | undefined + const created: HostObservable = { + getSnapshot: () => { + const raw = storedEntry(store.getSnapshot(), key) + if (seen === undefined || seen.raw !== raw) { + seen = { raw, preferences: raw === undefined ? defaultSearchPreferences() : readSearchPreferences(raw) } + } + return seen.preferences + }, + subscribe: listener => store.subscribe(listener), + } + sources.set(key, created) + return created + } + return { + source, + update(cwd, patch) { + const preferences = { ...source(cwd).getSnapshot(), ...patch } + const key = workspaceKey(cwd) + const stored = store.getSnapshot() + const entries = typeof stored === 'object' && stored !== null && !Array.isArray(stored) + ? Object.entries(stored).filter(([name]) => name !== key) + : [] + const changed = changedSearchPreferences(preferences) + if (changed !== undefined) entries.push([key, changed]) + store.set(Object.fromEntries(entries)) + }, + } +} diff --git a/packages/client/ui-sidebar-files/src/client/search-rules.ts b/packages/client/ui-sidebar-files/src/client/search-rules.ts new file mode 100644 index 0000000000..6751a7a3bc --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-rules.ts @@ -0,0 +1,233 @@ +/** + * Search exclusion rules and the search preferences that carry them. + * + * A rule names files and directories the workspace search leaves out, by name + * or by path. A path without `/` is a name and matches every file or directory + * of that name at any depth; a path with `/` is relative to the workspace root + * and matches that one file or directory. An excluded directory's contents are + * left out with it. This module keeps the editable list, checks what the + * reader types, and reads the list back from a stored value; the Host's + * workspace search applies the rules. + * + * The list records no origin: a default path the reader removed and then + * added again by hand counts as a default that is present. + */ + +/** One exclusion rule as the settings list shows and stores it. */ +export interface ExclusionRule { + /** Normalized name or `/`-separated workspace-relative path of a file or directory. */ + readonly path: string + /** Whether the search leaves this path out now. */ + readonly enabled: boolean +} + +/** Why a typed rule path was refused; each reason has its own `settings.invalid.*` line. */ +export type RuleInvalidReason = 'empty' | 'nul' | 'absolute' | 'parent' | 'glob' + +/** A typed rule path after normalization, or why it was refused. */ +export type RulePathResult = + | { readonly kind: 'ok'; readonly path: string } + | { readonly kind: 'invalid'; readonly reason: RuleInvalidReason } + +/** The search panel's persisted choices. */ +export interface WorkspaceSearchPreferences { + /** Exclusion rules, newest first. */ + readonly rules: readonly ExclusionRule[] + /** Whether results include hidden entries. */ + readonly showHidden: boolean + /** Whether the search leaves out entries the workspace's `.gitignore` files ignore. */ + readonly respectGitignore: boolean +} + +/** + * Names excluded until the reader changes the list, in the order a restore + * lists them: version-control, package-manager, and build output directories, + * then the metadata files and directories macOS and Windows write into folders + * and volumes. + */ +const DEFAULT_EXCLUDED_PATHS: readonly string[] = [ + '.git', '.hg', '.next', '.pnpm-store', '.svn', '.turbo', '.yarn', 'build', 'coverage', 'dist', 'node_modules', + '.DS_Store', '.Spotlight-V100', '.Trashes', '.fseventsd', 'Thumbs.db', 'desktop.ini', '$RECYCLE.BIN', 'System Volume Information', +] + +/** Characters that would make a literal path read as a pattern. */ +const GLOB = /[*?[\]{}!]/ + +/** + * Normalize a typed rule path: trim it, turn `\` into `/`, merge repeated + * `/`, and drop leading `./`, trailing `/`, and whitespace exposed at either + * edge. Internal whitespace stays unchanged. + * + * Refuses an empty path, one containing NUL, an absolute one (leading `/`, a + * drive letter such as `C:`, or `~`, including prefixes exposed by dropping + * leading `./` and whitespace), one with a `.` or `..` segment, and one + * containing a glob character (`* ? [ ] { } !`). Other characters, such as + * `$` and spaces, are kept literally. + * @param input - the text the reader typed. + * @returns the normalized path, unchanged by normalization again, or why it was refused. + */ +export function normalizeRulePath(input: string): RulePathResult { + const slashed = input.trim().replace(/\\/g, '/') + if (slashed === '') return { kind: 'invalid', reason: 'empty' } + if (slashed.includes('\0')) return { kind: 'invalid', reason: 'nul' } + const relative = slashed.replace(/\/{2,}/g, '/').replace(/^(?:\s|\.\/)+/, '') + if (slashed.startsWith('/') || /^(?:\/|~|[A-Za-z]:)/.test(relative)) return { kind: 'invalid', reason: 'absolute' } + // Anchor the suffix scan at the start so long internal whitespace is not scanned repeatedly. + const path = relative.replace(/^(.*[^\s/])?[\s/]*$/s, '$1') + if (GLOB.test(path)) return { kind: 'invalid', reason: 'glob' } + if (path === '') return { kind: 'invalid', reason: 'empty' } + if (path.split('/').some(segment => segment === '.' || segment === '..')) return { kind: 'invalid', reason: 'parent' } + return { kind: 'ok', path } +} + +/** + * The default rule list, every rule enabled. + * @returns a new list in default order. + */ +export function defaultRules(): ExclusionRule[] { + return DEFAULT_EXCLUDED_PATHS.map(path => ({ path, enabled: true })) +} + +/** + * The preferences before the reader changes anything. + * @returns the default rules, hidden entries not shown, and `.gitignore` respected. + */ +export function defaultSearchPreferences(): WorkspaceSearchPreferences { + return { rules: defaultRules(), showHidden: false, respectGitignore: true } +} + +/** + * Add a typed rule at the top of the list, enabled. + * + * A rule whose normalized path is already listed, enabled or not, is enabled + * and moved to the top instead of being listed twice. Paths compare exactly. + * @param rules - the current list. + * @param input - the text the reader typed. + * @returns the new list, or why the text was refused. + */ +export function addRule( + rules: readonly ExclusionRule[], + input: string, +): { readonly kind: 'ok'; readonly rules: readonly ExclusionRule[] } | { readonly kind: 'invalid'; readonly reason: RuleInvalidReason } { + const normalized = normalizeRulePath(input) + if (normalized.kind === 'invalid') return normalized + const { path } = normalized + return { kind: 'ok', rules: [{ path, enabled: true }, ...rules.filter(rule => rule.path !== path)] } +} + +/** + * Remove one rule. + * @param rules - the current list. + * @param path - the rule's normalized path. + * @returns the list without it; an unlisted path leaves the list as it was. + */ +export function removeRule(rules: readonly ExclusionRule[], path: string): readonly ExclusionRule[] { + return rules.filter(rule => rule.path !== path) +} + +/** + * Enable or disable one rule in place. + * @param rules - the current list. + * @param path - the rule's normalized path. + * @param enabled - whether the search leaves the path out. + * @returns the list with that rule changed; an unlisted path leaves the list as it was. + */ +export function setRuleEnabled(rules: readonly ExclusionRule[], path: string, enabled: boolean): readonly ExclusionRule[] { + return rules.map(rule => rule.path === path && rule.enabled !== enabled ? { path, enabled } : rule) +} + +/** + * The paths the search leaves out. + * @param rules - the current list. + * @returns the enabled rules' paths, in list order. + */ +export function enabledPaths(rules: readonly ExclusionRule[]): string[] { + return rules.filter(rule => rule.enabled).map(rule => rule.path) +} + +/** + * Whether a rule list equals the default list: the same paths in the same + * order, every rule enabled. + * @param rules - the current list. + * @returns `true` when nothing differs from {@link defaultRules}. + */ +export function isDefaultRules(rules: readonly ExclusionRule[]): boolean { + return rules.length === DEFAULT_EXCLUDED_PATHS.length + && rules.every((rule, index) => rule.path === DEFAULT_EXCLUDED_PATHS[index] && rule.enabled) +} + +/** + * Read preferences back from a value browser storage holds, which any earlier + * build or the reader may have written, after its JSON text was parsed. + * + * Each field is read on its own: a missing or mistyped `rules` array, + * `showHidden`, or `respectGitignore` takes the current default, so an entry + * that stores only the fields the reader changed keeps the defaults of the + * running build for the rest. A value that is not an object gives the + * defaults. Inside a `rules` array, a rule that is not an object with a string + * `path` and a boolean `enabled`, or whose path `normalizeRulePath` refuses, + * is dropped; a rule whose normalized path repeats an earlier one is dropped + * too. A stored empty list stays empty. + * @param value - the parsed stored value. + * @returns the preferences to use. + */ +export function readSearchPreferences(value: unknown): WorkspaceSearchPreferences { + const defaults = defaultSearchPreferences() + if (typeof value !== 'object' || value === null || Array.isArray(value)) return defaults + const field = (name: string): unknown => Object.hasOwn(value, name) ? Object.getOwnPropertyDescriptor(value, name)?.value : undefined + const rules = field('rules') + const showHidden = field('showHidden') + const respectGitignore = field('respectGitignore') + return { + rules: Array.isArray(rules) ? readRules(rules) : defaults.rules, + showHidden: typeof showHidden === 'boolean' ? showHidden : defaults.showHidden, + respectGitignore: typeof respectGitignore === 'boolean' ? respectGitignore : defaults.respectGitignore, + } +} + +/** + * The well-formed rules of a stored list, normalized, in stored order. + * @param rules - the stored list. + * @returns the rules to use. + */ +function readRules(rules: readonly unknown[]): ExclusionRule[] { + const parsed: ExclusionRule[] = [] + for (const rule of rules) { + if (typeof rule !== 'object' || rule === null || !('path' in rule) || !('enabled' in rule)) continue + const { path, enabled } = rule + if (typeof path !== 'string' || typeof enabled !== 'boolean') continue + const normalized = normalizeRulePath(path) + if (normalized.kind === 'invalid' || parsed.some(kept => kept.path === normalized.path)) continue + parsed.push({ path: normalized.path, enabled }) + } + return parsed +} + +/** + * The fields of preferences that differ from the defaults, as browser storage + * keeps them: a field equal to its default is left out, so a later build's + * default reaches it. + * @param preferences - the preferences to store. + * @returns the differing fields, or `undefined` when nothing differs from {@link defaultSearchPreferences}. + */ +export function changedSearchPreferences(preferences: WorkspaceSearchPreferences): Partial | undefined { + const defaults = defaultSearchPreferences() + const changed: { -readonly [K in keyof WorkspaceSearchPreferences]?: WorkspaceSearchPreferences[K] } = {} + if (!isDefaultRules(preferences.rules)) changed.rules = preferences.rules.map(rule => ({ path: rule.path, enabled: rule.enabled })) + if (preferences.showHidden !== defaults.showHidden) changed.showHidden = preferences.showHidden + if (preferences.respectGitignore !== defaults.respectGitignore) changed.respectGitignore = preferences.respectGitignore + return Object.keys(changed).length === 0 ? undefined : changed +} + +/** + * Whether the tree treats an entry as hidden: its name starts with `.`. The + * Host's search judges names the same way, except on a Windows Host, where + * ripgrep also treats an entry with the hidden file attribute as hidden. The + * tree lists names one level at a time under the workspace root, so a name is + * judged on its own. + * @param entry - a listed entry. + * @returns `true` for a hidden entry. + */ +export function isHiddenEntry(entry: { readonly name: string }): boolean { + return entry.name.startsWith('.') +} diff --git a/packages/client/ui-sidebar-files/src/client/search-tree.ts b/packages/client/ui-sidebar-files/src/client/search-tree.ts new file mode 100644 index 0000000000..06b51dafe2 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-tree.ts @@ -0,0 +1,74 @@ +/** + * The search results drawn as a tree, and the highlights in its names. + * + * A search answers with the workspace-relative paths of its matches, and not + * necessarily with their ancestors. The tree the navigator draws + * needs every level from the root down, so this module synthesizes the levels + * the results pass through, keyed by absolute path as the listed tree keys them. + */ +import { childPath } from './store.ts' +import type { DirLevel, FilesTreeState } from './store.ts' + +/** One entry a search matched. */ +export interface SearchMatch { + /** `/`-separated path relative to the workspace root, without leading or trailing `/`. */ + readonly path: string + /** Whether the entry is a file, a directory, or something else. */ + readonly type: DirLevel['entries'][number]['type'] +} + +/** + * Draw search results as a fully expanded tree. + * + * Every directory the results pass through gets a ready level: the root, each + * result's ancestors, and each result that is itself a directory. A level lists + * the children the results put there, once each, in first-seen order; a name + * that is an ancestor anywhere is a directory. A directory that matched but + * holds no matching descendant has a level with no entries, which the + * navigator draws differently from an empty listed directory. Every level is + * expanded, no level is truncated, and the tree does not refresh itself. + * @param root - absolute path of the workspace root, as `FilesTreeState.root` holds it. + * @param entries - the search's entries. + * @returns the tree to draw. + */ +export function buildSearchTree(root: string, entries: readonly SearchMatch[]): FilesTreeState { + type Names = Map + const children = new Map([[root, new Map()]]) + const directory = (path: string): Names => { + const names = children.get(path) ?? new Map() + children.set(path, names) + return names + } + for (const entry of entries) { + const parts = entry.path.split('/') + let parent = root + for (const [index, name] of parts.entries()) { + const type = index === parts.length - 1 ? entry.type : 'directory' + const names = directory(parent) + if (type === 'directory' || !names.has(name)) names.set(name, type) + parent = childPath(parent, name) + if (type === 'directory') directory(parent) + } + } + const levels: FilesTreeState['levels'] = {} + for (const [path, names] of children) { + const level: DirLevel = { entries: [...names].map(([name, type]) => ({ name, type })), truncated: false } + levels[path] = { kind: 'ready', level } + } + return { autoRefresh: false, root, levels, expanded: [...children.keys()] } +} + +/** + * Where the query occurs in one name, for highlighting. + * + * Matching ignores case by Unicode simple case folding; the ranges index the + * name as given. An empty query has no occurrence. + * @param name - the drawn name. + * @param query - the search text. + * @returns non-overlapping `[start, end)` UTF-16 ranges, left to right. + */ +export function matchRanges(name: string, query: string): readonly (readonly [number, number])[] { + if (query === '') return [] + const pattern = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu') + return [...name.matchAll(pattern)].map(match => [match.index, match.index + match[0].length] as const) +} diff --git a/packages/client/ui-sidebar-files/src/client/search-workspace.ts b/packages/client/ui-sidebar-files/src/client/search-workspace.ts new file mode 100644 index 0000000000..a3f90efa93 --- /dev/null +++ b/packages/client/ui-sidebar-files/src/client/search-workspace.ts @@ -0,0 +1,67 @@ +/** + * The workspace search, bound to the Host's `workspaceFiles.search` call. + * + * The Host walks the whole workspace of the Session and applies the query, + * the exclusion rules, the hidden-entry choice, and `.gitignore`; the Client + * only draws the matches it returns. + */ +import type { ClientRemote, RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import type { SearchMatch } from './search-tree.ts' + +/** What one search asks the Host for. */ +export interface WorkspaceSearchRequest { + /** The query without surrounding whitespace; never empty. */ + readonly query: string + /** The paths of the enabled exclusion rules, in list order, as `search-rules.ts` defines them. */ + readonly excludedPaths: readonly string[] + /** Whether hidden entries may match: names starting with `.`, and on a Windows Host also entries with the hidden file attribute. */ + readonly includeHidden: boolean + /** Whether entries the workspace's `.gitignore` files ignore are left out. */ + readonly respectGitignore: boolean +} + +/** One settled search's matches. */ +export interface WorkspaceSearchAnswer { + /** The matches, in the Host's order. */ + readonly matches: readonly SearchMatch[] + /** The Host returned only its first matches because more matched than it returns. */ + readonly truncated: boolean + /** + * Part of the workspace was not searched: the Host's search passed its file + * limit, or a directory could not be read. + */ + readonly incomplete: boolean +} + +/** + * One workspace search. The session travels with the call because the Host + * resolves the workspace root from it. A failure settles the result's error + * branch; aborting `signal` lets the caller drop the answer. + * @param sessionId - Session whose workspace is searched. + * @param request - the query and the preferences it follows. + * @param signal - the search's lifetime; the face aborts it when a newer search or the end of the search replaces it. + * @returns the matches, or why the Host could not search. + */ +export type SearchWorkspace = ( + sessionId: SessionId, + request: WorkspaceSearchRequest, + signal: AbortSignal, +) => Promise> + +/** + * The slice of the Client Remote face the search calls: the `workspaceFiles` + * namespace's `search`, exactly as the Host's generated client declares it. + */ +export type WorkspaceFilesSearchRemote = { + readonly workspaceFiles: Pick +} + +/** + * Bind the workspace search to one Remote face. + * @param remote - the Client Remote face carrying the `workspaceFiles` namespace. + * @returns the search the tree's face performs. + */ +export function createSearch(remote: WorkspaceFilesSearchRemote): SearchWorkspace { + return (sessionId, request, signal) => remote.workspaceFiles.search(sessionId, request, signal) +} diff --git a/packages/client/ui-sidebar-files/src/client/store.ts b/packages/client/ui-sidebar-files/src/client/store.ts index 182a142208..0019d90636 100644 --- a/packages/client/ui-sidebar-files/src/client/store.ts +++ b/packages/client/ui-sidebar-files/src/client/store.ts @@ -1,11 +1,12 @@ /** * The file tree's view state, one record per right-Sidebar pane: which - * directories are expanded, what each loaded level contains, and how the - * navigator is shown. A Slot-standard exclusive store (one instance per - * Session) keyed by pane, so every file tab of a pane draws the same tree; - * the face decides when a pane's record is forgotten (`FilesInjected.attach`). - * Beside it live pure reads shared by the face and the drawings: path keys, - * where a tab's file sits in the listed tree, and the navigator's geometry. + * directories are expanded, what each loaded level contains, how the + * navigator is shown, and the pane's search. A Slot-standard exclusive store + * (one instance per Session) keyed by pane, so every file tab of a pane draws + * the same tree; the face decides when a pane's record is forgotten + * (`FilesInjected.attach`). Beside it live pure reads shared by the face and + * the drawings: path keys, where a tab's file sits in the listed tree, and the + * navigator's geometry. */ import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store' import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' @@ -98,7 +99,50 @@ export interface FilesTreeState { expanded: string[] } -/** One pane's navigator: whether and how wide it is shown, and its tree once started. */ +/** + * One settled search, as the pane draws it instead of the tree: the matches, + * or why the Host could not search. + */ +export type FilesSearchResult = + | { + readonly kind: 'found' + /** The trimmed query the search answered, which the rows highlight. */ + readonly query: string + /** The matches as a tree; its `expanded` is the search's own and starts with every level. */ + readonly tree: FilesTreeState + /** How many entries the search returned. */ + readonly count: number + /** More entries matched than the Host returns, so only its first `count` are drawn. */ + readonly truncated: boolean + /** + * Part of the workspace was not searched: the Host's search passed its file + * limit, or a directory could not be read. + */ + readonly incomplete: boolean + /** Whether the search was asked to leave out hidden entries; it does not say that any were. */ + readonly hiddenLeftOut: boolean + /** Whether the search was given at least one enabled exclusion rule; it does not say that a rule matched. */ + readonly excluded: boolean + /** Whether the search was asked to respect ignore files; it does not say that one ignored anything. */ + readonly ignored: boolean + } + | { + readonly kind: 'failed' + /** The trimmed query the failed search asked for. */ + readonly query: string + /** Why the Host could not search. */ + readonly failure: RemoteFailure + } + +/** One pane's search while its query is not blank. */ +export interface FilesSearchState { + /** A search is running; the last settled result stays drawn until its answer replaces it. */ + readonly pending: boolean + /** The last settled search; `undefined` until the pane's first search settles. */ + readonly result: FilesSearchResult | undefined +} + +/** One pane's navigator: whether and how wide it is shown, its tree once started, and its search. */ export interface FilesPaneState { /** * Whether a preview's navigator is shown; `undefined`, hidden, until the @@ -109,6 +153,12 @@ export interface FilesPaneState { width: number /** The tree, listed once the navigator is first shown. */ tree: FilesTreeState | undefined + /** The search field's text, as typed; not persisted. */ + query: string + /** Whether the files page draws its search bar; hiding it retains the query and results. */ + searchBarOpen: boolean + /** The pane's search, which the navigator draws instead of the tree; `undefined` while the query is blank. */ + search: FilesSearchState | undefined } /** Every pane's navigator, keyed by pane id. */ @@ -216,7 +266,7 @@ function underRoot(path: string, root: string): string | undefined { * @returns the pane's record. */ function pane(state: FilesState, paneId: PaneId): FilesPaneState { - state.byPane[paneId] ??= { open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, tree: undefined } + state.byPane[paneId] ??= { open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, tree: undefined, query: '', searchBarOpen: false, search: undefined } return state.byPane[paneId] } @@ -242,8 +292,13 @@ type FilesActions = { failed: (draft: FilesState, paneId: PaneId, path: string, failure: RemoteFailure) => void toggled: (draft: FilesState, paneId: PaneId, path: string) => void shown: (draft: FilesState, paneId: PaneId, open: boolean) => void + searchBarShown: (draft: FilesState, paneId: PaneId, open: boolean) => void resized: (draft: FilesState, paneId: PaneId, width: number) => void forget: (draft: FilesState, paneId: PaneId) => void + queried: (draft: FilesState, paneId: PaneId, query: string) => void + searching: (draft: FilesState, paneId: PaneId) => void + searched: (draft: FilesState, paneId: PaneId, result: FilesSearchResult) => void + searchToggled: (draft: FilesState, paneId: PaneId, path: string) => void } /** @@ -344,6 +399,13 @@ export function createFilesStore(): EngineStoreHandle * @param open - whether the navigator is shown. */ shown: (d, paneId: PaneId, open: boolean) => { pane(d, paneId).open = open }, + /** + * Show or hide the files page's search bar without changing its search. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param open - whether the search bar is shown. + */ + searchBarShown: (d, paneId: PaneId, open: boolean) => { pane(d, paneId).searchBarOpen = open }, /** * Record one pane's navigator width preference. * @param d - draft state. @@ -359,6 +421,55 @@ export function createFilesStore(): EngineStoreHandle forget: (d, paneId: PaneId) => { d.byPane = Object.fromEntries(Object.entries(d.byPane).filter(([id]) => id !== paneId)) }, + /** + * Record the search field's text. A blank query ends the search, and the + * pane draws its tree again; otherwise the last result stays drawn until + * the next is recorded. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param query - the text as typed. + */ + queried: (d, paneId: PaneId, query: string) => { + const state = pane(d, paneId) + state.query = query + if (query.trim() === '') state.search = undefined + }, + /** + * Record that a search started, keeping the last result drawn; ignored while the query is blank. + * @param d - draft state. + * @param paneId - the pane being drawn. + */ + searching: (d, paneId: PaneId) => { + const state = d.byPane[paneId] + const result = state?.search?.result + if (state !== undefined && state.query.trim() !== '') { + state.search = { pending: true, result: result?.kind === 'failed' ? undefined : result } + } + }, + /** + * Record a search's result, ending the pending search; ignored while the query is blank. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param result - what the search found, or why it failed. + */ + searched: (d, paneId: PaneId, result: FilesSearchResult) => { + const state = d.byPane[paneId] + if (state !== undefined && state.query.trim() !== '') state.search = { pending: false, result } + }, + /** + * Open a collapsed directory of the search's tree, or collapse an open + * one; the listed tree's expansion stays as it was. + * @param d - draft state. + * @param paneId - the pane being drawn. + * @param path - absolute directory path. + */ + searchToggled: (d, paneId: PaneId, path: string) => { + const result = d.byPane[paneId]?.search?.result + if (result?.kind !== 'found') return + const at = result.tree.expanded.indexOf(path) + if (at >= 0) result.tree.expanded.splice(at, 1) + else result.tree.expanded.push(path) + }, }, }) } diff --git a/packages/client/ui-sidebar-files/src/client/workspace-tree.ts b/packages/client/ui-sidebar-files/src/client/workspace-tree.ts index 80eb21ae98..fe43fe1286 100644 --- a/packages/client/ui-sidebar-files/src/client/workspace-tree.ts +++ b/packages/client/ui-sidebar-files/src/client/workspace-tree.ts @@ -8,12 +8,17 @@ * key drops its trailing separators too, so `/` becomes the empty key and a * Windows drive root `C:\` becomes `C:`, and a top-level child's key still * ends at its parent's last `/`. + * + * Unless the reader shows them, hidden entries are left out, and a directory + * whose every entry is hidden says so. The same conversion draws a search's + * results, whose directories hold only the matches. */ import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import type { TreeDirectoryState, TreeEntry } from './FileTree.tsx' import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots' import type {} from './locales.ts' -import { childPath, type FilesTreeState } from './store.ts' +import { isHiddenEntry } from './search-rules.ts' +import { childPath, type DirLevel, type FilesTreeState } from './store.ts' /** * Say why a directory could not be listed, in terms of the directory. @@ -52,27 +57,48 @@ export function parentOf(tree: FilesTreeState, path: string): string { return parent === treeRootOf(tree.root) ? tree.root : parent } +/** + * A listing's entries as drawn. + * @param level - one ready listing. + * @param showHidden - whether hidden entries are drawn. + * @returns the entries, without hidden ones unless they are shown. + */ +function drawnEntries(level: DirLevel, showHidden: boolean): DirLevel['entries'] { + return showHidden ? level.entries : level.entries.filter(entry => !isHiddenEntry(entry)) +} + /** * Every listed entry of a pane's tree, collapsed levels included, each named - * as its listing spells it. + * as its listing spells it. Unless hidden entries are drawn, the kept levels + * below a hidden directory are left out with it, so a directory listed while + * hidden entries were shown is not drawn again through its descendants. * @param levels - the pane's level states. + * @param showHidden - whether hidden entries are drawn. * @returns the entries keyed as the tree draws them. */ -export function workspaceEntries(levels: FilesTreeState['levels']): TreeEntry[] { - return Object.entries(levels).flatMap(([path, level]) => level.kind !== 'ready' ? [] : level.level.entries - .map(entry => ({ path: childPath(path, entry.name), name: entry.name, meta: { kind: entry.type } }))) +export function workspaceEntries(levels: FilesTreeState['levels'], showHidden: boolean): TreeEntry[] { + const ready = Object.entries(levels).flatMap(([path, level]) => level.kind === 'ready' ? [{ path, level: level.level }] : []) + const hiddenPrefixes = showHidden ? [] : ready.flatMap(({ path, level }) => level.entries + .filter(entry => entry.type === 'directory' && isHiddenEntry(entry)).map(entry => childPath(childPath(path, entry.name), ''))) + return ready + .filter(({ path }) => !hiddenPrefixes.some(prefix => `${path}/`.startsWith(prefix))) + .flatMap(({ path, level }) => drawnEntries(level, showHidden) + .map(entry => ({ path: childPath(path, entry.name), name: entry.name, meta: { kind: entry.type } }))) } /** * Each directory's listing state: loading until its first listing settles, then - * its latest failure and whether its listing is truncated. + * its latest failure, whether its listing is truncated, and whether it holds + * only hidden entries that are not drawn. * @param tree - the pane's root, level states, and expanded directories. * @param t - namespace-bound translate, for failure lines. + * @param showHidden - whether hidden entries are drawn. * @returns the states keyed as the tree draws them. */ export function workspaceDirectories( tree: Pick, t: TranslateNS<'sidebarFiles'>, + showHidden: boolean, ): Record { const { root, levels, expanded } = tree const directories: Record = {} @@ -83,11 +109,23 @@ export function workspaceDirectories( if (level.kind === 'loading') directories[key] = { loading: true } else if (level.kind === 'failed') directories[key] = { failure: failureLine(t, level.failure) } else { - const state: { failure?: string; truncated?: true } = {} + const state: { failure?: string; truncated?: true; omitted?: 'hidden' } = {} if (level.failure !== undefined) state.failure = failureLine(t, level.failure) if (level.level.truncated) state.truncated = true + if (level.level.entries.length > 0 && drawnEntries(level.level, showHidden).length === 0) state.omitted = 'hidden' directories[key] = state } } return directories } + +/** + * Each directory of a search's results, which holds only the matches below it, + * so a matched directory without matched descendants draws no empty line. + * @param tree - the results as a tree. + * @returns the states keyed as the tree draws them. + */ +export function searchDirectories(tree: Pick): Record { + return Object.fromEntries(Object.keys(tree.levels) + .map(path => [path === tree.root ? treeRootOf(path) : path, { omitted: 'unmatched' } as const])) +} diff --git a/packages/client/ui-sidebar-files/tests/face.client.spec.ts b/packages/client/ui-sidebar-files/tests/face.client.spec.ts index 8502a8d348..15542328af 100644 --- a/packages/client/ui-sidebar-files/tests/face.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/face.client.spec.ts @@ -10,6 +10,7 @@ import { childPath } from '../src/client/store.ts' import { createFilesStore } from '../src/client/store.ts' import type { DirLevel } from '../src/client/store.ts' import { DirectoryNode } from '../src/client/directory-node.ts' +import { memoryBook, scriptedSearch } from './search-fixture.client.ts' import { scriptedList } from './scripted-list.client.ts' import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' @@ -29,7 +30,7 @@ function mount() { const script = scriptedList() /** The tabs the face placed itself beside, with each placement's release. */ const placed: { readonly tabId: TabId; readonly face: FilesInjected; readonly release: Mock<() => void> }[] = [] - const face = filesFace(script.list, script.watch, CAN_OPEN, () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }))(SESSION, instance, (tabId, bound) => { + const face = filesFace(script.list, script.watch, CAN_OPEN, () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }), scriptedSearch().search, memoryBook())(SESSION, instance, (tabId, bound) => { const release = vi.fn<() => void>() placed.push({ tabId, face: bound, release }) return release @@ -228,11 +229,15 @@ describe('filesFace', () => { onTestFinished(() => { tab.abort() }) face.attach(moved, 'tab-moved' as TabId, tab.signal) expect(instance.getSnapshot().byPane[moved]?.open).toBe(true) - // The tree drawn there next takes the keyboard. + expect(instance.getSnapshot().byPane[moved]?.searchBarOpen).toBe(false) + // The search field drawn there next takes the keyboard, not the tree. const body = { scrollTop: 0, focus: vi.fn() } face.bodyDrawn(moved, `${ROOT}/a.ts`, body as Partial as HTMLElement) + const input = { focus: vi.fn() } + face.searchDrawn(moved, input as Partial as HTMLInputElement) await Promise.resolve() - expect(body.focus).toHaveBeenCalledTimes(1) + expect(body.focus).not.toHaveBeenCalled() + expect(input.focus).toHaveBeenCalledTimes(1) face.hide('pane-never' as PaneId) expect(instance.getSnapshot().byPane['pane-never' as PaneId]).toBeUndefined() }) diff --git a/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx b/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx index aaebe5e72b..c812f9a287 100644 --- a/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx @@ -288,3 +288,26 @@ describe('FileTree', () => { expect(currentRef).toHaveBeenLastCalledWith(null) }) }) + +describe('caller-narrowed entries', () => { + it('highlights each occurrence of the given text in a name, ignoring case', () => { + const { view } = draw({ entries: CHANGES, expanded: ['pr/src'], highlight: 'FILE' }) + const marks = [...view.container.querySelectorAll('mark')].map(mark => mark.textContent) + expect(marks).toEqual(['file', 'file']) + expect(row(view.container, 'pr/src/file2.ts').textContent).toBe('file2.ts') + expect(row(view.container, 'pr/README.md').querySelector('mark')).toBeNull() + }) + + it('says a directory left without entries holds hidden ones, or nothing for a selection', () => { + const entries: readonly TreeEntry[] = [ + { path: 'pr/hidden', name: 'hidden', meta: { kind: 'directory' } }, + { path: 'pr/unmatched', name: 'unmatched', meta: { kind: 'directory' } }, + ] + const { view } = draw({ + entries, expanded: ['pr/hidden', 'pr/unmatched'], + directories: { 'pr/hidden': { omitted: 'hidden' }, 'pr/unmatched': { omitted: 'unmatched' } }, + }) + const notes = [...view.container.querySelectorAll('[data-files-row]')].map(note => [note.getAttribute('data-files-row'), note.textContent]) + expect(notes).toEqual([['hidden-only', en.emptyHidden]]) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx b/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx index ddb3dd2dfa..a8ef76a271 100644 --- a/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/files-body.client.spec.tsx @@ -6,9 +6,11 @@ import { makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime import type { RemoteFailure } from '@deepseek-ai/dsh-api-remotes/client' import { fileAddressFor } from '@deepseek-ai/dsh-util-workspace-path' import { failureLine } from '../src/client/workspace-tree.ts' +import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' import type { DirLevel } from '../src/client/store.ts' import { zh } from '../src/client/locales.ts' -import { mountBody, PANE, ROOT, SESSION } from './mount.client.tsx' +import { mountBody, PANE, ROOT, SESSION, TAB } from './mount.client.tsx' +import { answer, searchesSettled } from './search-fixture.client.ts' const ROOT_LEVEL: DirLevel = { entries: [ @@ -52,7 +54,7 @@ describe('FilesBody', () => { const header = page.firstElementChild! expect(header.querySelector('[data-files-path]')?.getAttribute('title')).toBe(ROOT) expect([...header.querySelectorAll('button:not([data-files-auto-refresh])')].map(button => button.getAttribute('aria-label'))) - .toEqual([zh.reload]) + .toEqual([zh.reload, zh['search.placeholder']]) const content = page.querySelector('[data-files-content]')! expect(content.children).toHaveLength(1) const navigator = content.firstElementChild! @@ -71,7 +73,122 @@ describe('FilesBody', () => { expect(typeof bound?.refresh).toBe('function') }) - it('lists the root on mount, heads it with its path split at the last segment, and draws directories first with dotfiles kept', async () => { + it('defers a files-page focus request until its pane attaches without changing the preview-tree choice', () => { + const h = mountBody() + const paneId = 'pane-before-attach' as PaneId + const navigator = document.createElement('aside') + h.view.container.append(navigator) + const controller = new AbortController() + onTestFinished(() => { controller.abort() }) + h.face.navigatorDrawn(paneId, navigator, false) + h.face.focus(paneId) + expect(h.instance.getSnapshot().byPane[paneId]).toBeUndefined() + h.face.attach(paneId, 'tab-before-attach' as TabId, controller.signal) + expect(h.instance.getSnapshot().byPane[paneId]).toMatchObject({ open: undefined, searchBarOpen: true }) + h.face.navigatorDrawn(paneId, null, false) + navigator.remove() + }) + + it('starts with the search bar collapsed and retains the query and results through collapse and remount', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(h.beside(TAB)).toBe(true) + await act(async () => { fireEvent.click(toggle) }) + const input = h.view.container.querySelector('[data-files-search]')! + expect(document.activeElement).toBe(input) + expect(toggle.getAttribute('aria-expanded')).toBe('true') + expect(h.instance.getSnapshot().byPane[PANE]?.open).toBeUndefined() + h.searches.answerWith(answer(['src/target.ts'])) + await act(async () => { + fireEvent.change(input, { target: { value: 'target' } }) + await searchesSettled() + }) + const search = h.instance.getSnapshot().byPane[PANE]!.search + const body = h.view.container.querySelector('[data-files-body]')! + expect(body.getAttribute('data-files-view')).toBe('search') + expect(names(h.view.container)).toContain(`${ROOT}/src/target.ts`) + fireEvent.click(toggle) + expect(document.activeElement).toBe(toggle) + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(toggle.getAttribute('aria-expanded')).toBe('false') + expect(h.instance.getSnapshot().byPane[PANE]!.query).toBe('target') + expect(h.instance.getSnapshot().byPane[PANE]!.search).toBe(search) + expect(h.view.container.querySelector('[data-files-body]')).toBe(body) + h.view.unmount() + const back = h.remount() + expect(back.queryByRole('searchbox')).toBeNull() + expect(names(back.container)).toContain(`${ROOT}/src/target.ts`) + await act(async () => { fireEvent.click(back.getByRole('button', { name: zh['search.placeholder'] })) }) + expect(back.container.querySelector('[data-files-search]')?.value).toBe('target') + expect(h.search).toHaveBeenCalledTimes(1) + }) + + it('keeps focus in the tree when Escape clears results while the search bar is collapsed', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + h.searches.answerWith(answer(['src/target.ts'])) + await act(async () => { + fireEvent.change(h.view.getByRole('searchbox'), { target: { value: 'target' } }) + await searchesSettled() + }) + fireEvent.click(toggle) + const result = h.view.container.querySelector(`[data-files-path="${ROOT}/src/target.ts"] button`)! + result.focus() + await act(async () => { fireEvent.keyDown(result, { key: 'Escape' }) }) + const body = h.view.container.querySelector('[data-files-body]')! + expect(body.getAttribute('data-files-view')).toBe('tree') + expect(h.instance.getSnapshot().byPane[PANE]!.query).toBe('') + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(document.activeElement).toBe(body) + }) + + it('keeps a search running and draws its answer while the search bar is collapsed', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + h.searches.answerWith(undefined) + fireEvent.change(h.view.getByRole('searchbox'), { target: { value: 'target' } }) + const running = h.searches.started[0]! + fireEvent.click(toggle) + expect(running.signal.aborted).toBe(false) + expect(h.view.container.querySelector('[data-files-body]')?.getAttribute('aria-busy')).toBe('true') + await act(async () => { + running.settle(answer(['src/target.ts'])) + await searchesSettled() + }) + expect(h.view.queryByRole('searchbox')).toBeNull() + expect(names(h.view.container)).toContain(`${ROOT}/src/target.ts`) + expect(h.view.container.querySelector('[data-files-body]')?.getAttribute('aria-busy')).toBe('false') + await act(async () => { h.face.focus(PANE) }) + expect(h.view.container.querySelector('[data-files-search]')?.value).toBe('target') + expect(document.activeElement).toBe(h.view.getByRole('searchbox')) + expect(h.search).toHaveBeenCalledTimes(1) + }) + + it('closes search settings when the toolbar collapses the search bar', async () => { + const h = mountBody() + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) + const toggle = h.view.getByRole('button', { name: zh['search.placeholder'] }) + await act(async () => { fireEvent.click(toggle) }) + fireEvent.click(h.view.getByRole('button', { name: zh['search.settings'] })) + expect(h.view.queryByRole('dialog')).not.toBeNull() + fireEvent.click(toggle) + expect(h.view.queryByRole('dialog')).toBeNull() + await act(async () => { fireEvent.click(toggle) }) + expect(h.view.queryByRole('dialog')).toBeNull() + }) + + it('lists the root on mount, heads it with its path split at the last segment, and draws directories first with dotfiles shown once the reader asks', async () => { const { view, script } = mountBody() expect(script.list).not.toHaveBeenCalled() await act(() => script.watches.ready(ROOT)) @@ -82,6 +199,9 @@ describe('FilesBody', () => { const path = view.container.querySelector('[data-files-path]') expect(path?.getAttribute('title')).toBe(ROOT) expect([...path?.firstElementChild?.children ?? []].map(span => span.textContent)).toEqual(['/work/', 'app']) + expect(names(view.container)).toEqual([`${ROOT}/src`, `${ROOT}/pipe`, `${ROOT}/README.md`]) + await act(async () => { fireEvent.click(view.getByRole('button', { name: zh['search.placeholder'] })) }) + act(() => { fireEvent.click(view.getByRole('button', { name: zh['search.showHidden'] })) }) expect(names(view.container)).toEqual([`${ROOT}/src`, `${ROOT}/.env`, `${ROOT}/pipe`, `${ROOT}/README.md`]) const envIcon = view.container.querySelector(`[data-files-path="${ROOT}/.env"] svg`)?.innerHTML const readmeIcon = view.container.querySelector(`[data-files-path="${ROOT}/README.md"] svg`)?.innerHTML @@ -94,7 +214,7 @@ describe('FilesBody', () => { await act(() => script.settle({ ok: true, value: ROOT_LEVEL })) const path = view.container.querySelector('[data-files-path]') expect([...path?.firstElementChild?.children ?? []].map(span => span.textContent)).toEqual(['/']) - expect(names(view.container)).toEqual(['/src', '/.env', '/pipe', '/README.md']) + expect(names(view.container)).toEqual(['/src', '/pipe', '/README.md']) }) it('marks the root path clipped while its text is wider than its box, re-reading on resize', async () => { diff --git a/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx b/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx index baaa8e2d53..60bb8667f7 100644 --- a/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/files-navigator.client.spec.tsx @@ -610,6 +610,17 @@ describe('FileNavigator beside a preview', () => { expect(document.activeElement).toBe(document.body) }) + it('carries keyboard focus on the tree\'s scroll container, with no current row, to the next drawing', async () => { + const h = mountNavigator('sidebar://files') + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + act(() => { h.view.container.querySelector('[data-files-body]')!.focus() }) + h.view.unmount() + const back = h.remount() + await endTask() + expect(document.activeElement).toBe(back.container.querySelector('[data-files-body]')) + }) + it('gives the carried focus to the drawing in place when the task ends, after the tab draws the tree again', async () => { const h = mountNavigator(A) await revealSrc(h) @@ -629,15 +640,15 @@ describe('FileNavigator beside a preview', () => { expect(document.activeElement).toBe(document.body) }) - it('takes keyboard focus when asked, at its next drawing or at once', async () => { + it('gives its search field keyboard focus when asked, at its next drawing or at once', async () => { const h = mountNavigator('sidebar://files') act(() => { h.face.focus(PANE) }) await act(() => h.script.watches.ready(ROOT)) - expect(document.activeElement?.hasAttribute('data-files-body')).toBe(true) + expect(document.activeElement).toBe(h.view.getByRole('searchbox', { name: zh['search.placeholder'] })) act(() => { (document.activeElement as HTMLElement).blur() }) act(() => { h.face.focus(PANE) }) await endTask() - expect(document.activeElement?.hasAttribute('data-files-body')).toBe(true) + expect(document.activeElement).toBe(h.view.getByRole('searchbox', { name: zh['search.placeholder'] })) }) it('keeps the pane\'s tree when a preview is replaced in place by the file it opened', async () => { diff --git a/packages/client/ui-sidebar-files/tests/mount.client.tsx b/packages/client/ui-sidebar-files/tests/mount.client.tsx index 35a660f264..32a4cc14aa 100644 --- a/packages/client/ui-sidebar-files/tests/mount.client.tsx +++ b/packages/client/ui-sidebar-files/tests/mount.client.tsx @@ -27,10 +27,12 @@ import { FilesBody } from '../src/client/FilesBody.tsx' import type { FilesBodyProps } from '../src/client/FilesBody.tsx' import { NavigatorToggle } from '../src/client/NavigatorToggle.tsx' import { zh } from '../src/client/locales.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' import { createFilesStore } from '../src/client/store.ts' import type { FilesStoreInstance } from '../src/client/store.ts' import { scriptedList } from './scripted-list.client.ts' import type { ScriptedList } from './scripted-list.client.ts' +import { memoryBook, scriptedSearch, type ScriptedSearch } from './search-fixture.client.ts' export const SESSION = 's-test' as SessionId export const ROOT = '/work/app' @@ -71,6 +73,12 @@ export interface Mounted { readonly view: RenderResult readonly instance: FilesStoreInstance readonly script: ScriptedList + /** The search the face calls; it matches nothing until a spec gives it matches. */ + readonly search: ScriptedSearch['search'] + /** That search's script: the searches it started, and how it answers later ones. */ + readonly searches: ScriptedSearch + /** The search preferences of every workspace, which another mount may share. */ + readonly book: WorkspaceSearchPreferenceBook readonly face: FilesInjected /** The first tab's lifetime. */ readonly controller: AbortController @@ -93,9 +101,11 @@ export interface Mounted { } /** One store instance, one face, one owner share. */ -function harness(placement: Placement, controller: AbortController) { +function harness(placement: Placement, controller: AbortController, book: WorkspaceSearchPreferenceBook) { const instance = createFilesStore().create() const script = scriptedList() + const searches = scriptedSearch() + const search = searches.search // Whether some tab type opens files: one predicate per answer, as registrations change it. const listeners = new Set<() => void>() let check = (_address: string): boolean => true @@ -115,7 +125,7 @@ function harness(placement: Placement, controller: AbortController) { // The owner's count of drawings that placed the face beside each tab. const placed = new Map() const navigation = createSnapshotStore({ address: placement.contentId, params: undefined, revision: 0 }) - const face = filesFace(script.list, script.watch, canOpen, () => navigation)(SESSION, instance, (tabId) => { + const face = filesFace(script.list, script.watch, canOpen, () => navigation, search, book)(SESSION, instance, (tabId) => { placed.set(tabId, (placed.get(tabId) ?? 0) + 1) return () => { placed.set(tabId, placed.get(tabId)! - 1) } }) @@ -164,9 +174,13 @@ function harness(placement: Placement, controller: AbortController) { }, useCanOpen: (sel: (check: (address: string) => boolean) => S) => sel(useSyncExternalStore(listener => hooks.canOpen.subscribe(listener), () => hooks.canOpen.getSnapshot())), + useSearchPreferences: (cwd: string) => { + const source = keyedHooks.searchPreferences(cwd) + return useSyncExternalStore(listener => source.subscribe(listener), () => source.getSnapshot()) + }, t, } - return { instance, script, face, controller, viewers, tabActions, onOpen, beside, shared } + return { instance, script, search, searches, book, face, controller, viewers, tabActions, onOpen, beside, shared } } /** @@ -278,16 +292,18 @@ function bodyProps(shared: object): FilesBodyProps { * @param placement - the tab's address, the pane's presentation, and the session's working directory. * @param draw - the drawing over the shared props. * @param recordObservers - capture navigator measurement notifications. + * @param book - the search preferences, shared with another mount when given. * @returns the mounted hands. */ function mount( given: Omit, draw: (shared: ReturnType['shared']) => ReactNode, recordObservers = false, + book: WorkspaceSearchPreferenceBook = memoryBook(), ): Mounted { const controller = new AbortController() const placement: Placement = { ...given, tabId: TAB, signal: controller.signal } - const { shared, ...hands } = harness(placement, controller) + const { shared, ...hands } = harness(placement, controller, book) const { row, viewport } = measureRows(recordObservers) const element = (): ReactNode =>
    {draw(shared)}
    const view = render(element()) @@ -319,9 +335,15 @@ export function mountBody(cwd: string | null = ROOT, placement: Partial = {}, cwd: string | null = ROOT): Mounted { +export function mountNavigator( + contentId: string, + placement: Partial = {}, + cwd: string | null = ROOT, + book?: WorkspaceSearchPreferenceBook, +): Mounted { return mount({ contentId, ...placement, cwd }, shared => ( <> @@ -330,5 +352,5 @@ export function mountNavigator(contentId: string, placement: Partial
    - ), true) + ), true, book) } diff --git a/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx b/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx index 7aee76c1fc..06aec36122 100644 --- a/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx +++ b/packages/client/ui-sidebar-files/tests/navigation.client.spec.tsx @@ -9,7 +9,9 @@ import type { SessionId } from '@deepseek-ai/dsh-session/types' import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' import { filesFace } from '../src/client/face.ts' import type { ListWorkspaceDirectory, WatchWorkspaceDirectory } from '../src/client/face.ts' +import type { SearchWorkspace } from '../src/client/search-workspace.ts' import { createFilesStore } from '../src/client/store.ts' +import { memoryBook } from './search-fixture.client.ts' const SESSION = 'navigation-session' as SessionId const LEFT = 'pane-left' as PaneId @@ -73,7 +75,7 @@ function harness() { return () => { unsubscribe(); tab.listeners.delete(listener) } }, } - })(SESSION, instance, () => () => {}) + }, vi.fn(() => { throw new Error('Navigation must not search') }), memoryBook())(SESSION, instance, () => () => {}) const tab = (id: TabId, revision = 0): TestTab => { const address = sessionFileAddress(SESSION, `${id}.ts`) diff --git a/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts new file mode 100644 index 0000000000..2436eac12e --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-face.client.spec.ts @@ -0,0 +1,224 @@ +/** The face's search: when it runs, the preferences it follows, what it aborts and drops, and the store writes it makes. */ +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' +import type { PaneId, TabId } from '@deepseek-ai/dsh-client-ui-dockkit' +import type { SessionId } from '@deepseek-ai/dsh-session/types' +import { filesFace } from '../src/client/face.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' +import { defaultSearchPreferences, enabledPaths } from '../src/client/search-rules.ts' +import { createSearch } from '../src/client/search-workspace.ts' +import type { WorkspaceFilesSearchRemote } from '../src/client/search-workspace.ts' +import { createFilesStore } from '../src/client/store.ts' +import { scriptedList } from './scripted-list.client.ts' +import { answer, memoryBook, scriptedSearch, searchesSettled } from './search-fixture.client.ts' + +const ROOT = '/work/app' +const PANE = 'pane-1' as PaneId +const CAN_OPEN = { getSnapshot: () => () => true, subscribe: () => () => {} } +/** No tab navigates. */ +const NO_NAVIGATION = () => ({ getSnapshot: () => ({ address: '', params: undefined, revision: 0 }), subscribe: () => () => {} }) + +/** One Session's face over a shared book, with its pane attached. */ +function session(id: string, book: WorkspaceSearchPreferenceBook) { + const instance = createFilesStore().create() + const script = scriptedList() + const searches = scriptedSearch(['src/a.ts']) + const face = filesFace(script.list, script.watch, CAN_OPEN, NO_NAVIGATION, searches.search, book)( + id as SessionId, instance, () => () => {}, + ) + const tab = new AbortController() + const release = face.attach(PANE, 'tab-1' as TabId, tab.signal) + onTestFinished(async () => { + release() + tab.abort() + await script.dispose() + }) + return { + instance, searches, search: searches.search, face, release, tab, + state: () => instance.getSnapshot().byPane[PANE]?.search, + result: () => instance.getSnapshot().byPane[PANE]?.search?.result, + } +} + +describe('the face\'s search', () => { + it('searches nothing for a pane no navigator attached', () => { + const h = session('s-1', memoryBook()) + h.face.setQuery('pane-2' as PaneId, ROOT, 'a') + h.face.retrySearch('pane-2' as PaneId) + expect(h.search).not.toHaveBeenCalled() + expect(h.instance.getSnapshot().byPane['pane-2' as PaneId]).toBeUndefined() + // A search field that goes after its pane was forgotten leaves nothing to record. + h.face.searchDrawn('pane-2' as PaneId, null) + expect(h.instance.getSnapshot().byPane['pane-2' as PaneId]).toBeUndefined() + }) + + it('asks the Host with the trimmed query and the workspace\'s preferences, pending until the answer draws the matches as a tree', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, ' a ') + expect(h.search).toHaveBeenCalledExactlyOnceWith('s-1', { + query: 'a', excludedPaths: enabledPaths(defaultSearchPreferences().rules), includeHidden: false, respectGitignore: true, + }, expect.any(AbortSignal)) + expect(h.state()).toEqual({ pending: true, result: undefined }) + h.searches.started[0]!.settle(answer(['src/a.ts'], { truncated: true, incomplete: true })) + await searchesSettled() + expect(h.state()?.pending).toBe(false) + expect(h.result()).toMatchObject({ + kind: 'found', query: 'a', count: 1, truncated: true, incomplete: true, hiddenLeftOut: true, excluded: true, + tree: { expanded: [ROOT, `${ROOT}/src`] }, + }) + // Whitespace around the same text searches nothing new. + h.face.setQuery(PANE, ROOT, 'a') + expect(h.search).toHaveBeenCalledOnce() + expect(h.instance.getSnapshot().byPane[PANE]?.query).toBe('a') + }) + + it('aborts the running search when a newer one starts, keeping the last result drawn and dropping the older answer', async () => { + const h = session('s-1', memoryBook()) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + const first = h.result() + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'ab') + h.face.setQuery(PANE, ROOT, 'abc') + const [, older, newer] = h.searches.started + expect(older?.signal.aborted).toBe(true) + expect(newer?.signal.aborted).toBe(false) + expect(h.state()).toEqual({ pending: true, result: first }) + // The newer answer draws; the older one, arriving later, is dropped. + newer!.settle(answer(['abc.ts'])) + await searchesSettled() + older!.settle(answer(['ab.ts'])) + await searchesSettled() + expect(h.result()).toMatchObject({ query: 'abc', count: 1 }) + expect(h.state()?.pending).toBe(false) + }) + + it('aborts a running search when the query is cleared or the pane is forgotten, and writes nothing for it', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'a') + const cleared = h.searches.started[0]! + h.face.setQuery(PANE, ROOT, '') + expect(cleared.signal.aborted).toBe(true) + // Typing the same text again searches anew, and the dropped answer does not draw. + h.face.setQuery(PANE, ROOT, 'a') + cleared.settle(answer(['old.ts'])) + await searchesSettled() + expect(h.state()).toEqual({ pending: true, result: undefined }) + + const running = h.searches.started[1]! + h.release() + h.tab.abort() + await searchesSettled() + expect(running.signal.aborted).toBe(true) + running.settle(answer(['late.ts'])) + await searchesSettled() + expect(h.instance.getSnapshot().byPane[PANE]).toBeUndefined() + }) + + it('records a failed search as a failure, and searches again on retry', async () => { + const h = session('s-1', memoryBook()) + h.searches.answerWith(undefined) + h.face.setQuery(PANE, ROOT, 'a') + const failure = new RemoteError('gateway/internal', 'host is gone', {}) + h.searches.started[0]!.settle({ ok: false, error: failure }) + await searchesSettled() + expect(h.state()).toEqual({ pending: false, result: { kind: 'failed', query: 'a', failure } }) + h.face.retrySearch(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + // A failure belongs to the query that failed, so a new search drops it instead of drawing it beside the spinner. + expect(h.state()).toEqual({ pending: true, result: undefined }) + // A rejected call, which only an assembly fault causes, is reported rather than left pending. + h.searches.started[1]!.reject(new Error('no search method')) + await searchesSettled() + expect(h.state()).toMatchObject({ + pending: false, result: { kind: 'failed', query: 'a', failure: { code: 'gateway/internal', message: 'no search method' } }, + }) + h.face.retrySearch(PANE) + h.searches.started[2]!.reject('refused') + await searchesSettled() + expect(h.result()).toMatchObject({ kind: 'failed', failure: { message: 'refused' } }) + // Without a query there is nothing to retry. + h.face.setQuery(PANE, ROOT, '') + h.face.retrySearch(PANE) + expect(h.search).toHaveBeenCalledTimes(3) + }) + + it('searches again on refresh while the pane has a query, and not once the query is blank', async () => { + const h = session('s-1', memoryBook()) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + expect(h.search).toHaveBeenCalledTimes(1) + h.face.refresh(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + expect(h.search).toHaveBeenLastCalledWith('s-1', expect.objectContaining({ query: 'a' }), expect.anything()) + h.face.setQuery(PANE, ROOT, '') + h.face.refresh(PANE) + expect(h.search).toHaveBeenCalledTimes(2) + }) + + it('follows one workspace\'s preferences, shared by every Session rooted there, until the query is blank', async () => { + const book = memoryBook() + const one = session('s-1', book) + const two = session('s-2', book) + const elsewhere = session('s-3', book) + expect(two.face.keyedHooks.searchPreferences(ROOT)).toBe(one.face.keyedHooks.searchPreferences(`${ROOT}/`)) + two.face.setQuery(PANE, ROOT, 'a') + elsewhere.face.setQuery(PANE, '/work/other', 'a') + const before = one.face.keyedHooks.searchPreferences('/work/other').getSnapshot() + one.face.setSearchPreferences(ROOT, { rules: [], showHidden: true }) + expect(two.search).toHaveBeenLastCalledWith( + 's-2', { query: 'a', excludedPaths: [], includeHidden: true, respectGitignore: true }, expect.any(AbortSignal), + ) + await searchesSettled() + expect(two.result()).toMatchObject({ hiddenLeftOut: false, excluded: false }) + expect(elsewhere.search).toHaveBeenCalledOnce() + expect(one.face.keyedHooks.searchPreferences('/work/other').getSnapshot()).toBe(before) + // The `.gitignore` choice is a preference like the others. + one.face.setSearchPreferences(ROOT, { respectGitignore: false }) + expect(two.search).toHaveBeenLastCalledWith('s-2', expect.objectContaining({ respectGitignore: false }), expect.any(AbortSignal)) + // A change to another root's entry leaves this root's search alone. + one.face.setSearchPreferences('/work/other', { ...defaultSearchPreferences(), rules: [] }) + expect(two.search).toHaveBeenCalledTimes(3) + + // A pane that moves to another root follows that root instead. + two.face.setQuery(PANE, '/work/other', 'a') + expect(two.search).toHaveBeenCalledTimes(4) + one.face.setSearchPreferences(ROOT, defaultSearchPreferences()) + expect(two.search).toHaveBeenCalledTimes(4) + + two.face.setQuery(PANE, '/work/other', ' ') + expect(two.state()).toBeUndefined() + one.face.setSearchPreferences('/work/other', { ...defaultSearchPreferences(), showHidden: true }) + expect(two.search).toHaveBeenCalledTimes(4) + }) + + it('does not search again when the listed levels change under shown results', async () => { + const h = session('s-1', memoryBook()) + h.instance.actions.start(PANE, ROOT) + h.face.setQuery(PANE, ROOT, 'a') + await searchesSettled() + const shown = h.result() + h.instance.actions.loaded(PANE, ROOT, { entries: [{ name: 'src', type: 'directory' }], truncated: false }) + await searchesSettled() + expect(h.search).toHaveBeenCalledOnce() + expect(h.result()).toBe(shown) + }) +}) + +describe('createSearch', () => { + it('passes the session, the request, and the signal through, and returns the Host\'s answer or failure as it is', async () => { + const search = vi.fn() + const value = { matches: [{ path: 'src/a.ts', type: 'file' as const }], truncated: false, incomplete: true } + search.mockResolvedValueOnce({ ok: true, value }) + const request = { query: 'a', excludedPaths: ['dist'], includeHidden: false, respectGitignore: true } + const signal = new AbortController().signal + const bound = createSearch({ workspaceFiles: { search } }) + expect(await bound('s-1' as SessionId, request, signal)).toEqual({ ok: true, value }) + expect(search).toHaveBeenCalledWith('s-1', request, signal) + const error = new RemoteError('gateway/internal', 'down', {}) + search.mockResolvedValueOnce({ ok: false, error }) + expect(await bound('s-1' as SessionId, request, signal)).toEqual({ ok: false, error }) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-fixture.client.ts b/packages/client/ui-sidebar-files/tests/search-fixture.client.ts new file mode 100644 index 0000000000..2b7fc0c35d --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-fixture.client.ts @@ -0,0 +1,91 @@ +/** Scripted search answers and in-memory preferences for the search specs. */ +import { vi } from 'vitest' +import type { Mock } from 'vitest' +import type { RemoteResult } from '@deepseek-ai/dsh-api-remotes/client' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSearchPreferenceBook } from '../src/client/search-preferences.ts' +import type { WorkspaceSearchPreferenceBook } from '../src/client/search-preferences.ts' +import type { SearchMatch } from '../src/client/search-tree.ts' +import type { SearchWorkspace, WorkspaceSearchAnswer, WorkspaceSearchRequest } from '../src/client/search-workspace.ts' + +/** + * Matches as a search answers them. + * @param paths - matched paths, files unless they end with `/`. + * @returns the matches. + */ +export function found(paths: readonly string[]): SearchMatch[] { + return paths.map(path => path.endsWith('/') ? { path: path.slice(0, -1), type: 'directory' as const } : { path, type: 'file' as const }) +} + +/** Whether an answer is cut at the Host's match limit, or missed some directories. */ +export interface AnswerFlags { + readonly truncated?: boolean + readonly incomplete?: boolean +} + +/** + * A settled answer. + * @param paths - the matches, as {@link found} takes them. + * @param flags - whether the answer is truncated or incomplete; neither when omitted. + * @returns the answer. + */ +export function answer(paths: readonly string[], flags: AnswerFlags = {}): RemoteResult { + return { ok: true, value: { matches: found(paths), truncated: flags.truncated ?? false, incomplete: flags.incomplete ?? false } } +} + +/** One search the face started. */ +export interface StartedSearch { + /** What the face asked for. */ + readonly request: WorkspaceSearchRequest + /** The signal the face passed. */ + readonly signal: AbortSignal + /** Answer it, unless it is already answered. @param result - the answer. */ + readonly settle: (result: RemoteResult) => void + /** Reject it, as an assembly fault does. @param error - the rejection. */ + readonly reject: (error: unknown) => void +} + +/** A search the face calls: it answers at once with a fixed answer, or leaves each call open for the spec to settle. */ +export interface ScriptedSearch { + /** The mock the face receives. */ + readonly search: Mock + /** Every search started, oldest first. */ + readonly started: readonly StartedSearch[] + /** + * Answer every later search at once, or leave later searches open. + * @param result - the answer, or `undefined` to leave them open. + */ + readonly answerWith: (result: RemoteResult | undefined) => void +} + +/** + * A search that answers every request with the same matches until the spec + * changes them. + * @param paths - the matches, as {@link found} takes them. + * @returns the scripted search. + */ +export function scriptedSearch(paths: readonly string[] = []): ScriptedSearch { + const started: StartedSearch[] = [] + let fixed: RemoteResult | undefined = answer(paths) + const search = vi.fn((_sessionId, request, signal) => new Promise((resolve, reject) => { + started.push({ request, signal, settle: resolve, reject }) + if (fixed !== undefined) resolve(fixed) + })) + return { search, started, answerWith: (result) => { fixed = result } } +} + +/** + * Let settled searches reach the face: a search's answer takes two microtasks to be written. + * @returns once they have. + */ +export async function searchesSettled(): Promise { + for (let turn = 0; turn < 3; turn += 1) await Promise.resolve() +} + +/** + * A preference book over an in-memory store, as the plugin keeps one over browser storage. + * @returns the book. + */ +export function memoryBook(): WorkspaceSearchPreferenceBook { + return createSearchPreferenceBook(createSnapshotStore({})) +} diff --git a/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts new file mode 100644 index 0000000000..f093c16185 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-preferences.client.spec.ts @@ -0,0 +1,119 @@ +// @vitest-environment jsdom +/** The workspace search preferences kept in browser storage, read back without trusting what storage holds. */ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createSnapshotStore } from '@deepseek-ai/dsh-client-store' +import { createSearchPreferenceBook, SEARCH_PREFERENCES_KEY, workspaceKey } from '../src/client/search-preferences.ts' +import { defaultSearchPreferences } from '../src/client/search-rules.ts' + +/** A book over browser storage, as the plugin's `apply` builds it. */ +function persisted() { + return createSearchPreferenceBook(createSnapshotStore({}, { persist: { name: SEARCH_PREFERENCES_KEY } })) +} +const stored = (): unknown => JSON.parse(localStorage.getItem(SEARCH_PREFERENCES_KEY) ?? 'null') + +afterEach(() => { + localStorage.clear() + vi.restoreAllMocks() +}) + +describe('workspaceKey', () => { + it.each([ + ['/work/app', '/work/app'], + ['/work/app/', '/work/app'], + ['/work/app//', '/work/app'], + ['/', '/'], + ['C:\\work\\', 'C:\\work'], + ['C:\\', 'C:\\'], + ['C:/', 'C:/'], + ['C:', 'C:'], + ])('keys %s as %s', (cwd, key) => { + expect(workspaceKey(cwd)).toBe(key) + }) +}) + +describe('createSearchPreferenceBook', () => { + it('writes only the roots the reader changed, and drops a root changed back to the defaults', () => { + const book = persisted() + const chosen = { rules: [{ path: 'out', enabled: false }], showHidden: true, respectGitignore: false } + book.update('/work/app/', chosen) + book.update('/work/lib', { ...defaultSearchPreferences(), showHidden: true }) + expect(stored()).toEqual({ '/work/app': chosen, '/work/lib': { showHidden: true } }) + expect(book.source('/work/app').getSnapshot()).toEqual(chosen) + book.update('/work/lib', defaultSearchPreferences()) + expect(stored()).toEqual({ '/work/app': chosen }) + expect(book.source('/work/never').getSnapshot()).toEqual(defaultSearchPreferences()) + }) + + it('changes only the fields a patch names, over the root\'s preferences at the time of the change', () => { + const book = persisted() + book.update('/work/app', { showHidden: true }) + book.update('/work/app', { rules: [{ path: 'out', enabled: true }] }) + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: true, respectGitignore: true }) + book.update('/work/app', { showHidden: false }) + book.update('/work/app', { respectGitignore: false }) + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: false, respectGitignore: false }) + // A `.gitignore` choice alone differs from the defaults, so only it is stored. + book.update('/work/app', { rules: defaultSearchPreferences().rules }) + expect(stored()).toEqual({ '/work/app': { respectGitignore: false } }) + }) + + it('leaves the rules out of an entry whose rules the reader did not change, so the running build\'s default list applies', () => { + persisted().update('/work/app', { showHidden: true }) + expect(stored()).toEqual({ '/work/app': { showHidden: true } }) + // An entry another build stored without rules reads the default list of this build. + localStorage.setItem(SEARCH_PREFERENCES_KEY, JSON.stringify({ '/work/app': { showHidden: true, respectGitignore: false } })) + expect(persisted().source('/work/app').getSnapshot()).toEqual({ ...defaultSearchPreferences(), showHidden: true, respectGitignore: false }) + }) + + it('keeps each root\'s snapshot until that root changes', () => { + const book = persisted() + const app = book.source('/work/app') + const first = app.getSnapshot() + expect(app.getSnapshot()).toBe(first) + const heard = vi.fn() + const stop = app.subscribe(heard) + book.update('/work/other', { rules: [], showHidden: false }) + expect(heard).toHaveBeenCalledTimes(1) + expect(app.getSnapshot()).toBe(first) + book.update('/work/app', { rules: [], showHidden: false }) + expect(app.getSnapshot()).not.toBe(first) + stop() + }) + + it('reads back what an earlier session stored, and the default for each missing or malformed field', () => { + localStorage.setItem(SEARCH_PREFERENCES_KEY, JSON.stringify({ + '/work/app': { rules: [{ path: 'out', enabled: true }, { path: '../x', enabled: true }], showHidden: true }, + '/work/lib': { rules: [], showHidden: false, respectGitignore: false }, + '/work/full': { ...defaultSearchPreferences(), showHidden: true }, + '/work/bad': { rules: 'dist', showHidden: true }, + '/work/odd': 7, + })) + const book = persisted() + expect(book.source('/work/app').getSnapshot()).toEqual({ rules: [{ path: 'out', enabled: true }], showHidden: true, respectGitignore: true }) + expect(book.source('/work/lib').getSnapshot()).toEqual({ rules: [], showHidden: false, respectGitignore: false }) + // Saving an entry that stored every field keeps only those that differ from the defaults. + book.update('/work/full', { showHidden: true }) + expect(stored()).toMatchObject({ '/work/full': { showHidden: true } }) + expect(book.source('/work/bad').getSnapshot()).toEqual({ ...defaultSearchPreferences(), showHidden: true }) + expect(book.source('/work/odd').getSnapshot()).toEqual(defaultSearchPreferences()) + }) + + it.each([ + ['a JSON array', '[]'], + ['a JSON string', '"oops"'], + ['a JSON null', 'null'], + ])('reads %s in storage as no preferences, and replaces it on the first change', (_label, raw) => { + localStorage.setItem(SEARCH_PREFERENCES_KEY, raw) + const book = persisted() + expect(book.source('/work/app').getSnapshot()).toEqual(defaultSearchPreferences()) + book.update('/work/app', { rules: [], showHidden: false }) + expect(stored()).toEqual({ '/work/app': { rules: [] } }) + }) + + it('reads storage that is not JSON as no preferences', () => { + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + localStorage.setItem(SEARCH_PREFERENCES_KEY, '{nope') + expect(persisted().source('/work/app').getSnapshot()).toEqual(defaultSearchPreferences()) + expect(report).toHaveBeenCalledTimes(1) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts new file mode 100644 index 0000000000..19addd7423 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-rules.client.spec.ts @@ -0,0 +1,239 @@ +/** Exclusion rule editing, default restoration, stored preferences, and hidden entries. */ +import { describe, expect, it } from 'vitest' +import { + addRule, changedSearchPreferences, defaultRules, defaultSearchPreferences, enabledPaths, isDefaultRules, isHiddenEntry, + normalizeRulePath, readSearchPreferences, removeRule, setRuleEnabled, type ExclusionRule, +} from '../src/client/search-rules.ts' + +const DEFAULTS = [ + '.git', '.hg', '.next', '.pnpm-store', '.svn', '.turbo', '.yarn', 'build', 'coverage', 'dist', 'node_modules', + '.DS_Store', '.Spotlight-V100', '.Trashes', '.fseventsd', 'Thumbs.db', 'desktop.ini', '$RECYCLE.BIN', 'System Volume Information', +] + +describe('normalizeRulePath', () => { + it.each([ + ['node_modules', 'node_modules'], + ['$RECYCLE.BIN', '$RECYCLE.BIN'], + [' System Volume Information ', 'System Volume Information'], + ['a/$b c/.DS_Store', 'a/$b c/.DS_Store'], + [' dist ', 'dist'], + ['packages\\app\\dist', 'packages/app/dist'], + ['./a/', 'a'], + ['././a', 'a'], + ['.//a', 'a'], + ['a//b///c', 'a/b/c'], + ['a/b//', 'a/b'], + ['.hidden', '.hidden'], + ['a..b', 'a..b'], + ['./././/cache///', 'cache'], + [' .\\.\\cache\\ ', 'cache'], + ['./parent/~cache', 'parent/~cache'], + ['./parent/C:/cache', 'parent/C:/cache'], + ['./ cache', 'cache'], + ['./ ./\t./\ncache', 'cache'], + ['cache /', 'cache'], + ['cache/ /\t/\n/', 'cache'], + [' ./ \t./cache / / ', 'cache'], + ['./\u00a0cache\ufeff/\u00a0/', 'cache'], + ['./ cache dir / nested folder / ', 'cache dir / nested folder'], + ['./ cache\t name/ next folder / ', 'cache\t name/ next folder'], + ])('normalizes %j to %j and keeps the result stable', (input, path) => { + expect(normalizeRulePath(input)).toEqual({ kind: 'ok', path }) + expect(normalizeRulePath(path)).toEqual({ kind: 'ok', path }) + const preferences = { rules: [{ path, enabled: true }], showHidden: false, respectGitignore: true } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it('normalizes long mixed edge chains while preserving internal whitespace', () => { + const path = 'cache dir / nested folder' + const input = `${'./ \t'.repeat(10_000)}${path}${' / \t'.repeat(10_000)}` + const normalized = normalizeRulePath(input) + expect(normalized.kind === 'ok' && normalized.path.length).toBe(path.length) + expect(normalized).toEqual({ kind: 'ok', path }) + expect(normalizeRulePath(path)).toEqual({ kind: 'ok', path }) + const preferences = { rules: [{ path, enabled: false }], showHidden: true, respectGitignore: false } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it.each([ + ['', 'empty'], + [' ', 'empty'], + ['./', 'empty'], + ['.//', 'empty'], + ['./ \t./ \n', 'empty'], + ['./ . / ', 'parent'], + ['a\0b', 'nul'], + ['\0', 'nul'], + ['/abs', 'absolute'], + ['/', 'absolute'], + ['///', 'absolute'], + ['\\\\server\\share', 'absolute'], + ['C:\\x', 'absolute'], + ['c:x', 'absolute'], + ['~/x', 'absolute'], + ['~', 'absolute'], + ['./~cache', 'absolute'], + ['././~cache/', 'absolute'], + ['.//./~/cache', 'absolute'], + ['./C:/cache', 'absolute'], + ['././c:cache/', 'absolute'], + ['.\\.\\C:\\cache', 'absolute'], + ['./ ~cache', 'absolute'], + ['./ C:/cache', 'absolute'], + ['./ ./\t~cache / /', 'absolute'], + ['.\\ .\\ c:cache \\ ', 'absolute'], + ['./ /cache', 'absolute'], + [' ./ ./ / ', 'absolute'], + [' \t/ ./ cache/ ', 'absolute'], + ['./ ./ /\t/', 'absolute'], + ['..', 'parent'], + ['a/../b', 'parent'], + ['a/..', 'parent'], + ['.', 'parent'], + ['a/./b', 'parent'], + ['a/.', 'parent'], + ['*.log', 'glob'], + ['a?', 'glob'], + ['[ab]', 'glob'], + ['a]', 'glob'], + ['{a,b}', 'glob'], + ['a}', 'glob'], + ['!dist', 'glob'], + ])('refuses %j as %s', (input, reason) => { + expect(normalizeRulePath(input)).toEqual({ kind: 'invalid', reason }) + }) +}) + +describe('rule list', () => { + it('starts from every default, enabled, in default order', () => { + expect(defaultRules()).toEqual(DEFAULTS.map(path => ({ path, enabled: true }))) + expect(enabledPaths(defaultRules())).toEqual(DEFAULTS) + expect(defaultSearchPreferences()).toEqual({ rules: defaultRules(), showHidden: false, respectGitignore: true }) + expect(defaultRules()).not.toBe(defaultRules()) + // Every default is a path the reader could type, unchanged by normalization. + expect(DEFAULTS.map(path => normalizeRulePath(path))).toEqual(DEFAULTS.map(path => ({ kind: 'ok', path }))) + }) + + it('adds a normalized rule at the top, enabled', () => { + const rules: ExclusionRule[] = [{ path: 'dist', enabled: true }] + expect(addRule(rules, ' ./out/ ')).toEqual({ kind: 'ok', rules: [{ path: 'out', enabled: true }, { path: 'dist', enabled: true }] }) + expect(rules).toEqual([{ path: 'dist', enabled: true }]) + }) + + it('refuses an invalid rule without changing the list', () => { + expect(addRule([], 'a/../b')).toEqual({ kind: 'invalid', reason: 'parent' }) + }) + + it('enables and moves an existing rule to the top instead of listing it twice', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: true }, { path: 'dist', enabled: false }] + expect(addRule(rules, 'dist/')).toEqual({ + kind: 'ok', rules: [{ path: 'dist', enabled: true }, { path: 'a', enabled: true }, { path: 'b', enabled: true }], + }) + expect(addRule(rules, 'b')).toEqual({ + kind: 'ok', rules: [{ path: 'b', enabled: true }, { path: 'a', enabled: true }, { path: 'dist', enabled: false }], + }) + }) + + it('removes one rule and leaves others', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: false }] + expect(removeRule(rules, 'b')).toEqual([{ path: 'a', enabled: true }]) + expect(removeRule(rules, 'c')).toEqual(rules) + }) + + it('switches one rule on or off in place', () => { + const rules: ExclusionRule[] = [{ path: 'a', enabled: true }, { path: 'b', enabled: true }] + const off = setRuleEnabled(rules, 'a', false) + expect(off).toEqual([{ path: 'a', enabled: false }, { path: 'b', enabled: true }]) + expect(off[1]).toBe(rules[1]) + expect(setRuleEnabled(off, 'a', true)).toEqual(rules) + expect(setRuleEnabled(rules, 'a', true)[0]).toBe(rules[0]) + expect(setRuleEnabled(rules, 'c', false)).toEqual(rules) + expect(enabledPaths(off)).toEqual(['b']) + }) + + it('treats only the default list, in default order and fully enabled, as the defaults', () => { + expect(isDefaultRules(defaultRules())).toBe(true) + expect(isDefaultRules(removeRule(defaultRules(), 'dist'))).toBe(false) + expect(isDefaultRules(setRuleEnabled(defaultRules(), '.git', false))).toBe(false) + const added = addRule(defaultRules(), 'out') + expect(added.kind === 'ok' && isDefaultRules(added.rules)).toBe(false) + // Adding a listed default again moves it to the top, which differs from the default order. + const moved = addRule(defaultRules(), 'dist') + expect(moved.kind === 'ok' && isDefaultRules(moved.rules)).toBe(false) + expect(isDefaultRules([])).toBe(false) + }) +}) + +describe('readSearchPreferences', () => { + it('reads stored preferences back', () => { + const preferences = { rules: [{ path: 'out', enabled: false }, { path: 'dist', enabled: true }], showHidden: true, respectGitignore: false } + expect(readSearchPreferences(JSON.parse(JSON.stringify(preferences)))).toEqual(preferences) + }) + + it('keeps a stored empty list', () => { + const preferences = { rules: [], showHidden: false, respectGitignore: true } + expect(readSearchPreferences(preferences)).toEqual(preferences) + }) + + it.each([ + ['no rules', { showHidden: true, respectGitignore: false }, { showHidden: true, respectGitignore: false }], + ['rules that are not an array', { rules: {}, showHidden: true }, { showHidden: true }], + ['no showHidden', { rules: [] }, { rules: [] }], + ['a showHidden that is not a boolean', { rules: [], showHidden: 'yes' }, { rules: [] }], + ['no .gitignore choice', { rules: [{ path: 'out', enabled: false }], showHidden: true }, { rules: [{ path: 'out', enabled: false }], showHidden: true }], + ['a .gitignore choice that is a string', { respectGitignore: 'no' }, {}], + ['a .gitignore choice that is a JSON null', { respectGitignore: null }, {}], + ])('gives %s its default alone, keeping the other fields', (_label, stored, kept) => { + expect(readSearchPreferences(stored)).toEqual({ ...defaultSearchPreferences(), ...kept }) + }) + + it.each([ + ['nothing stored', undefined], + ['a JSON null', null], + ['a JSON string', 'dist'], + ['an array', []], + ])('falls back to the defaults for %s', (_label, stored) => { + expect(readSearchPreferences(stored)).toEqual(defaultSearchPreferences()) + }) + + it('drops malformed, invalid, and repeated rules and normalizes the rest', () => { + const stored = { + rules: [ + null, 'dist', { path: 'a' }, { enabled: true }, { path: 1, enabled: true }, { path: 'b', enabled: 'yes' }, + { path: '../x', enabled: true }, { path: '*.log', enabled: true }, { path: '/abs', enabled: true }, { path: 'a\0b', enabled: true }, + { path: './out/', enabled: false }, { path: 'out', enabled: true }, { path: 'a\\b', enabled: true }, + ], + showHidden: false, + } + expect(readSearchPreferences(stored)).toEqual({ + rules: [{ path: 'out', enabled: false }, { path: 'a/b', enabled: true }], showHidden: false, respectGitignore: true, + }) + }) +}) + +describe('changedSearchPreferences', () => { + it('keeps only the fields that differ from the defaults, rule order and enabled state included', () => { + const defaults = defaultSearchPreferences() + expect(changedSearchPreferences(defaults)).toBeUndefined() + expect(changedSearchPreferences({ ...defaults, showHidden: true })).toEqual({ showHidden: true }) + expect(changedSearchPreferences({ ...defaults, respectGitignore: false })).toEqual({ respectGitignore: false }) + expect(changedSearchPreferences({ ...defaults, rules: defaults.rules.slice(1) })).toEqual({ rules: defaults.rules.slice(1) }) + const reversed = [...defaults.rules].reverse() + expect(changedSearchPreferences({ ...defaults, rules: reversed })).toEqual({ rules: reversed }) + const disabled = setRuleEnabled(defaults.rules, 'dist', false) + expect(changedSearchPreferences({ rules: disabled, showHidden: true, respectGitignore: false })) + .toEqual({ rules: disabled, showHidden: true, respectGitignore: false }) + }) +}) + +describe('isHiddenEntry', () => { + it.each([ + [{ name: '.env' }, true], + [{ name: '.git' }, true], + [{ name: 'desktop.ini' }, false], + [{ name: 'src' }, false], + [{ name: 'a.b' }, false], + ])('%j is hidden: %s', (entry, hidden) => { + expect(isHiddenEntry(entry)).toBe(hidden) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts b/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts new file mode 100644 index 0000000000..dfac89ae63 --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search-tree.client.spec.ts @@ -0,0 +1,86 @@ +/** Search results synthesized into a fully expanded tree, their count, and in-name highlights. */ +import { describe, expect, it } from 'vitest' +import { buildSearchTree, matchRanges } from '../src/client/search-tree.ts' +import type { SearchMatch } from '../src/client/search-tree.ts' + +const ROOT = '/work/app' + +describe('buildSearchTree', () => { + it('synthesizes every ancestor level and expands all of them', () => { + const tree = buildSearchTree(ROOT, [ + { path: 'src/search/index.ts', type: 'file' }, + { path: 'src/search.ts', type: 'file' }, + { path: 'notes/search.txt', type: 'file' }, + ]) + expect(tree).toEqual({ + autoRefresh: false, + root: ROOT, + levels: { + [ROOT]: { kind: 'ready', level: { entries: [{ name: 'src', type: 'directory' }, { name: 'notes', type: 'directory' }], truncated: false } }, + '/work/app/src': { kind: 'ready', level: { entries: [{ name: 'search', type: 'directory' }, { name: 'search.ts', type: 'file' }], truncated: false } }, + '/work/app/src/search': { kind: 'ready', level: { entries: [{ name: 'index.ts', type: 'file' }], truncated: false } }, + '/work/app/notes': { kind: 'ready', level: { entries: [{ name: 'search.txt', type: 'file' }], truncated: false } }, + }, + expanded: [ROOT, '/work/app/src', '/work/app/src/search', '/work/app/notes'], + }) + }) + + it('gives a matched directory without matched descendants an empty level', () => { + const tree = buildSearchTree(ROOT, [{ path: 'lib/search', type: 'directory' }, { path: 'odd', type: 'other' }]) + expect(tree.levels['/work/app/lib/search']).toEqual({ kind: 'ready', level: { entries: [], truncated: false } }) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'lib', type: 'directory' }, { name: 'odd', type: 'other' }], truncated: false } }) + expect(tree.expanded).toEqual([ROOT, '/work/app/lib', '/work/app/lib/search']) + }) + + it('lists each child once and keeps a matched directory that also has matched descendants', () => { + const entries: SearchMatch[] = [ + { path: 'search', type: 'directory' }, + { path: 'search/a.ts', type: 'file' }, + { path: 'search/a.ts', type: 'file' }, + ] + const tree = buildSearchTree(ROOT, entries) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'search', type: 'directory' }], truncated: false } }) + expect(tree.levels['/work/app/search']).toEqual({ kind: 'ready', level: { entries: [{ name: 'a.ts', type: 'file' }], truncated: false } }) + }) + + it('treats a name as a directory once any result passes through it, keeping its first position', () => { + const tree = buildSearchTree(ROOT, [{ path: 'x', type: 'file' }, { path: 'y', type: 'file' }, { path: 'x/z', type: 'file' }]) + expect(tree.levels[ROOT]).toEqual({ kind: 'ready', level: { entries: [{ name: 'x', type: 'directory' }, { name: 'y', type: 'file' }], truncated: false } }) + expect(buildSearchTree(ROOT, [{ path: 'x/z', type: 'file' }, { path: 'x', type: 'file' }]).levels[ROOT]) + .toEqual({ kind: 'ready', level: { entries: [{ name: 'x', type: 'directory' }], truncated: false } }) + }) + + it('joins paths the way the listed tree does, whatever the root spelling', () => { + const windows = buildSearchTree('C:\\work\\', [{ path: 'a/b.txt', type: 'file' }]) + expect(windows.expanded).toEqual(['C:\\work\\', 'C:\\work/a']) + expect(buildSearchTree('/', [{ path: 'etc/x', type: 'file' }]).expanded).toEqual(['/', '/etc']) + }) + + it('draws no results as an expanded empty root', () => { + expect(buildSearchTree(ROOT, [])).toEqual({ + autoRefresh: false, root: ROOT, levels: { [ROOT]: { kind: 'ready', level: { entries: [], truncated: false } } }, expanded: [ROOT], + }) + }) +}) + +describe('matchRanges', () => { + it('finds every non-overlapping occurrence regardless of case', () => { + expect(matchRanges('Search-search.SEARCH', 'search')).toEqual([[0, 6], [7, 13], [14, 20]]) + expect(matchRanges('aaaa', 'aa')).toEqual([[0, 2], [2, 4]]) + }) + + it('treats the query literally', () => { + expect(matchRanges('a.b(c)*', '.b(c)*')).toEqual([[1, 7]]) + expect(matchRanges('axb', '.')).toEqual([]) + }) + + it('has no ranges for an empty query or a miss', () => { + expect(matchRanges('name', '')).toEqual([]) + expect(matchRanges('name', 'src/name')).toEqual([]) + }) + + it('indexes the name as given around non-ASCII text', () => { + expect(matchRanges('Größe.TXT', 'größe')).toEqual([[0, 5]]) + expect(matchRanges('报告-搜索.md', '搜索')).toEqual([[3, 5]]) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/search.client.spec.tsx b/packages/client/ui-sidebar-files/tests/search.client.spec.tsx new file mode 100644 index 0000000000..3fb08ea2cf --- /dev/null +++ b/packages/client/ui-sidebar-files/tests/search.client.spec.tsx @@ -0,0 +1,666 @@ +// @vitest-environment jsdom +/** + * The navigator's search: the bar above the tree, the results drawn in the + * tree's place, the settings panel, the hidden-entry control, the keyboard, + * and the Escape order. A scripted search stands in for the Host's: it + * answers every query with fixed matches, or leaves a query open. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { act, cleanup, fireEvent, within } from '@testing-library/react' +import { sessionFileAddress } from '@deepseek-ai/dsh-util-workspace-path' +import { zh } from '../src/client/locales.ts' +import { defaultRules, enabledPaths } from '../src/client/search-rules.ts' +import type { WorkspaceSearchPreferences } from '../src/client/search-rules.ts' +import type { DirLevel } from '../src/client/store.ts' +import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime' +import { mountNavigator, PANE, ROOT, SESSION } from './mount.client.tsx' +import type { Mounted } from './mount.client.tsx' +import { answer, memoryBook, searchesSettled } from './search-fixture.client.ts' +import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' + +const ROOT_LEVEL: DirLevel = { + entries: [ + { name: 'src', type: 'directory' }, { name: 'node_modules', type: 'directory' }, + { name: '.env', type: 'file', size: 1 }, { name: 'README.md', type: 'file', size: 1 }, + ], + truncated: false, +} +const SRC_LEVEL: DirLevel = { entries: [{ name: 'a.ts', type: 'file', size: 1 }, { name: 'b.ts', type: 'file', size: 1 }], truncated: false } +const A = sessionFileAddress(SESSION, 'src/a.ts') +const t = makeTranslate(zh) + +beforeEach(() => { + Element.prototype.scrollIntoView = vi.fn() +}) +afterEach(() => { + cleanup() + Reflect.deleteProperty(Element.prototype, 'scrollIntoView') +}) + +/** Show the navigator on a page-less tab and answer the root listing. */ +async function shown(h: Mounted): Promise { + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: ROOT_LEVEL })) +} + +/** Show the navigator beside `src/a.ts` and answer the root and `src` listings. */ +async function revealed(h: Mounted): Promise { + await shown(h) + await act(() => h.script.watches.ready(`${ROOT}/src`)) + await act(() => h.script.settle({ ok: true, value: SRC_LEVEL })) +} + +const field = (h: Mounted): HTMLInputElement => within(h.view.container).getByRole('searchbox', { name: zh['search.placeholder'] }) +const body = (h: Mounted): HTMLElement => h.view.container.querySelector('[data-files-body]')! + +/** + * The tooltip text of the empty result's information button, read by pinning + * the tooltip with a click and closing it again; `undefined` without the button. + */ +const emptyHint = (h: Mounted): string | undefined => { + const button = body(h).querySelector('[data-files-search-hint]') + if (button === null) return undefined + expect(button.getAttribute('aria-label')).toBe(zh['search.emptyHint.label']) + fireEvent.click(button) + const text = document.querySelector('[role="tooltip"]')?.textContent + fireEvent.click(button) + expect(document.querySelector('[role="tooltip"]')).toBeNull() + return text +} +const status = (h: Mounted): string | null | undefined => h.view.container.querySelector('[data-files-search-status]')?.textContent +const paths = (h: Mounted): string[] => [...body(h).querySelectorAll('[data-files-entry]')].map(li => li.getAttribute('data-files-path')!) +const dialog = (h: Mounted): HTMLElement | null => h.view.queryByRole('dialog') +const settingsButton = (h: Mounted): HTMLElement => h.view.getByRole('button', { name: zh['search.settings'] }) + +/** jsdom omits mousedown's focus default; honor its cancellation before clicking. */ +function pointerClick(target: HTMLElement): void { + act(() => { + fireEvent.pointerDown(target, { button: 0, pointerType: 'mouse' }) + if (fireEvent.mouseDown(target, { button: 0 })) target.focus() + fireEvent.pointerUp(target, { button: 0, pointerType: 'mouse' }) + fireEvent.mouseUp(target, { button: 0 }) + fireEvent.click(target, { button: 0 }) + }) +} + +/** Supply the focused button's native keyboard activation that jsdom omits. */ +function keyboardClick(target: HTMLElement, key: 'Enter' | ' '): void { + act(() => { + target.focus() + const allowed = fireEvent.keyDown(target, { key }) + if (allowed && key === 'Enter') target.click() + const released = fireEvent.keyUp(target, { key }) + if (allowed && released && key === ' ') target.click() + }) +} + +/** + * Type into the search field and let the search's answer draw. + * @param h - the mounted navigator. + * @param text - the field's new text. + * @param matches - what the search answers, as `answer` takes them; the previous answer when omitted. + */ +async function type(h: Mounted, text: string, matches?: readonly string[]): Promise { + if (matches !== undefined) h.searches.answerWith(answer(matches)) + await act(async () => { + fireEvent.change(field(h), { target: { value: text } }) + await searchesSettled() + }) +} +/** Run a store or face write and let a search it starts draw its answer. */ +async function settled(write: () => void): Promise { + await act(async () => { + write() + await searchesSettled() + }) +} +/** The requests the search received, oldest first. */ +const requests = (h: Mounted) => h.search.mock.calls.map(([, request]) => request) + +describe('the search bar', () => { + it('searches as the reader types and draws the matches as a highlighted tree with its count', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + expect(h.view.queryByRole('button', { name: zh['search.clear'] })).toBeNull() + await type(h, ' Ab ', ['src/tab.ts', 'lib/AB/', 'lib/AB/x.ts']) + expect(requests(h)).toEqual([{ query: 'Ab', excludedPaths: enabledPaths(defaultRules()), includeHidden: false, respectGitignore: true }]) + expect(status(h)).toBe(t('search.results', { count: '3' })) + expect(paths(h)).toEqual([`${ROOT}/lib`, `${ROOT}/lib/AB`, `${ROOT}/lib/AB/x.ts`, `${ROOT}/src`, `${ROOT}/src/tab.ts`]) + expect([...body(h).querySelectorAll('mark')].map(mark => mark.textContent)).toEqual(['AB', 'ab']) + expect(body(h).querySelector(`[data-files-path="${ROOT}/src/tab.ts"] button`)?.textContent).toBe('tab.ts') + expect(h.view.getByRole('button', { name: zh['search.clear'] })).toBeTruthy() + // Whitespace around the same text asks nothing new and keeps the count. + await type(h, 'Ab') + expect(requests(h)).toHaveLength(1) + expect(status(h)).toBe(t('search.results', { count: '3' })) + }) + + it('collapses result directories on their own, and opens a result like a tree row with the tab\'s file marked', async () => { + const h = mountNavigator(A) + await revealed(h) + await type(h, 'a', ['src/a.ts', 'empty/']) + // A matched directory without matched descendants is not called empty. + expect(body(h).querySelector('[data-files-row="empty"]')).toBeNull() + expect(body(h).querySelector('[aria-current="true"]')?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src/a.ts`) + const src = (): HTMLElement => body(h).querySelector(`[data-files-path="${ROOT}/src"] > div > button`)! + act(() => { fireEvent.click(src()) }) + expect(src().getAttribute('aria-expanded')).toBe('false') + expect(h.instance.getSnapshot().byPane[PANE]?.tree?.expanded).toEqual([ROOT, `${ROOT}/src`]) + act(() => { fireEvent.click(src()) }) + fireEvent.click(body(h).querySelector(`[data-files-path="${ROOT}/src/a.ts"] > div > button`)!) + expect(h.onOpen).toHaveBeenLastCalledWith(A) + }) + + it('draws the tree again as it was — expansion, scroll, and the current file — once the query is cleared', async () => { + const h = mountNavigator(A) + await revealed(h) + fireEvent.scroll(body(h), { target: { scrollTop: 64 } }) + await type(h, 'b', ['src/b.ts']) + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).scrollTop).toBe(0) + fireEvent.scroll(body(h), { target: { scrollTop: 12 } }) + act(() => { fireEvent.click(h.view.getByRole('button', { name: zh['search.clear'] })) }) + expect(document.activeElement).toBe(field(h)) + expect(status(h)).toBe('') + expect(body(h).getAttribute('data-files-view')).toBe('tree') + expect(body(h).scrollTop).toBe(64) + expect(h.instance.getSnapshot().byPane[PANE]?.tree?.expanded).toEqual([ROOT, `${ROOT}/src`]) + expect(body(h).querySelector('[aria-current="true"]')?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src/a.ts`) + await type(h, 'b') + expect(body(h).scrollTop).toBe(0) + // A remount during a search restores the results' own offset. + fireEvent.scroll(body(h), { target: { scrollTop: 30 } }) + h.view.unmount() + const back = h.remount() + expect(back.container.querySelector('[data-files-body]')?.scrollTop).toBe(30) + // New results start at their top. + await settled(() => { h.face.setQuery(PANE, ROOT, 'bb') }) + expect(back.container.querySelector('[data-files-body]')?.scrollTop).toBe(0) + }) + + it('says when nothing matched, with an information button whose tooltip names which of hidden entries, excluded paths, and ignored ones the search left out', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'zzz') + expect(body(h).textContent).toBe(zh['search.empty']) + expect(emptyHint(h)).toBe(zh['search.emptyHint.all']) + expect(status(h)).toBe(t('search.results', { count: '0' })) + const settle = async (preferences: Partial): Promise => { + await settled(() => { h.face.setSearchPreferences(ROOT, preferences) }) + expect(body(h).textContent).toBe(zh['search.empty']) + return emptyHint(h) + } + expect(await settle({ showHidden: true })).toBe(zh['search.emptyHint.excludedIgnored']) + expect(requests(h).at(-1)).toMatchObject({ excludedPaths: enabledPaths(defaultRules()), includeHidden: true }) + expect(await settle({ rules: [] })).toBe(zh['search.emptyHint.ignored']) + expect(requests(h).at(-1)).toMatchObject({ excludedPaths: [], includeHidden: true }) + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.hiddenIgnored']) + // Turning ignore files off leaves out only what the other two settings take. + expect(await settle({ respectGitignore: false })).toBe(zh['search.emptyHint.hidden']) + expect(requests(h).at(-1)).toMatchObject({ respectGitignore: false }) + // With nothing excluded, hidden entries shown, and ignore files not respected, the search left nothing out. + expect(await settle({ showHidden: true })).toBeUndefined() + // A rule that is listed but off excludes nothing. + expect(await settle({ rules: [{ path: 'dist', enabled: false }] })).toBeUndefined() + // Leaving out hidden entries is the only thing that remains. + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.hidden']) + expect(await settle({ rules: defaultRules(), showHidden: true })).toBe(zh['search.emptyHint.excluded']) + expect(await settle({ showHidden: false })).toBe(zh['search.emptyHint.both']) + }) + + it('says below the results, matched or not, when only the first matches are drawn and when some directories were not searched', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const note = (row: string): string | null | undefined => body(h).querySelector(`[data-files-row="${row}"]`)?.textContent + h.searches.answerWith(answer(['src/a.ts', 'src/ab.ts'], { truncated: true })) + await type(h, 'a') + expect(note('search-truncated')).toBe(t('search.truncated', { count: '2' })) + expect(note('search-incomplete')).toBeUndefined() + expect(note('search-empty')).toBeUndefined() + h.searches.answerWith(answer(['src/a.ts'], { incomplete: true })) + await type(h, 'ab') + expect(note('search-truncated')).toBeUndefined() + expect(note('search-incomplete')).toBe(zh['search.incomplete']) + h.searches.answerWith(answer([], { truncated: true, incomplete: true })) + await type(h, 'zzz') + expect(body(h).textContent).toBe(`${zh['search.empty']}${t('search.truncated', { count: '0' })}${zh['search.incomplete']}`) + expect(emptyHint(h)).toBe(zh['search.emptyHint.all']) + }) + + it('keeps the last results drawn with a spinner while the next search runs, and draws only a spinner before the first answer', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const spinner = (): Element | null => h.view.container.querySelector('[data-files-search-status] [data-state="ongoing"]') + expect(spinner()).toBeNull() + h.searches.answerWith(undefined) + await type(h, 'a') + // Before the first answer the results area is empty: no tree, no note. + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).getAttribute('aria-busy')).toBe('true') + expect(body(h).textContent).toBe('') + expect(status(h)).toBe('') + expect(spinner()).not.toBeNull() + await settled(() => { h.searches.started[0]!.settle(answer(['src/a.ts'])) }) + expect(spinner()).toBeNull() + expect(body(h).getAttribute('aria-busy')).toBe('false') + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + // A newer search keeps those results and the count until its answer replaces them. + await type(h, 'b') + expect(spinner()).not.toBeNull() + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + expect(status(h)).toBe(t('search.results', { count: '1' })) + await settled(() => { h.searches.started[1]!.settle(answer([])) }) + expect(spinner()).toBeNull() + expect(status(h)).toBe(t('search.results', { count: '0' })) + }) + + it('says why a search failed in the results\' place, and searches again from its retry control', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + h.searches.answerWith({ ok: false, error: new RemoteError('workspace-file/not-found', 'no entry at "/work/app"', { path: '/work/app' }) }) + await type(h, 'a') + const failed = (): HTMLElement | null => body(h).querySelector('[data-files-row="search-failed"]') + // A classified failure reads as the tree's own line, not the Host's untranslated message. + expect(within(failed()!).getByRole('alert').textContent).toBe(t('search.failed', { message: t('error.notFound') })) + expect(status(h)).toBe('') + expect(paths(h)).toEqual([]) + h.searches.answerWith(answer(['src/a.ts'])) + const retry = within(failed()!).getByRole('button', { name: zh['search.retry'] }) + await settled(() => { fireEvent.click(retry) }) + expect(requests(h)).toHaveLength(2) + expect(requests(h)[1]).toEqual(requests(h)[0]) + expect(failed()).toBeNull() + expect(paths(h)).toEqual([`${ROOT}/src`, `${ROOT}/src/a.ts`]) + }) + + it('keeps the status line mounted as a live region while the query is blank, so a screen reader hears the first search', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const live = h.view.container.querySelector('[data-files-search-status]') + expect(live?.getAttribute('aria-live')).toBe('polite') + expect(live?.textContent).toBe('') + await type(h, 'a', ['a.ts']) + expect(h.view.container.querySelector('[data-files-search-status]')).toBe(live) + expect(live?.textContent).toBe(t('search.results', { count: '1' })) + await type(h, '') + expect(h.view.container.querySelector('[data-files-search-status]')).toBe(live) + expect(live?.textContent).toBe('') + }) +}) + +describe('the hidden-entry control', () => { + it('leaves hidden entries out of the tree and the search until pressed, and shows them in both while pressed', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const eye = (): HTMLElement => h.view.container.querySelector('[data-files-show-hidden]')! + expect(eye().getAttribute('aria-pressed')).toBe('false') + expect(eye().getAttribute('aria-label')).toBe(zh['search.showHidden']) + // The name stays fixed; only `aria-pressed` reports the state. + expect(paths(h)).not.toContain(`${ROOT}/.env`) + act(() => { fireEvent.click(eye()) }) + expect(eye().getAttribute('aria-pressed')).toBe('true') + expect(eye().getAttribute('aria-label')).toBe(zh['search.showHidden']) + expect(paths(h)).toContain(`${ROOT}/.env`) + await type(h, 'env', ['.env']) + expect(requests(h)[0]?.includeHidden).toBe(true) + expect(paths(h)).toEqual([`${ROOT}/.env`]) + // Changing it during a search searches again at once. + act(() => { fireEvent.click(eye()) }) + expect(requests(h)[1]?.includeHidden).toBe(false) + }) + + it('says a directory holding only hidden entries holds hidden entries, not that it is empty', async () => { + const h = mountNavigator('sidebar://files') + act(() => { h.instance.actions.shown(PANE, true) }) + await act(() => h.script.watches.ready(ROOT)) + await act(() => h.script.settle({ ok: true, value: { entries: [{ name: '.env', type: 'file', size: 1 }], truncated: false } })) + expect(body(h).querySelector('[data-files-row="empty"]')).toBeNull() + expect(body(h).querySelector('[data-files-row="hidden-only"]')?.textContent).toBe(zh.emptyHidden) + act(() => { fireEvent.click(h.view.container.querySelector('[data-files-show-hidden]')!) }) + expect(body(h).querySelector('[data-files-row="hidden-only"]')).toBeNull() + expect(paths(h)).toEqual([`${ROOT}/.env`]) + }) + + it('applies exclusions only to the search, so the tree still lists excluded directories', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + expect(paths(h)).toContain(`${ROOT}/node_modules`) + await type(h, 'x') + expect(requests(h)[0]?.excludedPaths).toContain('node_modules') + await type(h, '') + expect(paths(h)).toContain(`${ROOT}/node_modules`) + }) + + it('shares one workspace\'s choice across Sessions rooted there, and not with another workspace', async () => { + const book = memoryBook() + const one = mountNavigator('sidebar://files', {}, ROOT, book) + const two = mountNavigator('sidebar://files', {}, `${ROOT}/`, book) + const other = mountNavigator('sidebar://files', {}, '/work/other', book) + act(() => { + for (const h of [one, two, other]) h.instance.actions.shown(PANE, true) + }) + const eye = (h: Mounted): string | null => h.view.container.querySelector('[data-files-show-hidden]')!.getAttribute('aria-pressed') + act(() => { fireEvent.click(one.view.container.querySelector('[data-files-show-hidden]')!) }) + expect([eye(one), eye(two), eye(other)]).toEqual(['true', 'true', 'false']) + }) +}) + +describe('the settings panel', () => { + /** Open the panel from the magnifier. */ + function open(h: Mounted): HTMLElement { + pointerClick(settingsButton(h)) + expect(settingsButton(h).getAttribute('aria-expanded')).toBe('true') + return dialog(h)! + } + const stored = (h: Mounted) => h.book.source(ROOT).getSnapshot() + + it.each(['pointer', 'Enter', ' '] as const)('saves checkbox edits when the magnifier is activated with %j and searches with the saved rules', async (gesture) => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + const toggle = (): void => { + if (gesture === 'pointer') pointerClick(settingsButton(h)) + else keyboardClick(settingsButton(h), gesture) + } + toggle() + const checkbox = within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) }) + pointerClick(checkbox) + expect(document.activeElement).toBe(checkbox) + expect(checkbox.checked).toBe(false) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + expect(requests(h)).toHaveLength(1) + + toggle() + expect(dialog(h)).toBeNull() + expect(settingsButton(h).getAttribute('aria-expanded')).toBe('false') + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(document.activeElement).toBe(settingsButton(h)) + expect(requests(h)).toEqual([requests(h)[0], { + query: 'a', excludedPaths: enabledPaths(defaultRules()).filter(path => path !== 'dist'), includeHidden: false, respectGitignore: true, + }]) + + toggle() + expect(within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })).toHaveProperty('checked', false) + }) + + it('keeps added and removed paths when the magnifier closes a panel without a query', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + pointerClick(settingsButton(h)) + const panel = dialog(h)! + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + act(() => { + fireEvent.change(add, { target: { value: './cache/' } }) + fireEvent.keyDown(add, { key: 'Enter' }) + }) + pointerClick(within(panel).getByRole('button', { name: t('settings.remove', { path: 'build' }) })) + expect(document.activeElement).toBe(add) + expect(stored(h).rules.map(rule => rule.path)).not.toContain('cache') + expect(stored(h).rules.map(rule => rule.path)).toContain('build') + + pointerClick(settingsButton(h)) + expect(dialog(h)).toBeNull() + expect(stored(h).rules[0]).toEqual({ path: 'cache', enabled: true }) + expect(stored(h).rules.map(rule => rule.path)).not.toContain('build') + pointerClick(settingsButton(h)) + expect(within(dialog(h)!).getByRole('checkbox', { name: t('settings.toggle', { path: 'cache' }) })).toHaveProperty('checked', true) + expect(within(dialog(h)!).queryByRole('checkbox', { name: t('settings.toggle', { path: 'build' }) })).toBeNull() + expect(h.search).not.toHaveBeenCalled() + }) + + it('opens from the magnifier with the add field focused, and saves on its close control, on Escape, and when focus leaves it', async () => { + const h = mountNavigator('sidebar://files') + h.row.width = 480 + await shown(h) + // Pressing the magnifier on a closed panel takes the keyboard as any button does. + expect(fireEvent.mouseDown(settingsButton(h))).toBe(true) + let panel = open(h) + expect(within(panel).getByText(zh['settings.title'])).toBeTruthy() + expect(document.activeElement).toBe(within(panel).getByRole('textbox', { name: zh['settings.add'] })) + expect(h.view.container.querySelectorAll('[data-files-show-hidden]')).toHaveLength(1) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + // Nothing is written while the panel is open. + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(dialog(h)).toBeNull() + expect(document.activeElement).toBe(settingsButton(h)) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + + panel = open(h) + pointerClick(within(panel).getByRole('button', { name: t('settings.remove', { path: 'build' }) })) + expect(dialog(h)).not.toBeNull() + act(() => { fireEvent.keyDown(within(panel).getByRole('textbox'), { key: 'Escape' }) }) + expect(dialog(h)).toBeNull() + // The overlaying navigator stays: the panel kept the Escape. + expect(h.view.container.querySelector('[data-files-navigator]')).not.toBeNull() + expect(stored(h).rules.map(rule => rule.path)).not.toContain('build') + + panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'coverage' }) })) + act(() => { body(h).focus() }) + expect(dialog(h)).toBeNull() + expect(stored(h).rules.find(rule => rule.path === 'coverage')?.enabled).toBe(false) + + // Closing without an edit writes nothing; the magnifier closes it too. + const before = stored(h) + open(h) + pointerClick(settingsButton(h)) + expect(dialog(h)).toBeNull() + expect(stored(h)).toBe(before) + }) + + it('shows the restore control whenever the list differs from the defaults, and replaces the list with the defaults', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + const restore = (): HTMLElement | null => within(panel).queryByRole('button', { name: zh['settings.restore'] }) + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + const rules = (): string[] => [...panel.querySelectorAll('[data-files-rule]')].map(row => row.getAttribute('data-files-rule')!) + const defaults = rules() + const type = (value: string): void => { + act(() => { fireEvent.change(add, { target: { value } }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + } + expect(restore()).toBeNull() + // A custom path alone differs from the defaults. + type('out') + expect(restore()).not.toBeNull() + act(() => { fireEvent.click(within(panel).getByRole('button', { name: t('settings.remove', { path: 'out' }) })) }) + expect(document.activeElement).toBe(add) + expect(restore()).toBeNull() + // A default added again moves to the top, so the order differs. + type('dist') + expect(rules()[0]).toBe('dist') + expect(restore()).not.toBeNull() + act(() => { fireEvent.click(within(panel).getByRole('button', { name: t('settings.remove', { path: 'node_modules' }) })) }) + act(() => { fireEvent.click(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: '.git' }) })) }) + type('out') + act(() => { fireEvent.click(restore()!) }) + expect(document.activeElement).toBe(add) + expect(restore()).toBeNull() + expect(rules()).toEqual(defaults) + expect(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: '.git' }) })).toHaveProperty('checked', true) + }) + + it('refuses an invalid path where it was typed, and adds a valid one at the top', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + const add = within(panel).getByRole('textbox', { name: zh['settings.add'] }) + act(() => { fireEvent.change(add, { target: { value: '../x' } }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + expect(within(panel).getByRole('alert').textContent).toBe(zh['settings.invalid.parent']) + expect(add.getAttribute('aria-invalid')).toBe('true') + act(() => { fireEvent.change(add, { target: { value: 'tmp/' } }) }) + expect(within(panel).queryByRole('alert')).toBeNull() + act(() => { fireEvent.keyDown(add, { key: 'a' }) }) + act(() => { fireEvent.keyDown(add, { key: 'Enter' }) }) + expect(add.value).toBe('') + expect(panel.querySelector('[data-files-rule]')?.getAttribute('data-files-rule')).toBe('tmp') + }) + + it('saves only the rules on close, keeping a hidden-entry choice made while the panel was open', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + act(() => { h.face.setSearchPreferences(ROOT, { showHidden: true }) }) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(stored(h).showHidden).toBe(true) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + }) + + it('saves the draft when the eye is clicked without losing the hidden-entry change', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + const panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + const eye = h.view.getByRole('button', { name: zh['search.showHidden'] }) + pointerClick(eye) + expect(dialog(h)).toBeNull() + expect(document.activeElement).toBe(eye) + expect(eye.getAttribute('aria-pressed')).toBe('true') + expect(stored(h).showHidden).toBe(true) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(paths(h)).toContain(`${ROOT}/.env`) + expect(within(open(h)).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })).toHaveProperty('checked', false) + }) + + it('respects .gitignore until its checkbox is cleared, saving the choice at once and searching again with it', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + expect(requests(h)[0]?.respectGitignore).toBe(true) + const panel = open(h) + const gitignore = within(panel).getByRole('checkbox', { name: zh['settings.respectGitignore'] }) + expect(gitignore.checked).toBe(true) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(gitignore) + // Saved while the panel is open, unlike the rules, which wait for it to close. + expect(gitignore.checked).toBe(false) + expect(stored(h).respectGitignore).toBe(false) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(true) + expect(requests(h)[1]).toMatchObject({ respectGitignore: false, excludedPaths: enabledPaths(defaultRules()) }) + expect(dialog(h)).not.toBeNull() + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(stored(h)).toMatchObject({ respectGitignore: false }) + expect(stored(h).rules.find(rule => rule.path === 'dist')?.enabled).toBe(false) + expect(within(open(h)).getByRole('checkbox', { name: zh['settings.respectGitignore'] })).toHaveProperty('checked', false) + }) + + it('searches again with the saved rules when the panel closes during a search', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + await type(h, 'a') + const panel = open(h) + pointerClick(within(panel).getByRole('checkbox', { name: t('settings.toggle', { path: 'dist' }) })) + pointerClick(within(panel).getByRole('button', { name: zh['settings.close'] })) + expect(requests(h)[1]?.excludedPaths).not.toContain('dist') + }) +}) + +describe('the keyboard', () => { + it('walks from the field through the rows with ↓ and ↑, back to the field from the first row', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + const rows = [...body(h).querySelectorAll('[data-files-path] > div > button')] + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(rows[0]) + act(() => { fireEvent.keyDown(rows[0]!, { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(rows[1]) + act(() => { fireEvent.keyDown(rows[1]!, { key: 'ArrowDown', shiftKey: true }) }) + expect(document.activeElement).toBe(rows[1]) + act(() => { fireEvent.keyDown(rows[1]!, { key: 'ArrowUp' }) }) + act(() => { fireEvent.keyDown(rows[0]!, { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + // Past the last row there is nowhere to go; the separator's arrows are its own. + const last = rows.at(-1)! + act(() => { last.focus() }) + act(() => { fireEvent.keyDown(last, { key: 'ArrowDown' }) }) + expect(document.activeElement).toBe(last) + act(() => { fireEvent.keyDown(h.view.getByRole('separator'), { key: 'ArrowDown' }) }) + // The rows are buttons, so Enter opens a file as a click does. + expect(last.tagName).toBe('BUTTON') + }) + + it('leaves ↓ to an input method composing text, and to a key someone in the navigator already handled', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown', isComposing: true }) }) + expect(document.activeElement).toBe(field(h)) + const keep = (event: KeyboardEvent): void => { event.preventDefault() } + field(h).addEventListener('keydown', keep) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + field(h).removeEventListener('keydown', keep) + expect(document.activeElement).toBe(field(h)) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + expect(document.activeElement).not.toBe(field(h)) + }) + + it('closes the settings on Escape first, then clears the query, and only then lets the overlay close', async () => { + const h = mountNavigator('sidebar://files') + h.row.width = 480 + await shown(h) + await type(h, 'a') + act(() => { fireEvent.click(settingsButton(h)) }) + act(() => { fireEvent.keyDown(document.activeElement!, { key: 'Escape' }) }) + expect(dialog(h)).toBeNull() + expect(field(h).value).toBe('a') + // An Escape someone in the navigator already kept does not clear it. + const keep = (event: KeyboardEvent): void => { event.preventDefault() } + field(h).addEventListener('keydown', keep) + act(() => { fireEvent.keyDown(field(h), { key: 'Escape' }) }) + field(h).removeEventListener('keydown', keep) + expect(field(h).value).toBe('a') + act(() => { fireEvent.keyDown(body(h), { key: 'Escape' }) }) + expect(field(h).value).toBe('') + expect(document.activeElement).toBe(field(h)) + expect(h.view.container.querySelector('[data-files-navigator]')).not.toBeNull() + act(() => { fireEvent.keyDown(field(h), { key: 'Escape' }) }) + expect(h.view.container.querySelector('[data-files-navigator]')).toBeNull() + }) + + it('keeps the keyboard where the reader moved it as the view switches to the results and back, each with its own scroll', async () => { + const h = mountNavigator(A) + await revealed(h) + fireEvent.scroll(body(h), { target: { scrollTop: 64 } }) + const first = body(h).querySelector('[data-files-path] > div > button')! + act(() => { first.focus() }) + act(() => { fireEvent.keyDown(first, { key: 'ArrowUp' }) }) + expect(document.activeElement).toBe(field(h)) + await type(h, 'b', ['src/b.ts']) + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(field(h)) + expect(body(h).getAttribute('data-files-view')).toBe('search') + expect(body(h).scrollTop).toBe(0) + act(() => { fireEvent.keyDown(field(h), { key: 'ArrowDown' }) }) + const result = document.activeElement + expect(result?.closest('[data-files-path]')?.getAttribute('data-files-path')).toBe(`${ROOT}/src`) + // Escape on a result row clears the text and hands the keyboard to the field. + act(() => { fireEvent.keyDown(result!, { key: 'Escape' }) }) + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(field(h)) + expect(body(h).getAttribute('data-files-view')).toBe('tree') + expect(body(h).scrollTop).toBe(64) + }) + + it('carries the search field\'s keyboard focus to the pane\'s next drawing in the same task only', async () => { + const h = mountNavigator('sidebar://files') + await shown(h) + act(() => { field(h).focus() }) + h.view.unmount() + const back = h.remount() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(within(back.container).getByRole('searchbox')) + back.unmount() + await act(async () => { await Promise.resolve() }) + h.remount() + await act(async () => { await Promise.resolve() }) + expect(document.activeElement).toBe(document.body) + }) +}) diff --git a/packages/client/ui-sidebar-files/tests/store.client.spec.ts b/packages/client/ui-sidebar-files/tests/store.client.spec.ts index cadf73fe6e..27df4c170a 100644 --- a/packages/client/ui-sidebar-files/tests/store.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/store.client.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { createFilesStore } from '../src/client/store.ts' import { DEFAULT_NAVIGATOR_WIDTH } from '../src/client/store.ts' -import type { DirLevel } from '../src/client/store.ts' +import type { DirLevel, FilesSearchResult } from '../src/client/store.ts' import type { PaneId } from '@deepseek-ai/dsh-client-ui-dockkit' const ROOT = '/work/app' @@ -22,13 +22,29 @@ describe('createFilesStore', () => { expect(second.getSnapshot().byPane[PANE]).toBeUndefined() }) + it('keeps each pane\'s search-bar choice independent without changing its search', () => { + const store = createFilesStore().create() + const other = 'pane-2' as PaneId + store.actions.start(PANE, ROOT) + store.actions.start(other, ROOT) + store.actions.queried(PANE, 'target') + store.actions.searching(PANE) + const search = store.getSnapshot().byPane[PANE]!.search + store.actions.searchBarShown(PANE, true) + expect(store.getSnapshot().byPane[PANE]!.searchBarOpen).toBe(true) + expect(store.getSnapshot().byPane[other]!.searchBarOpen).toBe(false) + store.actions.searchBarShown(PANE, false) + expect(store.getSnapshot().byPane[PANE]!.query).toBe('target') + expect(store.getSnapshot().byPane[PANE]!.search).toBe(search) + }) + it('seeds a pane at its root with the root expanded and nothing loaded', () => { const store = createFilesStore().create() const { actions } = store const getSnapshot = (): ReturnType => store.getSnapshot() actions.start(PANE, ROOT) expect(getSnapshot().byPane[PANE]).toEqual({ - open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, + open: undefined, width: DEFAULT_NAVIGATOR_WIDTH, query: '', searchBarOpen: false, search: undefined, tree: { root: ROOT, levels: {}, expanded: [ROOT], autoRefresh: true }, }) }) @@ -147,12 +163,12 @@ describe('createFilesStore', () => { const { actions } = store actions.shown(PANE, true) actions.resized(PANE, 320) - expect(store.getSnapshot().byPane[PANE]).toEqual({ open: true, width: 320, tree: undefined }) + expect(store.getSnapshot().byPane[PANE]).toEqual({ open: true, width: 320, tree: undefined, query: '', searchBarOpen: false, search: undefined }) actions.start(PANE, ROOT) actions.loaded(PANE, ROOT, LEVEL) actions.start(PANE, '/work/other') expect(store.getSnapshot().byPane[PANE]).toEqual({ - open: true, width: 320, + open: true, width: 320, query: '', searchBarOpen: false, search: undefined, tree: { root: '/work/other', levels: {}, expanded: ['/work/other'], autoRefresh: true }, }) }) @@ -171,4 +187,51 @@ describe('createFilesStore', () => { actions.forget(PANE) expect(Object.keys(getSnapshot().byPane)).toEqual(['pane-2']) }) + + it('keeps a pane\'s search apart from its tree, and drops a result the query already ended', () => { + const store = createFilesStore().create() + const { actions } = store + const getSnapshot = (): ReturnType => store.getSnapshot() + const search = () => getSnapshot().byPane[PANE]?.search + const found = () => { + const result = search()?.result + return result?.kind === 'found' ? result : undefined + } + const result = (query: string): FilesSearchResult => ({ + kind: 'found', query, count: 0, truncated: false, incomplete: false, hiddenLeftOut: true, excluded: true, ignored: true, + tree: { root: ROOT, levels: {}, expanded: [ROOT, `${ROOT}/src`], autoRefresh: false }, + }) + actions.searching(PANE) + actions.searched(PANE, result('a')) + actions.searchToggled(PANE, ROOT) + expect(getSnapshot().byPane).toEqual({}) + actions.queried(PANE, ' ') + actions.searching(PANE) + actions.searched(PANE, result('a')) + expect(getSnapshot().byPane[PANE]).toMatchObject({ query: ' ', search: undefined }) + actions.queried(PANE, 'a') + expect(search()).toBeUndefined() + // A search under way before its first answer has nothing to draw yet. + actions.searching(PANE) + expect(search()).toEqual({ pending: true, result: undefined }) + actions.searchToggled(PANE, ROOT) + actions.searched(PANE, result('a')) + expect(search()?.pending).toBe(false) + actions.searchToggled(PANE, ROOT) + expect(found()?.tree.expanded).toEqual([`${ROOT}/src`]) + actions.searchToggled(PANE, ROOT) + expect(found()?.tree.expanded).toEqual([`${ROOT}/src`, ROOT]) + // Other text keeps the last result, pending, until the next is recorded. + actions.queried(PANE, 'ab') + actions.searching(PANE) + expect(search()).toMatchObject({ pending: true, result: { query: 'a' } }) + const failure = new RemoteError('gateway/internal', 'down', {}) + actions.searched(PANE, { kind: 'failed', query: 'ab', failure }) + expect(search()).toEqual({ pending: false, result: { kind: 'failed', query: 'ab', failure } }) + // A failed search has no tree to toggle. + actions.searchToggled(PANE, ROOT) + expect(search()?.result).toEqual({ kind: 'failed', query: 'ab', failure }) + actions.queried(PANE, '') + expect(search()).toBeUndefined() + }) }) diff --git a/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts b/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts index 8a95bf5ff4..09fbb72caf 100644 --- a/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts +++ b/packages/client/ui-sidebar-files/tests/workspace-tree.client.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import { makeTranslate, RemoteError } from '@deepseek-ai/dsh-client-test-runtime' import { zh } from '../src/client/locales.ts' import type { FilesTreeState } from '../src/client/store.ts' -import { parentOf, treeRootOf, workspaceDirectories, workspaceEntries } from '../src/client/workspace-tree.ts' +import { parentOf, searchDirectories, treeRootOf, workspaceDirectories, workspaceEntries } from '../src/client/workspace-tree.ts' const t = makeTranslate(zh) @@ -29,14 +29,15 @@ describe('workspace tree keys', () => { ['\\\\server\\share\\', '\\\\server\\share'], ])('keys root %j as %j, its entries one slash below it, and their parents back to the root as stored', (root, key) => { const tree = listed(root) - expect(workspaceEntries(tree.levels)).toEqual([ + expect(workspaceEntries(tree.levels, false)).toEqual([ { path: `${key}/src`, name: 'src', meta: { kind: 'directory' } }, { path: `${key}/pipe`, name: 'pipe', meta: { kind: 'other' } }, { path: `${key}/src/a.ts`, name: 'a.ts', meta: { kind: 'file' } }, ]) expect(parentOf(tree, `${key}/src`)).toBe(root) expect(parentOf(tree, `${key}/src/lib`)).toBe(`${key}/src`) - expect(Object.keys(workspaceDirectories(tree, t))).toEqual([key, `${key}/src`]) + expect(Object.keys(workspaceDirectories(tree, t, false))).toEqual([key, `${key}/src`]) + expect(Object.keys(searchDirectories(tree))).toEqual([key, `${key}/src`]) }) }) @@ -52,7 +53,7 @@ describe('workspaceDirectories', () => { '/r/c': { kind: 'failed', failure }, '/r/d': { kind: 'ready', level: { entries: [], truncated: false } }, }, - }, t) + }, t, false) expect(states).toEqual({ '/r': { failure: zh['error.notFound'], truncated: true }, '/r/a': { loading: true }, @@ -62,3 +63,37 @@ describe('workspaceDirectories', () => { }) }) }) + +describe('hidden entries', () => { + const tree: FilesTreeState = { + root: '/r', autoRefresh: true, expanded: ['/r', '/r/.git'], + levels: { + '/r': { kind: 'ready', level: { entries: [{ name: '.git', type: 'directory' }, { name: 'a.ts', type: 'file' }], truncated: false } }, + '/r/.git': { kind: 'ready', level: { entries: [{ name: '.keep', type: 'file' }], truncated: false } }, + }, + } + + it('leaves them out, and says a directory of only hidden entries holds some, until they are shown', () => { + expect(workspaceEntries(tree.levels, false).map(entry => entry.path)).toEqual(['/r/a.ts']) + expect(workspaceDirectories(tree, t, false)).toEqual({ '/r': {}, '/r/.git': { omitted: 'hidden' } }) + expect(workspaceEntries(tree.levels, true).map(entry => entry.path)).toEqual(['/r/.git', '/r/a.ts', '/r/.git/.keep']) + expect(workspaceDirectories(tree, t, true)).toEqual({ '/r': {}, '/r/.git': {} }) + }) + + it('leaves out the kept levels below a hidden directory once hidden entries are no longer shown', () => { + const levels: FilesTreeState['levels'] = { + '/r': { kind: 'ready', level: { entries: [{ name: '.config', type: 'directory' }, { name: 'src', type: 'directory' }], truncated: false } }, + '/r/.config': { kind: 'ready', level: { entries: [{ name: 'app', type: 'directory' }, { name: 'config.json', type: 'file' }], truncated: false } }, + '/r/.config/app': { kind: 'ready', level: { entries: [{ name: 'a.json', type: 'file' }], truncated: false } }, + '/r/.configs': { kind: 'ready', level: { entries: [{ name: 'kept.json', type: 'file' }], truncated: false } }, + '/r/src': { kind: 'ready', level: { entries: [{ name: 'b.ts', type: 'file' }], truncated: false } }, + } + // `.configs` shares the hidden directory's name as a prefix but is not below it. + expect(workspaceEntries(levels, false).map(entry => entry.path)).toEqual(['/r/src', '/r/.configs/kept.json', '/r/src/b.ts']) + expect(workspaceEntries(levels, true).map(entry => entry.path)).toContain('/r/.config/app/a.json') + }) + + it('draws a search result directory without matches below it as a selection', () => { + expect(searchDirectories(tree)).toEqual({ '/r': { omitted: 'unmatched' }, '/r/.git': { omitted: 'unmatched' } }) + }) +}) diff --git a/packages/experimental/liveshare/src/endpoint-classification.ts b/packages/experimental/liveshare/src/endpoint-classification.ts index a868012bd6..e817a48d82 100644 --- a/packages/experimental/liveshare/src/endpoint-classification.ts +++ b/packages/experimental/liveshare/src/endpoint-classification.ts @@ -139,6 +139,7 @@ export const VIEWER_ENDPOINT_CLASSES = { 'workspaceFiles/list': 'owner-only', // owner Workspace file access' 'workspaceFiles/read': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it 'workspaceFiles/readBytes': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it + 'workspaceFiles/search': 'owner-only', // owner Workspace file access 'workspaceFiles/stat': 'owner-only', // absolute paths reach files outside the Workspace, so no share offers it 'pluginManager/cancelInstall': 'owner-only', // owner plugin management 'pluginManager/inspect': 'owner-only', // owner plugin management 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 a882ea0ca9..36cbd48ee7 100644 --- a/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts +++ b/packages/extensions/cordis-client-runner/src/client/slot-catalog.ts @@ -4882,7 +4882,7 @@ export const CLIENT_SLOT_API: readonly ClientSlotEntry[] = [ ], replaceRisk: 'none', example: 'return {\n inject: [\'slots\'],\n apply(ctx) {\n ctx.slots.inject(\'sidebar.right.tab.files.actions\', () => ctx.slots.register(\n { name: \'sidebar.right.tab.files.actions\', id: \'my-entry\', order: 100, label: \'My entry\' },\n () => React.createElement(\'div\', null, \'hello\'),\n ))\n },\n}', - source: 'packages/client/ui-sidebar-files/src/client/index.ts:39', + source: 'packages/client/ui-sidebar-files/src/client/index.ts:46', }, { key: 'sidebar.right.tab.guide', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 0ac2e9e122..82efc1844f 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -4707,6 +4707,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ parameters: [{ name: 'workspaceFileScope', description: 'header-derived workspace root for the Session identity on the wire.' }, { name: 'path', description: 'workspace path, absolute or relative to the workspace root.' }, { name: 'signal', description: 'caller cancellation.' }], returns: 'the directory\'s children in the backend\'s stable name order, bounded by the entry cap.', }, + { + signature: '@Remote async search( workspaceFileScope: WorkspaceFileScope, request: WorkspaceFileSearchRequest, signal: AbortSignal, ): Promise', + description: 'Search files and their inferred ancestor directories with packaged ripgrep. Native ignore rules apply unless disabled; VCS metadata, symlinks and empty directories are absent. Within the bounded set of listed files, matches sort by depth, then workspace-relative path.', + parameters: [{ name: 'workspaceFileScope', description: 'header-derived workspace root for the Session identity on the wire.' }, { name: 'request', description: 'the query, literal exclusions, and hidden/ignore switches.' }, { name: 'signal', description: 'caller cancellation, forwarded to the subprocess; rejection preserves its reason.' }], + returns: 'matches capped by search.maxResults; incomplete marks excess rg files or exit 2.', + throws: ['RemoteError `gateway/bad-request`: the query is blank.', 'RemoteError `workspace-file/not-found`: the workspace root does not exist.', 'RemoteError `workspace-file/not-directory`: the workspace root is not a directory.', 'RemoteError `workspace-file/search-failed`: subprocess is missing, rg cannot launch or execute, or the search times out.'], + }, { signature: '@Remote({ mode: \'stream\' }) changes(workspaceFileScope: WorkspaceFileScope, path: string, signal: AbortSignal): AsyncIterable', description: 'Watch one file or a directory\'s direct entries in the Session\'s filesystem. Files use the backend\'s read authority; directories remain workspace-scoped.', @@ -10486,6 +10493,18 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'WorkspaceFileScope', declaration: 'export interface WorkspaceFileScope {\n readonly sessionId: SessionId;\n readonly workspaceRoot: string;\n}', }, + { + name: 'WorkspaceFileSearchMatch', + declaration: 'export interface WorkspaceFileSearchMatch {\n readonly path: string;\n readonly type: WorkspaceDirectoryEntry[\'type\'];\n}', + }, + { + name: 'WorkspaceFileSearchRequest', + declaration: 'export interface WorkspaceFileSearchRequest {\n readonly query: string;\n readonly excludedPaths: readonly string[];\n readonly includeHidden: boolean;\n readonly respectGitignore: boolean;\n}', + }, + { + name: 'WorkspaceFileSearchResult', + declaration: 'export interface WorkspaceFileSearchResult {\n readonly matches: readonly WorkspaceFileSearchMatch[];\n readonly truncated: boolean;\n readonly incomplete: boolean;\n}', + }, { name: 'WorkspaceFileStat', declaration: 'export interface WorkspaceFileStat {\n readonly absolutePath: string;\n readonly version: string;\n readonly bytes?: number;\n}', diff --git a/packages/fs/tool-fs-search/README.i18n.yaml b/packages/fs/tool-fs-search/README.i18n.yaml index b1c75185bb..804fb56a70 100644 --- a/packages/fs/tool-fs-search/README.i18n.yaml +++ b/packages/fs/tool-fs-search/README.i18n.yaml @@ -42,8 +42,8 @@ en: 5a30f023dd86c345 zh: 558b6e80c62648ba /deepseek-ai-dsh-tool-fs-search/understand-the-implementation/how-a-search-runs: - en: 7904c9f013272819 - zh: 656763e9a7e97c1e + en: f3fc47e0bec9091f + zh: af6723f131c40f10 /deepseek-ai-dsh-tool-fs-search/understand-the-implementation/native-mode-benchmark: en: 031654f59e63d07e zh: a3b488fb1880d2f5 diff --git a/packages/fs/tool-fs-search/README.md b/packages/fs/tool-fs-search/README.md index 4c26ffa018..790f620fb1 100644 --- a/packages/fs/tool-fs-search/README.md +++ b/packages/fs/tool-fs-search/README.md @@ -107,7 +107,7 @@ Local workspace discovery is naturally a process-backed `rg` workflow, and putti Without an explicit `path`, `glob` prunes unrelated subtrees for patterns such as `packages/core/src/*.ts` when every directory component is a plain relative name outside VCS metadata. Ordered ripgrep globs exclude the tree, admit directories with the prefix's distinct names, then apply the original file pattern. Same-named directories elsewhere may also be traversed, but only the original pattern admits files. The added arguments are capped at 8 KiB; larger sets use the original traversal. The search root, path separators, symlink handling, matching, and modification-time ordering stay unchanged; other patterns retain the original traversal. -Each call resolves the packaged binary (`@vscode/ripgrep`, or the executable's `-rg` sidecar in a pkg single-file runtime), prepends `--no-config` so a host `RIPGREP_CONFIG_PATH` cannot inject a `--pre` preprocessor into the unconfined spawn, and passes every model-controlled value as a plain argv element — no shell layer exists, so no quoting applies. Collect-mode budgets bound complete stdout and a stderr tail; a lossy stdout read fails as `SEARCH_RAW_OUTPUT_OVERFLOW` rather than parsing a silently-partial stream. The tools never read a raw spill path. +Each call resolves and starts the packaged binary through the shared [ripgrep library](../../util/ripgrep/README.md), which prepends `--no-config` to prevent configuration-driven preprocessors. Model-controlled values remain plain argv elements without shell quoting. Collect-mode budgets bound complete stdout and a stderr tail; a lossy stdout read fails as `SEARCH_RAW_OUTPUT_OVERFLOW` rather than parsing a silently-partial stream. The tools never read a raw spill path. ### Native-mode benchmark diff --git a/packages/fs/tool-fs-search/README.zh.md b/packages/fs/tool-fs-search/README.zh.md index 10cae42308..f39f31c57e 100644 --- a/packages/fs/tool-fs-search/README.zh.md +++ b/packages/fs/tool-fs-search/README.zh.md @@ -107,7 +107,7 @@ Node 部署在受支持的 macOS、Linux 与 Windows 目标上获得 `@vscode/ri 未显式提供 `path` 时,如果目录部分的每一项都是普通相对名称且不属于 VCS 元数据目录,`glob` 会为 `packages/core/src/*.ts` 这样的模式跳过无关子树。按顺序添加的 ripgrep glob 先排除目录树,再按前缀中去重后的名称放行目录,最后应用原始文件模式。其他位置的同名目录也可能被遍历,但文件仍只按原模式匹配。新增参数上限为 8 KiB,超过时沿用原遍历方式。搜索根目录、路径分隔符、符号链接处理、匹配规则和修改时间排序保持不变;其他模式仍按原方式遍历。 -每次调用解析打包二进制(`@vscode/ripgrep`,或 pkg 单文件运行时中可执行程序的 `-rg` 伴随文件),前置 `--no-config`,使宿主的 `RIPGREP_CONFIG_PATH` 无法向不受约束的 spawn 注入 `--pre` 预处理器,并把每个模型控制的值作为普通 argv 元素传入——不存在 shell 层,因此不涉及 shell 引号处理。collect 模式预算限制完整 stdout 与 stderr 尾部;lossy stdout 读取以 `SEARCH_RAW_OUTPUT_OVERFLOW` 失败,而不是解析静默不完整的流。工具从不读取原始 spill 路径。 +每次调用通过共享的 [ripgrep 库](../../util/ripgrep/README.zh.md) 解析并启动打包二进制,由它前置 `--no-config` 防止配置启用预处理程序。模型控制的值作为普通 argv 元素传入,不经过 shell 引号处理。collect 模式预算限制完整 stdout 与 stderr 尾部;lossy stdout 读取以 `SEARCH_RAW_OUTPUT_OVERFLOW` 失败,而不是解析静默不完整的流。工具从不读取原始 spill 路径。 ### Native 模式 benchmark diff --git a/packages/fs/tool-fs-search/package.json b/packages/fs/tool-fs-search/package.json index 29e776f7a3..1649d99a4c 100644 --- a/packages/fs/tool-fs-search/package.json +++ b/packages/fs/tool-fs-search/package.json @@ -32,8 +32,8 @@ ], "license": "MIT", "dependencies": { - "@vscode/ripgrep": "^1.18.0", - "@deepseek-ai/schemastery": "workspace:~" + "@deepseek-ai/schemastery": "workspace:~", + "@deepseek-ai/dsh-util-ripgrep": "workspace:*" }, "peerDependencies": { "@deepseek-ai/dsh-llm": "workspace:*", @@ -63,6 +63,7 @@ "@deepseek-ai/cordis": "workspace:~", "@deepseek-ai/dsh-scope": "workspace:*", "@deepseek-ai/dsh-working-directory": "workspace:*", - "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*" + "@deepseek-ai/dsh-agent-loop-testkit": "workspace:*", + "@vscode/ripgrep": "^1.18.0" } } diff --git a/packages/fs/tool-fs-search/src/search-core.ts b/packages/fs/tool-fs-search/src/search-core.ts index 794a5d43fe..970846b99a 100644 --- a/packages/fs/tool-fs-search/src/search-core.ts +++ b/packages/fs/tool-fs-search/src/search-core.ts @@ -19,9 +19,10 @@ * @module @deepseek-ai/dsh-tool-fs-search/search-core */ -import { existsSync } from 'node:fs' -import { isAbsolute, join, parse, relative, sep } from 'node:path' +import { isAbsolute, relative, sep } from 'node:path' import type { Context } from '@deepseek-ai/cordis' +import { spawnRipgrep } from '@deepseek-ai/dsh-util-ripgrep' +export { resolveRgPath } from '@deepseek-ai/dsh-util-ripgrep' import { HarnessError } from '@deepseek-ai/dsh-llm' import { ItemRetainer, TextRetainer } from '@deepseek-ai/dsh-output-retention' import type { RetainedItems } from '@deepseek-ai/dsh-output-retention' @@ -154,35 +155,6 @@ function completeStdout(toolName: string, stdout: SubprocessOutputRead, rawOutpu ) } -let rgPathPromise: Promise | undefined - -/** - * The packaged ripgrep binary path, resolved lazily once per process. - * - * A single-file runtime uses the executable's `-rg` sidecar because a native - * helper cannot be spawned from pkg's virtual filesystem. Node-mode builds - * fall back to the platform package selected by `@vscode/ripgrep`. Resolving - * at the call boundary keeps a missing or corrupt binary at the first search - * call as `SEARCH_FAILED`, rather than failing the Loader composition. - * - * @returns the packaged binary's absolute path; the memoized promise rejects - * when the platform package cannot be resolved. - */ -export function resolveRgPath(): Promise { - rgPathPromise ??= Promise.resolve().then(async () => { - const executable = parse(process.execPath) - const executableSidecar = process.platform === 'win32' - ? join(executable.dir, `${executable.name}-rg.exe`) - : `${process.execPath}-rg` - if ('pkg' in process && existsSync(executableSidecar)) return executableSidecar - const dependency = (await import('@vscode/ripgrep')).rgPath - return process.versions.electron === undefined - ? dependency - : dependency.replace(/\.asar(?=[\\/])/u, '.asar.unpacked') - }) - return rgPathPromise -} - /** * Run the packaged ripgrep binary with a plain argv vector and return its * complete raw stdout. The working directory is the calling agent's session @@ -236,8 +208,8 @@ export async function runRipgrep( : await ctx.workingDirectory.ensure(exec.agent, exec.signal) let handle: SubprocessHandle try { - handle = ctx.subprocess.spawn({ - argv: [await resolveRgPath(), '--no-config', ...argv], + handle = await spawnRipgrep(ctx.subprocess, { + argv, cwd: workdir, stdio: { stdin: 'ignore', diff --git a/packages/fs/tool-fs-search/tsconfig.json b/packages/fs/tool-fs-search/tsconfig.json index 4e6b7268ce..5971d17453 100644 --- a/packages/fs/tool-fs-search/tsconfig.json +++ b/packages/fs/tool-fs-search/tsconfig.json @@ -43,6 +43,9 @@ }, { "path": "../../session/working-directory" + }, + { + "path": "../../util/ripgrep" } ] } diff --git a/packages/util/README.i18n.yaml b/packages/util/README.i18n.yaml index f726477c4b..9a1e6e84a4 100644 --- a/packages/util/README.i18n.yaml +++ b/packages/util/README.i18n.yaml @@ -3,20 +3,20 @@ # After editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/util/README.md /: - en: 2994957e73b4e3e2 - zh: 3bf7bbfc3efeab31 + en: 4e92398c76bf480f + zh: 18840c65a44a8c38 /util-shared-utilities: en: 7283f2afb343d150 zh: 32c56bd67c0314c6 /util-shared-utilities/summary: - en: ed8863365a68c0ef - zh: 4bcff265d4d5694e + en: e1aa918f27dccf20 + zh: 7d415fdc8c0248ed /util-shared-utilities/table-of-contents: en: 1eb35b015a6c423f zh: a8a3dceee2c9e943 /util-shared-utilities/packages: - en: e345b399695a4e93 - zh: 179fee3e2c4d90cc + en: 461990a6f0e944bd + zh: 788c91b2b1cf0426 /util-shared-utilities/related-documentation: en: 432ae81110914571 zh: c5bf4efc007311f3 diff --git a/packages/util/README.md b/packages/util/README.md index ac3e59f3a1..2635eac7df 100644 --- a/packages/util/README.md +++ b/packages/util/README.md @@ -1,5 +1,5 @@ --- -description: "Package map for shared utilities: atomic file writes, branded ids, deques, JSON values, harness home paths, launch environment, native commands, output retention, time and zone vocabulary, timeouts, and official package lists." +description: "Package map for shared utilities: atomic file writes, branded ids, deques, JSON values, harness home paths, launch environment, native commands, packaged ripgrep, output retention, time and zone vocabulary, timeouts, and official package lists." kind: "package-group" --- @@ -9,7 +9,7 @@ English | [中文](README.zh.md) ## Summary -The `util/` group gives capability packages shared mechanical primitives instead of duplicate implementations. It covers atomic writes, branded ids, deques, lossless JSON values, UUIDs, Harness-home paths, launch environments, outbound proxy policy, native commands, output retention, time-zone, instant, and span vocabulary, and timeout handling. Every root entry here is a library: it registers no product service or event, and the consuming capability retains the business semantics. The exception is `official-bundles`: instead of a mechanical primitive, it holds the installation's and the plugin manager's official package lists as data their consumers apply. +The `util/` group gives capability packages shared mechanical primitives instead of duplicate implementations. It covers atomic writes, branded ids, deques, lossless JSON values, UUIDs, Harness-home paths, launch environments, outbound proxy policy, native commands, packaged ripgrep execution, output retention, time-zone, instant, and span vocabulary, and timeout handling. Every root entry here is a library: it registers no product service or event, and the consuming capability retains the business semantics. The exception is `official-bundles`: instead of a mechanical primitive, it holds the installation's and the plugin manager's official package lists as data their consumers apply. ## Table of Contents @@ -42,6 +42,7 @@ Each package provides one primitive or one data set; open a package page for how | [`atomic-write/`](atomic-write/README.md) | Atomic file replacement and cross-process writer locking | | [`lazy-require/`](lazy-require/README.md) | Loads CommonJS-compatible Host dependencies on first use with caller-relative resolution | | [`native-command/`](native-command/README.md) | Runs host-native commands directly, never through a shell string | +| [`ripgrep/`](ripgrep/README.md) | Resolves the packaged ripgrep binary, spawns it through the caller's subprocess service, and streams its output records | | [`workspace-path/`](workspace-path/README.md) | Provides browser-safe Workspace path and display helpers | | [`code-language/`](code-language/README.md) | Maps a filename suffix to the syntax-highlighting language that the Code preview, diff review, and the read card render | | [`output-retention/`](output-retention/README.md) | Bounds model-facing output and reports exact omission metadata | diff --git a/packages/util/README.zh.md b/packages/util/README.zh.md index e59f702191..0f0ddfc17d 100644 --- a/packages/util/README.zh.md +++ b/packages/util/README.zh.md @@ -1,5 +1,5 @@ --- -description: "共享工具家族的包映射:原子文件写入、品牌化 id、双端队列、JSON 值、harness 主目录路径、启动环境、原生命令、输出保留、时间与时区词汇、超时,以及官方包列表。" +description: "共享工具家族的包映射:原子文件写入、品牌化 id、双端队列、JSON 值、harness 主目录路径、启动环境、原生命令、打包 ripgrep、输出保留、时间与时区词汇、超时,以及官方包列表。" kind: "package-group" --- @@ -9,7 +9,7 @@ kind: "package-group" ## 概述 -`util/` 组为能力包提供共享的机制原语,避免重复实现。它涵盖原子写入、品牌化 id、双端队列、无损 JSON 值、UUID、Harness home 路径、启动环境、出站代理策略、原生命令、输出保留、时区、时刻与时间段词汇,以及超时处理。这里的每个根入口都是库:它不注册产品服务或事件,业务语义仍由消费它的能力负责。例外是 `official-bundles`:它不是机制原语,而是以纯数据形式保存安装方和插件管理器的官方包列表,由各自的消费方应用。 +`util/` 组为能力包提供共享的机制原语,避免重复实现。它涵盖原子写入、品牌化 id、双端队列、无损 JSON 值、UUID、Harness home 路径、启动环境、出站代理策略、原生命令、打包 ripgrep 的执行、输出保留、时区、时刻与时间段词汇,以及超时处理。这里的每个根入口都是库:它不注册产品服务或事件,业务语义仍由消费它的能力负责。例外是 `official-bundles`:它不是机制原语,而是以纯数据形式保存安装方和插件管理器的官方包列表,由各自的消费方应用。 ## 目录 @@ -42,6 +42,7 @@ kind: "package-group" | [`atomic-write/`](atomic-write/README.zh.md) | 原子文件替换与跨进程写锁 | | [`lazy-require/`](lazy-require/README.zh.md) | 在首次使用时按调用方位置加载兼容 CommonJS 的 Host 依赖 | | [`native-command/`](native-command/README.zh.md) | 直接运行宿主原生命令,绝不拼 shell 字符串 | +| [`ripgrep/`](ripgrep/README.zh.md) | 解析打包的 ripgrep 二进制,通过调用方的子进程服务启动它,并流式读取输出记录 | | [`workspace-path/`](workspace-path/README.zh.md) | 提供浏览器安全的 Workspace 路径与显示辅助函数 | | [`code-language/`](code-language/README.zh.md) | 把文件名后缀映射为 Code 预览、diff 审阅与 read 卡片所渲染的语法高亮语言 | | [`output-retention/`](output-retention/README.zh.md) | 限制面向模型的输出并报告精确的省略元数据 | diff --git a/packages/util/ripgrep/README.i18n.yaml b/packages/util/ripgrep/README.i18n.yaml new file mode 100644 index 0000000000..532bd49d2a --- /dev/null +++ b/packages/util/ripgrep/README.i18n.yaml @@ -0,0 +1,37 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/util/ripgrep/README.md +/: + en: bc82952963b17d8c + zh: 675b139ebabdc650 +/deepseek-ai-dsh-util-ripgrep: + en: b04d02f7de33360d + zh: 1cfe8f875568591b +/deepseek-ai-dsh-util-ripgrep/summary: + en: bb3d7c655f3adebc + zh: bffe6ea95d686080 +/deepseek-ai-dsh-util-ripgrep/table-of-contents: + en: d152484eb41ac6b4 + zh: 09388d293f9be9cb +/deepseek-ai-dsh-util-ripgrep/use-this-package: + en: 53799d1dd3fc2137 + zh: da69fc599badb99d +/deepseek-ai-dsh-util-ripgrep/understand-the-implementation: + en: b0b0e642476cd3a3 + zh: fa265461d2dabe03 +/deepseek-ai-dsh-util-ripgrep/further-exploration: + en: a95949bcc607ac71 + zh: da783fcb920b894f +/deepseek-ai-dsh-util-ripgrep/model-experience: + en: 9df66fc6f8d80d3e + zh: cf37a67237e3c082 +/deepseek-ai-dsh-util-ripgrep/model-experience/kv-cache-effect: + en: 3b134ccd04fc3436 + zh: 46c862e01cb4b9be +/deepseek-ai-dsh-util-ripgrep/known-limitations-and-deferred-work: + en: 1bfaa2f90e3c339b + zh: da09b60f225fcdf6 +/deepseek-ai-dsh-util-ripgrep/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: e88aeb617ffb74ea diff --git a/packages/util/ripgrep/README.md b/packages/util/ripgrep/README.md new file mode 100644 index 0000000000..17bd06b249 --- /dev/null +++ b/packages/util/ripgrep/README.md @@ -0,0 +1,79 @@ +--- +description: "Run the packaged ripgrep binary through the composed subprocess provider, with bounded streaming for file-search consumers." +kind: "package-library" +--- + +# @deepseek-ai/dsh-util-ripgrep + +English | [中文](README.zh.md) + +## Summary + +Use this library to start packaged ripgrep without a shell or a system `rg` installation. `tool-fs-search` uses collected output; `workspace-files` reads file paths incrementally and stops at its configured cap. Callers supply the working directory, arguments, stream modes, termination grace and cancellation signal, and own exit-code interpretation. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +Import `spawnRipgrep` from this package and pass the composed subprocess service plus an explicit `SubprocessSpawnSpec`; its `argv` contains only rg arguments. The returned handle exposes collected output or piped streams as requested. With piped stdout, `readRipgrepLines` delivers newline- or NUL-separated UTF-8 records; returning false from the callback terminates rg and suppresses remaining records. It awaits stdout, the process outcome and managed-range quiescence before returning. Callback, stream and provider failures reject after cleanup. Callers classify exit codes and cancellation using their own signal. + +`resolveRgPath` is available independently for consumers that only need the executable path. Resolution and spawn failures reject the call; they do not prevent importing the package. This library is a dependency, not a profile plugin. + +----- + + +## Understand the implementation + +
    +Implementation internals — click to expand + +The resolver selects the executable's existing `-rg` sidecar in a single-file runtime, otherwise the `@vscode/ripgrep` platform package. Electron paths replace `app.asar` with `app.asar.unpacked`. Every spawn prepends `--no-config` so an ambient rg configuration cannot enable a preprocessor. The subprocess provider owns environment scrubbing and termination; the caller owns deadlines and result budgets. See [the implementation](src/index.ts). + +
    + +----- + + +## Further Exploration + +- [Subprocess provider contract](../../subprocess/subprocess/README.md) — explicit spawn specifications and managed process ranges. +- [Model search tools](../../fs/tool-fs-search/README.md) — collected output, tool errors and result retention. +- [Workspace file search](../../api/workspace-files/README.md#search) — native ignore rules and shallow-first file/ancestor matching. + +----- + + +## Model Experience + +Indirectly, through the search tools that consume the subprocess output. + +#### KV Cache effect + +None directly; consumers own model-visible results and request assembly. + +## Known Limitations and Deferred Work + + + +- **Co-located executable required** — resolution uses the Host's packaged binary path. A remote subprocess provider without that binary fails; there is no system-rg lookup or filesystem-traversal fallback. +- **Record buffering** — streaming retains one incomplete record plus the current stream chunk; callers whose filenames may contain newlines use NUL separators rather than newlines. Records decode as UTF-8, so a filename that is not valid UTF-8 arrives with U+FFFD replacements and cannot be opened by that string. + + +### Dev Note + +
    +Working context for maintainers — click to expand + +None. + +
    diff --git a/packages/util/ripgrep/README.zh.md b/packages/util/ripgrep/README.zh.md new file mode 100644 index 0000000000..47aba57d1f --- /dev/null +++ b/packages/util/ripgrep/README.zh.md @@ -0,0 +1,79 @@ +--- +description: "通过组合的子进程提供方运行打包的 ripgrep,为文件搜索消费方提供有界流式读取。" +kind: "package-library" +--- + +# @deepseek-ai/dsh-util-ripgrep + +[English](README.md) | 中文 + +## 概述 + +使用本库,无需 shell 或系统安装的 `rg` 即可启动打包的 ripgrep。`tool-fs-search` 使用收集后的输出;`workspace-files` 增量读取文件路径,并在配置的上限处停止。调用方显式传入工作目录、参数、流模式、终止宽限期与取消信号,并负责解释退出码。 + +## 目录 + +- [使用本包](#use-this-package) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延期工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +从本包导入 `spawnRipgrep`,传入组合的子进程服务与显式的 `SubprocessSpawnSpec`;其中 `argv` 只包含 rg 参数。返回的 handle 按请求提供已收集输出或管道流。stdout 为管道时,`readRipgrepLines` 逐条提供以换行或 NUL 分隔的 UTF-8 记录;回调返回 false 会终止 rg,并抑制剩余记录。该函数等待 stdout、进程结果与托管进程范围全部结束后返回。回调、流或提供方失败会在清理后拒绝。调用方按自身 signal 解释退出码与取消。 + +只需要可执行文件路径的消费方可以独立使用 `resolveRgPath`。解析与启动失败会拒绝调用,不阻止导入本包。本库是依赖,不是 profile 插件。 + +----- + + +## 理解实现 + +
    +实现内幕——点击展开 + +单文件运行时优先选用可执行文件旁已有的 `-rg` 附属程序,否则使用 `@vscode/ripgrep` 平台包。Electron 路径将 `app.asar` 替换为 `app.asar.unpacked`。每次启动前置 `--no-config`,防止环境中的 rg 配置启用预处理程序。子进程提供方负责环境清理与终止;调用方负责截止时间与结果预算。参见[实现](src/index.ts)。 + +
    + +----- + + +## 进一步探索 + +- [子进程提供方约定](../../subprocess/subprocess/README.zh.md)——显式启动规格与托管进程范围。 +- [模型搜索工具](../../fs/tool-fs-search/README.zh.md)——输出收集、工具错误与结果保留。 +- [工作区文件搜索](../../api/workspace-files/README.zh.md#search)——原生忽略规则与浅层优先的文件及祖先目录匹配。 + +----- + + +## 模型体验 + +间接影响,通过消费子进程输出的搜索工具。 + +#### KV Cache 影响 + +没有直接影响;模型可见结果与请求装配由消费方负责。 + +## 已知限制与延期工作 + + + +- **要求同处一个执行环境的程序**——解析使用 Host 的打包二进制路径。远端子进程提供方没有该程序时调用失败;不查找系统 rg,也不回退到文件系统遍历。 +- **记录缓冲**——流式读取保留一条尚未完整的记录与当前流块;文件名可能含换行符的调用方使用 NUL 分隔符而不是换行符。记录按 UTF-8 解码,因此不是有效 UTF-8 的文件名会带着 U+FFFD 替换字符到达,无法用该字符串打开。 + + +### 开发备注 + +
    +维护者工作上下文——点击展开 + +无。 + +
    diff --git a/packages/util/ripgrep/package.json b/packages/util/ripgrep/package.json new file mode 100644 index 0000000000..1ff4e89dd4 --- /dev/null +++ b/packages/util/ripgrep/package.json @@ -0,0 +1,43 @@ +{ + "name": "@deepseek-ai/dsh-util-ripgrep", + "description": "Packaged ripgrep resolution and subprocess streaming helpers", + "version": "0.2.2-rc.1", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/util/ripgrep" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "lib/index.js", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dependencies": { + "@vscode/ripgrep": "^1.18.0" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-subprocess": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-subprocess": "workspace:*" + } +} diff --git a/packages/util/ripgrep/src/index.ts b/packages/util/ripgrep/src/index.ts new file mode 100644 index 0000000000..e9ca71e636 --- /dev/null +++ b/packages/util/ripgrep/src/index.ts @@ -0,0 +1,109 @@ +/** Packaged ripgrep resolution and subprocess execution, independent of tool or Remote consumers. */ +import { existsSync } from 'node:fs' +import { join, parse } from 'node:path' +import type { SubprocessHandle, SubprocessOutcome, SubprocessRuntime, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' + +let rgPathPromise: Promise | undefined + +/** + * Resolve the packaged executable lazily, once per process. Single-file runtimes use an existing + * `-rg` sidecar; Electron uses the unpacked ASAR path. Resolution failures reject + * this call, not package loading. No system executable or remote fallback is used. + * @returns the packaged executable's absolute path. + */ +export function resolveRgPath(): Promise { + rgPathPromise ??= Promise.resolve().then(async () => { + const executable = parse(process.execPath) + const executableSidecar = process.platform === 'win32' + ? join(executable.dir, `${executable.name}-rg.exe`) + : `${process.execPath}-rg` + if ('pkg' in process && existsSync(executableSidecar)) return executableSidecar + const dependency = (await import('@vscode/ripgrep')).rgPath + return process.versions.electron === undefined + ? dependency + : dependency.replace(/\.asar(?=[\\/])/u, '.asar.unpacked') + }) + return rgPathPromise +} + +/** + * Start packaged ripgrep with explicit subprocess settings. `spec.argv` contains + * only rg arguments, without an executable. This function prepends the resolved + * rg executable path and `--no-config`, so ambient configuration cannot enable a + * preprocessor. The caller owns exit classification and process cleanup. + * @param subprocess - the composed subprocess service. + * @param spec - cwd, rg arguments (without the executable), stdio, signal and termination grace. + * @returns the live subprocess handle; resolution and synchronous spawn failures reject. + */ +export async function spawnRipgrep(subprocess: Pick, spec: SubprocessSpawnSpec): Promise { + const executable = await resolveRgPath() + return subprocess.spawn({ ...spec, argv: [executable, '--no-config', ...spec.argv] }) +} + +/** Exit facts and whether the line consumer requested early termination. */ +export interface RipgrepLinesResult { + readonly outcome: SubprocessOutcome + readonly stopped: boolean +} + +/** + * Read UTF-8 stdout records without retaining the complete output. A false + * callback return terminates the process and suppresses remaining records. + * Completion, callback failure and stream failure all await process quiescence; + * provider failures reject. Exit codes and cancellation remain consumer-owned. + * @param handle - an owned ripgrep process spawned with piped stdout. + * Records are decoded as UTF-8, so bytes of a name that is not valid UTF-8 + * arrive replaced with U+FFFD. + * @param separator - newline for text output, or NUL for file paths that may contain newlines. + * @param onLine - synchronous record consumer; false requests early termination. + * @returns exit facts after stdout and the managed process range settle. + */ +export async function readRipgrepLines( + handle: SubprocessHandle, + separator: '\n' | '\0', + onLine: (line: string) => boolean, +): Promise { + const stdout = handle.stdout + if (stdout === undefined) { + handle.terminate() + await Promise.allSettled([handle.done, handle.waitForExit()]) + throw new Error('ripgrep requires piped stdout') + } + stdout.setEncoding('utf8') + let stopped = false + let completed = false + const reading = (async () => { + let pending = '' + for await (const chunk of stdout as AsyncIterable) { + if (stopped) continue + pending += chunk + let end: number + while ((end = pending.indexOf(separator)) !== -1) { + const line = pending.slice(0, end) + pending = pending.slice(end + 1) + if (!onLine(line)) { + stopped = true + pending = '' + handle.terminate() + break + } + } + } + if (pending.length > 0 && !onLine(pending)) { + stopped = true + handle.terminate() + } + })() + try { + const [, outcome] = await Promise.all([reading, handle.done]) + completed = true + return { outcome, stopped } + } finally { + if (!completed) { + handle.terminate() + stdout.destroy() + } + await Promise.allSettled([reading, handle.done]) + await handle.waitForExit() + } +} diff --git a/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts b/packages/util/ripgrep/tests/path.spec.ts similarity index 90% rename from packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts rename to packages/util/ripgrep/tests/path.spec.ts index 9afb0cef58..37eeba956c 100644 --- a/packages/fs/tool-fs-search/tests/rg-sidecar.spec.ts +++ b/packages/util/ripgrep/tests/path.spec.ts @@ -39,7 +39,7 @@ describe('ripgrep resolution', () => { process.execPath = '/runtime/dsh' existsSync.mockReturnValue(true) const sidecar = '/runtime/dsh-rg' - const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + const { resolveRgPath } = await import('@deepseek-ai/dsh-util-ripgrep') await expect(resolveRgPath()).resolves.toBe(sidecar) expect(existsSync).toHaveBeenCalledWith(sidecar) @@ -51,7 +51,7 @@ describe('ripgrep resolution', () => { process.execPath = 'C:\\runtime\\deepseek-harness-sdk-runtime-win-x64.exe' existsSync.mockReturnValue(true) const sidecar = 'C:\\runtime\\deepseek-harness-sdk-runtime-win-x64-rg.exe' - const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + const { resolveRgPath } = await import('@deepseek-ai/dsh-util-ripgrep') await expect(resolveRgPath()).resolves.toBe(sidecar) expect(existsSync).toHaveBeenCalledWith(sidecar) @@ -59,7 +59,7 @@ describe('ripgrep resolution', () => { it('uses the dependency binary in an ordinary Node process', async () => { existsSync.mockReturnValue(true) - const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + const { resolveRgPath } = await import('@deepseek-ai/dsh-util-ripgrep') await expect(resolveRgPath()).resolves.toBe(dependency.rgPath) expect(existsSync).not.toHaveBeenCalled() @@ -68,7 +68,7 @@ describe('ripgrep resolution', () => { it('uses the dependency binary when a packaged runtime has no sidecar', async () => { Reflect.defineProperty(process, 'pkg', { configurable: true, value: {} }) existsSync.mockReturnValue(false) - const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + const { resolveRgPath } = await import('@deepseek-ai/dsh-util-ripgrep') await expect(resolveRgPath()).resolves.toBe(dependency.rgPath) const executable = parse(process.execPath) @@ -81,7 +81,7 @@ describe('ripgrep resolution', () => { it('uses the unpacked executable path for an Electron ASAR dependency', async () => { Reflect.defineProperty(process.versions, 'electron', { configurable: true, value: '44.0.0' }) dependency.rgPath = '/Applications/DeepSeek Harness.app/Contents/Resources/app.asar/dsh/node_modules/@vscode/ripgrep/bin/rg' - const { resolveRgPath } = await import('@deepseek-ai/dsh-tool-fs-search') + const { resolveRgPath } = await import('@deepseek-ai/dsh-util-ripgrep') await expect(resolveRgPath()).resolves.toBe( '/Applications/DeepSeek Harness.app/Contents/Resources/app.asar.unpacked/dsh/node_modules/@vscode/ripgrep/bin/rg', diff --git a/packages/util/ripgrep/tests/stream.spec.ts b/packages/util/ripgrep/tests/stream.spec.ts new file mode 100644 index 0000000000..3887fdf548 --- /dev/null +++ b/packages/util/ripgrep/tests/stream.spec.ts @@ -0,0 +1,99 @@ +/** Stream framing, early termination and process ownership for packaged rg. */ +import { PassThrough, Readable } from 'node:stream' +import { describe, expect, it, vi } from 'vitest' +import type { SubprocessHandle, SubprocessOutcome, SubprocessSpawnSpec } from '@deepseek-ai/dsh-subprocess' +import { readRipgrepLines, resolveRgPath, spawnRipgrep } from '../src/index.ts' + +function handle( + stdout: Readable | undefined, + done: Promise = Promise.resolve({ exitCode: 0, signal: null }), +) { + return { stdout, stdin: undefined, stderr: undefined, control: undefined, collected: {}, done, + terminate: vi.fn(), waitForExit: vi.fn(async () => true) } satisfies SubprocessHandle +} + +describe('packaged rg spawning', () => { + it('forwards explicit settings and prepends --no-config', async () => { + const child = handle(undefined) + const spawn = vi.fn(() => child) + const spec: SubprocessSpawnSpec = { argv: ['--files'], cwd: '/workspace', signal: new AbortController().signal, + graceMs: 5, stdio: { stdin: 'ignore', stdout: 'pipe', stderr: { maxBytes: 20 } }, env: { TEST: 'value' } } + await expect(spawnRipgrep({ spawn }, spec)).resolves.toBe(child) + expect(spawn).toHaveBeenCalledWith({ ...spec, argv: [await resolveRgPath(), '--no-config', '--files'] }) + }) + + it('preserves synchronous provider failures', async () => { + const failure = new Error('cannot spawn') + await expect(spawnRipgrep({ spawn() { throw failure } }, { argv: [], cwd: '/', graceMs: 1, + stdio: { stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' } })).rejects.toBe(failure) + }) +}) + +describe('incremental stdout records', () => { + it('decodes split UTF-8 and delimiter chunks, including an unterminated final record', async () => { + const bytes = Buffer.from('雪\0two\0tail') + const child = handle(Readable.from([bytes.subarray(0, 1), bytes.subarray(1, 4), bytes.subarray(4)])) + const lines: string[] = [] + expect(await readRipgrepLines(child, '\0', (line) => { lines.push(line); return true })).toEqual({ stopped: false, outcome: { exitCode: 0, signal: null } }) + expect(lines).toEqual(['雪', 'two', 'tail']) + expect(child.terminate).not.toHaveBeenCalled() + expect(child.waitForExit).toHaveBeenCalledOnce() + }) + + it('stops callbacks at the cap while draining subsequent buffered chunks', async () => { + const child = handle(Readable.from(['one\ntwo\n', 'three\n'])) + const onLine = vi.fn(() => false) + expect((await readRipgrepLines(child, '\n', onLine)).stopped).toBe(true) + expect(onLine).toHaveBeenCalledExactlyOnceWith('one') + expect(child.terminate).toHaveBeenCalledOnce() + }) + + it('accepts an empty stream and can stop at the final unterminated record', async () => { + const empty = handle(Readable.from([])) + const onLine = vi.fn(() => true) + expect((await readRipgrepLines(empty, '\n', onLine)).stopped).toBe(false) + expect(onLine).not.toHaveBeenCalled() + const child = handle(Readable.from(['last'])) + expect((await readRipgrepLines(child, '\n', () => false)).stopped).toBe(true) + expect(child.terminate).toHaveBeenCalledOnce() + }) + + it('terminates a handle without piped stdout and waits for its outcome', async () => { + const child = handle(undefined, Promise.reject(new Error('launch failure'))) + await expect(readRipgrepLines(child, '\n', () => true)).rejects.toThrow('requires piped stdout') + expect(child.terminate).toHaveBeenCalledOnce() + expect(child.waitForExit).toHaveBeenCalledOnce() + }) + + it('propagates callback failures after terminating and awaiting cleanup', async () => { + const child = handle(Readable.from(['line\n'])) + const failure = new Error('consumer failed') + await expect(readRipgrepLines(child, '\n', () => { throw failure })).rejects.toBe(failure) + expect(child.terminate).toHaveBeenCalledOnce() + expect(child.waitForExit).toHaveBeenCalledOnce() + }) + + it('settles a provider failure even if stdout stays open', async () => { + const stdout = new PassThrough() + const failure = new Error('provider failed') + const child = handle(stdout, Promise.reject(failure)) + await expect(readRipgrepLines(child, '\n', () => true)).rejects.toBe(failure) + expect(stdout.destroyed).toBe(true) + expect(child.terminate).toHaveBeenCalledOnce() + }) + + it('waits for the managed process range after stdout and the outcome finish', async () => { + let release!: () => void + const cleanup = new Promise((resolve) => { release = resolve }) + const entered = Promise.withResolvers() + const child = { ...handle(Readable.from(['line\n'])), + waitForExit: async () => { entered.resolve(undefined); await cleanup; return true } } + let settled = false + const result = readRipgrepLines(child, '\n', () => true).then((value) => { settled = true; return value }) + await entered.promise + expect(settled).toBe(false) + release() + await result + expect(settled).toBe(true) + }) +}) diff --git a/packages/util/ripgrep/tsconfig.json b/packages/util/ripgrep/tsconfig.json new file mode 100644 index 0000000000..63eb05171f --- /dev/null +++ b/packages/util/ripgrep/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../subprocess/subprocess" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b48c3c87c1..d016fe8deb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1894,6 +1894,9 @@ importers: '@deepseek-ai/dsh-typert-protocol': specifier: workspace:* version: link:../../typert/protocol + '@deepseek-ai/dsh-util-ripgrep': + specifier: workspace:* + version: link:../../util/ripgrep '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery @@ -1934,6 +1937,12 @@ importers: '@deepseek-ai/dsh-session-persistence': specifier: workspace:* version: link:../../session/session-persistence + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local '@deepseek-ai/dsh-util-workspace-path': specifier: workspace:* version: link:../../util/workspace-path @@ -12356,12 +12365,12 @@ importers: packages/fs/tool-fs-search: dependencies: + '@deepseek-ai/dsh-util-ripgrep': + specifier: workspace:* + version: link:../../util/ripgrep '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery - '@vscode/ripgrep': - specifier: ^1.18.0 - version: 1.18.0 devDependencies: '@deepseek-ai/cordis': specifier: workspace:~ @@ -12411,6 +12420,9 @@ importers: '@deepseek-ai/dsh-working-directory': specifier: workspace:* version: link:../../session/working-directory + '@vscode/ripgrep': + specifier: ^1.18.0 + version: 1.18.0 packages/fs/tool-str-replace-editor: dependencies: @@ -17871,6 +17883,19 @@ importers: specifier: ^7.8.0 version: 7.8.0 + packages/util/ripgrep: + dependencies: + '@vscode/ripgrep': + specifier: ^1.18.0 + version: 1.18.0 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/dsh-subprocess': + specifier: workspace:* + version: link:../../subprocess/subprocess + packages/util/time: dependencies: '@js-temporal/polyfill': diff --git a/scripts/doc-standard.spec.ts b/scripts/doc-standard.spec.ts index 4ae1b2fc56..a8f2eb1095 100644 --- a/scripts/doc-standard.spec.ts +++ b/scripts/doc-standard.spec.ts @@ -107,6 +107,7 @@ const PACKAGE_LIBRARIES: Readonly> = { 'packages/util/package-manifest': 'Shared package manifest declarations with type-only exports.', 'packages/util/plugin-detail': 'Plugin detail document library.', 'packages/util/plugin-market-index': 'Plugin market index validation library.', + 'packages/util/ripgrep': 'Packaged executable resolution and caller-owned subprocess streaming without a plugin entry.', 'packages/util/time': 'Zero-dependency time-zone canonicalization utility.', 'packages/util/timeout': 'Zero-dependency timeout utility.', 'packages/util/values': 'Stateless lossless-JSON and immutable-value helpers.', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 9e5119387d..3f528ef5f3 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -1125,6 +1125,8 @@ export const TYPE_LINK_EXEMPTIONS: Readonly> = { WorkspaceFileRange: 'Host workspace file endpoint contract is owned by packages/api/workspace-files/README.md', WorkspaceFileStat: 'Host workspace file endpoint contract is owned by packages/api/workspace-files/README.md', WorkspaceFileText: 'Host workspace file endpoint contract is owned by packages/api/workspace-files/README.md', + WorkspaceFileSearchRequest: 'Host workspace file endpoint contract is owned by packages/api/workspace-files/README.md', + WorkspaceFileSearchResult: 'Host workspace file endpoint contract is owned by packages/api/workspace-files/README.md', TerminalShell: 'Browser terminal shell profiles are owned by packages/api/terminal-controller/README.md', TerminalEnvironment: 'Browser terminal environment fields are owned by packages/api/terminal-controller/README.md', WebTerminalInfo: 'Browser terminal metadata is owned by packages/api/terminal-controller/README.md', diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 700ba10ca6..4ad6448e20 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -70,6 +70,8 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = { '@deepseek-ai/dsh-session-format': ['sessionFormatLogFilename'], '@deepseek-ai/dsh-storage-domain': ['defineDomain'], '@deepseek-ai/dsh-timeout': ['MAX_TIMER_DELAY_MS'], + // Both operate only on the caller's subprocess service and handle; the module memoizes only the binary path. + '@deepseek-ai/dsh-util-ripgrep': ['readRipgrepLines', 'spawnRipgrep'], '@deepseek-ai/schemastery': ['default'], } as const satisfies HostDependencyExports diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index d5001cd021..6424868d38 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -113,6 +113,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/util/lazy-require': { kind: 'none', reason: 'Host module-loading primitive; registers nothing model-facing.' }, 'packages/util/plugin-detail': { kind: 'none', reason: 'Pure document selection for plugin detail pages; registers nothing model-facing.' }, 'packages/util/plugin-market-index': { kind: 'indirect', reason: 'Pure index validation; the plugin_market tool owns the entries it returns to the model.' }, + 'packages/util/ripgrep': { kind: 'indirect', reason: 'Search consumers own tool results and model context; this library only resolves and runs rg.' }, 'packages/util/time': { kind: 'indirect', reason: 'Pure zone validation; the consumer that records a canonical zone owns the model-visible line derived from it.' }, 'packages/core/agent-default-model': { kind: 'indirect', reason: 'The service supplies a ModelSelection; request assembly and adapters own the model-visible request.' }, 'packages/llm/deepseek-llm-api-extensions': { kind: 'indirect', reason: 'The registry contributes model-hidden provider fields; dsh-llm-deepseek owns their wire placement.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index 2121904985..e8ca4f8e44 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -410,6 +410,7 @@ // so these aliases stay hand-written like dsh-util-crypto above. "@deepseek-ai/dsh-util-time": ["./packages/util/time/src"], "@deepseek-ai/dsh-util-file-drag": ["./packages/util/file-drag/src"], + "@deepseek-ai/dsh-util-ripgrep": ["./packages/util/ripgrep/src"], // session-log-export lives under session-query/, so the generated aliases map only its // bare name; the browser half needs this explicit subpath for source-mode dynamic imports. "@deepseek-ai/dsh-session-log-export/client": ["./packages/session-query/session-log-export/src/client"], diff --git a/tsconfig.host.json b/tsconfig.host.json index c926055be3..9480842554 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -352,6 +352,7 @@ { "path": "./packages/util/launch-environment" }, { "path": "./packages/util/lazy-require" }, { "path": "./packages/util/native-command" }, + { "path": "./packages/util/ripgrep" }, { "path": "./packages/util/home-paths" }, { "path": "./packages/client/ui-plugin-manager/tsconfig.host.json" }, { "path": "./packages/client/ui-trajectory/tsconfig.host.json" }, From e98fcd59c25f088335c596df9c758aeb4bb38a8d Mon Sep 17 00:00:00 2001 From: Shigma Date: Tue, 3 Nov 2026 13:49:28 +0800 Subject: [PATCH 076/103] docs(vendor): drop the rc.11 plan and correct upstream pins --- vendor/README.md | 21 +++---- vendor/cordis-rc11-upgrade-plan.md | 93 ------------------------------ 2 files changed, 9 insertions(+), 105 deletions(-) delete mode 100644 vendor/cordis-rc11-upgrade-plan.md diff --git a/vendor/README.md b/vendor/README.md index 9020f5dcb6..c3a4c8e774 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -6,23 +6,19 @@ All vendored packages use the **`@deepseek-ai` scope** (`cordis` → `@deepseek- This file covers the manifest, the local-modification log, and the procedure for **updating** an existing vendored package. To **add a new** one, see the cookbook guide: [docs/cookbook/adding-a-vendored-package.md](../docs/cookbook/adding-a-vendored-package.md). -The proposed [Cordis rc.11 upgrade plan](cordis-rc11-upgrade-plan.md) records the package scope, PR dependencies and intended disposition of the local modifications. - ## Manifest -Upstream workspace: `cordis-workspace` (local checkout: `~/repos/cordis-workspace`). - | Directory | npm name | Upstream name | Version | Upstream repo | Commit | |---|---|---|---|---|---| -| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/deepseek-harness/cosmokit | `16f6fc058ade66e8ac5da0033d35a8d0f279f544` | -| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/deepseek-harness/schemastery (`packages/core`) | `e67cee00ad725bd1534aee930a979ea3eec6f698` | +| `cosmokit/` | `@deepseek-ai/cosmokit` | `cosmokit` | 1.8.1 | https://github.com/shigma/cosmokit | `02e691c5aa7f37f6e0b1cee7ee8f4a21c2e34507` | +| `schemastery/` | `@deepseek-ai/schemastery` | `schemastery` | 3.18.0 | https://github.com/shigma/schemastery (`packages/core`) | `cf0b7e5481d0e31d10cdc30bc45c09366c332f27` | | `cordis/` | `@deepseek-ai/cordis` | `cordis` | 4.0.0-rc.11 | https://github.com/cordiverse/cordis (`packages/core`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | | `loader/` | `@deepseek-ai/cordis-plugin-loader` | `@cordisjs/plugin-loader` | 1.0.0-rc.8 | https://github.com/cordiverse/cordis (`packages/loader`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | | `include/` | `@deepseek-ai/cordis-plugin-include` | `@cordisjs/plugin-include` | 1.1.1 | https://github.com/cordiverse/cordis (`packages/include`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/deepseek-harness/cordis (`packages/group`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | -| `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `0b96d9fd517b998e44e2209560c9e5f0671ce933` | -| `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/deepseek-harness/cordis (`packages/hmr`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | -| `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/deepseek-harness/cordis (`packages/logger-console`) | `abb0a307cb1d3b0947f455d590cf5ba922d4caa4` | +| `group/` | `@deepseek-ai/cordis-plugin-group` | `@cordisjs/plugin-group` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/group`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `timer/` | `@deepseek-ai/cordis-plugin-timer` | `@cordisjs/plugin-timer` | 1.1.4 | https://github.com/cordiverse/cordis (`packages/timer`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | +| `hmr/` | `@deepseek-ai/cordis-plugin-hmr` | `@cordisjs/plugin-hmr` | 1.0.15 | https://github.com/cordiverse/cordis (`packages/hmr`) | `ed8a7755c26a27a72064a21dea036ad1d1d6833c` | +| `logger-console/` | `@deepseek-ai/cordis-plugin-logger-console` | `@cordisjs/plugin-logger-console` | 1.0.0 | https://github.com/cordiverse/cordis (`packages/logger-console`) | `01b396240ce47cf2779c40af9bc445bb748fe112` | Third-party dependencies of the vendored packages stay on npm: `@standard-schema/spec`, `js-yaml`, `chokidar`, `picomatch`, `@babel/code-frame`, `supports-color`, `node-addon-require-builtin`. @@ -31,13 +27,14 @@ Intentionally **not** vendored (verified unused by this set): `reggol`, `@cordis ## Local modifications Keep this log exhaustive — every divergence from upstream must be listed. Each entry has a stable ID: remove an entry when its divergence no longer exists, and never renumber or reuse IDs. The next new entry is V28. + - **V1 · `hmr/src/index.ts`**: removed the `./locales/en-US.yml` / `./locales/zh-CN.yml` imports, the `.i18n({...})` call on the `Config` schema, and the `src/locales/` directory. Rationale: those imports require a runtime YAML loader hook (`@cordisjs/unyaml`) that we do not vendor; the i18n texts only localize config descriptions. - **V2 · All `package.json` files**: regenerated for Harness releases with scoped names, release versions, publication metadata, precise bundled-runtime and `lib/types/**/*.d.ts` / `.d.ts.map` file entries, source exports where applicable, and declaration metadata pointing at `lib/types`. References within the vendored set use `workspace:~`. HMR declares `esbuild` as a direct dev dependency for its imported `BuildFailure` type, and Loader requires `node-addon-require-builtin@^0.1.4` to match published app runtimes. - **V3 · All `tsconfig.json` files**: regenerated to extend the repo-root `tsconfig.base.json`, emit TypeScript intermediates to `lib/types`, and declare project references. - **V4 · Vendored TypeScript source internal specifiers**: changed local relative imports/exports from upstream's specifier shape to explicit `.ts` specifiers so TypeScript rewrites emitted JS to `.js` while declarations keep explicit, NodeNext-safe `.ts` specifiers. This includes `loader/src/config/isolate.ts` using `declare module './entry.ts'`. Type-only dependencies use `import type` or inline `type` modifiers so ESM output does not retain erased interfaces. - **V5 · `schemastery/tsdown.config.ts` and `logger-console/tsdown.config.ts`**: ours, not upstream files — per-package build-shape overrides (dual ESM+CJS output; separate node/browser entries) for the repo-root tsdown build. They read the JS emitted under `lib/types` and then write the publish runtime entries under `lib/`. Like the regenerated tsconfigs, they are not part of the upstream sync surface. - **V6 · `cordis/src/fiber.ts` lifecycle hardening**: locally closes three reentrant disposal gaps. An effect's owner-list wrapper is registered before its setup body runs, so an unload begun from inside setup awaits setup and every collected cleanup; synchronous setup failure removes the wrapper and rolls back collected cleanup. Async cleanup stays owner-visible until quiescence, and Cordis's internal effect composition joins an already-running cleanup while repeated public disposer calls retain their upstream single-shot result. Effect creation is rejected while the owner is `UNLOADING` (while `PENDING` and `LOADING` remain legal), preventing cleanup-time registrations from escaping the unload snapshot. Child fibers register and receive their parent-owned disposer before `internal/plugin` publication, resolve dependency declarations added by that notification before activation, drain effects attached while pending, and contain teardown-notification failures per observer so one callback cannot starve peers or interrupt ownership cleanup. -- **V7 · Cordis, Loader and Timer JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed to the fork. +- **V7 · JSDoc enrichment**: added `@param`/`@returns` tags and contract documentation (disposal semantics, waterfall veto, bail conditions, error cases) across the public plugin-author surface — `Context` (class, statics, and the `Context` interface properties incl. `root`), module re-exports, shared utility helpers, `EventsService`, `Fiber`, `RegistryService`, `ReflectService`, `Service`, `LoggerService` and their `declare module './context.ts'` overloads. Loader documentation covers `loader/src/{index,internal,config/entry,config/group,config/isolate,config/tree,config/utils}.ts`, including entry ownership, tree mutation methods, and the `!!js` discriminator. The upstream `EventsService.dispatch()` deprecation annotation is omitted: DSH enumerates callbacks to contain each observer failure independently, which the typed dispatch methods do not provide. Timer retains its local class and helper summaries; its README is local documentation because the upstream package has none. Cosmokit and Schemastery add summaries to their exported helpers, types and namespaces, logger-console to its exporters and config namespace, and HMR to its build-failure logger in `hmr/src/error.ts`. Comment-only; no code changes. Motivation: the website API-reference generator renders these docs and hard-errors on undocumented members. Retire this entry when the enrichment is upstreamed. - **V9 · `hmr/src/index.ts` module-watcher readiness and native paths**: realpath the existing watch base, classify framework modules and attach listeners before reporting readiness, and compare config paths using both canonical and configured spellings. This preserves Node module-cache identity across Windows short-name paths and filesystem aliases. The main watcher uses `ignoreInitial: true` so startup reads do not trigger another refresh; exact profile patch watching is owned by `packages/boot/hmr/src/watch-config.ts`. The Include change listener logs a rejected `Include.refresh()` instead of leaving the rejection unhandled; the rejection reports unsaved runtime changes while Include keeps its running tree. Covered by `packages/boot/hmr/tests/watch-config.spec.ts` and `scripts/cordis-vendor-hmr-include.spec.ts`. - **V10 · Vendored Node-compatible TypeScript**: marked erased imports explicitly across `cordis`, `loader`, `include`, `hmr`, and `schemastery` so Node's native TypeScript transform does not request types as runtime exports. Schemastery's source uses an ESM default export and its package declares `type: module`. Conditional exports select `.mjs` for import and `.cjs` for require; without them, concurrent imports under module-hook hosts reach the CJS entry and can race its require of ESM Cosmokit (`ERR_REQUIRE_ESM_RACE_CONDITION`). - **V11 · Include patch and YAML exports**: `include/src/index.ts` exports upstream `applyPatches` as `applyEntryPatches` and the `!!js` YAML dialect as `entryListSchema`, so `dsh --dump-config` composes entries with the same algorithm that mounting uses. Covered by `packages/boot/app-boot/tests/config-reload.spec.ts` and `scripts/cordis-entry-commit.spec.ts`. @@ -63,7 +60,7 @@ Relative to the resolver source in Cordis `v4.0.0-rc.11`: To update a vendored package from upstream: -1. In the upstream workspace, note `git rev-parse HEAD` of the relevant submodule. +1. In the upstream repository listed in the manifest, check out the release tag or commit to sync and note its full commit SHA. 2. Copy the package's `src/` (and `bin.js`, `README.md`, `LICENSE` if changed) over the vendored directory. 3. Re-apply the local modifications listed above (or drop them if upstream made them unnecessary — update the log either way). 4. Update the version and commit hash in the manifest table. diff --git a/vendor/cordis-rc11-upgrade-plan.md b/vendor/cordis-rc11-upgrade-plan.md deleted file mode 100644 index 7833cf3514..0000000000 --- a/vendor/cordis-rc11-upgrade-plan.md +++ /dev/null @@ -1,93 +0,0 @@ -# Cordis rc.11 vendor upgrade plan - -Status: proposed - -## Problem - -The upgrade starts from the [vendored](README.md) baselines Cordis core 4.0.0-rc.7, Loader 1.0.0-rc.5, Include 1.0.4, HMR 1.0.15 and Timer 1.1.2, with 24 local-modification entries. [Cordis v4.0.0-rc.11](https://github.com/cordiverse/cordis/releases/tag/v4.0.0-rc.11) incorporates some fixes and replaces other mechanisms. Updating every package and retiring every patch in one change would combine configuration, persistence, lifecycle and module-replacement decisions. - -DSH also has consumers that upstream Cordis does not own. Volatile configuration fields are stable references updated without restarting plugins; the settings UI reads their live values. A profile selects ordered plugin bundles and configuration overrides. [DSH HMR](../packages/boot/hmr/README.md) coordinates module replacement and profile changes through `ctx.hmr`. An entry's module namespace is its raw import result, retained before selecting `default` or `apply` so HMR can identify the module already loaded. These consumers must remain usable at every merge point. - -## Proposal - -Keep source vendoring and stage the upgrade as independently reviewable PRs, each covering a complete concern with its producers and consumers. Upgrade Core with the minimum cross-package compatibility changes, then complete Loader, Include and vendor HMR separately. Retire an existing patch when its replacement is adopted and verified; retain independently applicable patches until their behavior has a replacement. PR 0 records this plan only. It does not approve the open runtime decisions or implement the upgrade. - -### Package scope - -| Package | Target from the rc.11 tag | Treatment | -|---|---|---| -| `vendor/cordis` | 4.0.0-rc.11 | Upgrade with the Core compatibility slice. | -| `vendor/loader` | 1.0.0-rc.8 | Import required slices first; complete the package after resolution and change reporting land. | -| `vendor/include` | 1.1.1 | Separate patch composition from journal adoption. | -| `vendor/hmr` | 1.1.1 | Upgrade independently of the Include journal. | -| `vendor/timer` | 1.1.4 | Upgrade independently of Core. | -| `vendor/group` | Keep the existing pin | Its entry source matches the tag after rescoping. The Group implementation lives in Loader and still requires migration. | -| `vendor/logger-console` | Keep the existing pin | All three source files match the tag after normalizing scope, relative import extensions and comments. Core's logger changes remain part of the Core upgrade. | -| `vendor/cosmokit`, `vendor/schemastery` | Keep the existing pins | Retain the volatile extensions; their upstream upgrades are outside this plan. | - -The comparison above checks the current vendored source against the release tag; it does not assume equal version numbers imply equal code. DSH package versions, exports and build settings remain governed by the repository. A partially synchronized Loader, Include or HMR keeps its old manifest baseline and records the imported upstream slice in the local-modification log. Advance the package baseline only when the complete package has been reconciled, with remaining differences recorded explicitly. - -### PR dependencies - -The identifiers below are plan labels, not GitHub issue numbers. Preconditions are merge requirements. Independent PRs can be developed and reviewed concurrently; a dependent PR can start against the proposed changes before its predecessors merge, but must validate the actual combined result before merging. - -`Vn` below is the stable ID of an entry in the [local-modification log](README.md#local-modifications), not a PR; a retired ID no longer appears in the log. **Retire** means the upstream implementation replaces the local difference; **partial** means some behavior still needs a local adaptation; **retain** means the requirement remains; **prepare** does not retire a patch. These are proposed outcomes, confirmed only by the owning PR's tests. - -| PR | Scope | Prerequisite PRs | Existing vendor modifications | Required evidence | -|---|---|---|---|---| -| 0 | This plan, package comparison and open decisions. | None | None retired; records the proposed disposition. | Documentation checks; no runtime changes. | -| 1 | Define access to raw config, candidate resolution and the active instance's effective config, and migrate settings, Config Editor, volatile updates and HMR readers together. Initially delegate to the old framework fields. | 0 | Prepare V15 (lazy/raw config) and V22 (volatile); retire neither yet. | Preserve existing objects, validation, settings and volatile behavior. Candidate validation does not replace the active instance's references; introduce no dependency from vendor code to DSH packages. | -| 2 | Add upstream-compatible `hmr.watch()` to both HMR providers with compatible typing, migrate the existing Include to explicit registration, and remove the equivalent Include scans. Use DSH HMR's existing coordination queue. | 0 | Adapt V9's config-path matching to explicit watches; retain its readiness and native-path requirements. | Callback ordering, disposal, explicit paths and `root: []` under the old Core; one Include refresh per change under either provider. Preserve profile watching and both module-replacement algorithms. | -| 3 | Upgrade Timer to 1.1.4, retaining DSH locale resources and build metadata. | 0 | Retain V24 (display metadata); no logged runtime patch retired. | Concurrent interval reads, throttle cancellation and void return types; check callers using the old Core. | -| 4a | Upgrade Core to rc.11 with the minimum Loader, Include and HMR compatibility slice described below. | 1 | Retire V12 (activation observer), V21 (logger disposer) and, after canonical-fiber audits, V20 (Entry identity workaround). Partial V6 (lifecycle) and V15 (config model). Retain/adapt V22 and V23 (module namespace). | Config resolution, volatile identity, service isolation, dependent-before-provider teardown, retained effect regressions and application startup. | -| 4b | Import Loader's project-relative bare-specifier resolver, runtime API detection and fallback when Node internals are absent. | 0 | Retire V19: upstream now detects the internal loader by its available APIs. | Resolve in the config project's package scope, retain subpaths, handle read-only helper creation and test Node 24's older v1 API. | -| 4c | Complete Loader's `EntryChange` / `commit(change)` reporting and remaining changes, and upgrade Include to its 1.1.1 journal implementation in the same PR. Both HMR providers keep finding Include through their existing scans; keep `applyEntryPatches` and `entryListSchema` exports and in-memory no-op commits. | 4a, 4b | Retire V18 (`disabled` expressions), V8 (old refresh implementation) and V13 (`writeTask` type). Partial V11: retire the duplicate patch algorithm and insert-index fix; retain public exports. Partial V14: replace the write queue; retain rejection while the journal contains unsaved changes. Retain/adapt V22, including the schema receiver fix, V23 and the V15 child-expression marker. | Create, move, remove and self-update reports; no false self-disposal writes; later patches address inserted rows; stable ids for anonymous entries; file/runtime conflict handling, patch-owned writes, shutdown results and nested expressions; cloning and config dumps agree with mounting. | -| 4e | Complete vendor HMR's upgrade to 1.1.1, preserving required local path, readiness and explicit-watch behavior. | 2, 3, 4a | Partial V9: adopt upstream ordering and path handling where equivalent; retain explicit readiness and realpath gaps. Retain V1 (no YAML locale imports). | Three-stage module replacement, nested entries, disabled/removed entries, explicit watches and the existing local path cases. | -| 4f | Register the journal Include through the explicit watch adopted in PR 2 and remove the remaining Include scans. | 2, 4c | Adapt V9's config-path matching to the journal Include. | One coordinated refresh per change under either HMR provider; profile watching unchanged. | - -Shared integration differences remain in every affected sync: V2 (manifests), V3 (TypeScript projects), V4/V10 (imports and Node-compatible modules), V5 (build overrides), V7 (API documentation), V16 (published Core source) and V17 (scope). Untouched packages retain them without edits. V6 only loses the stale-epoch guard already supplied upstream; its remaining ownership and cleanup guarantees stay. V15 replaces the old raw/effective-config and event implementation, but the Include child-expression behavior remains local. V22 is not upstreamed by this release, including its schema-bound `simplify` call. - -After PR 0, PRs 1, 2, 3 and 4b have no implementation dependency on one another. Core depends on configuration preparation; it does not depend on Timer. Loader completion and vendor HMR can proceed independently after Core. Include journal adoption is part of Loader completion; PR 4f only connects that Include to PR 2's explicit watches and does not depend on the new vendor HMR replacement algorithm, so PRs 4e and 4f can merge in either order. No single GitHub stack should impose a dependency between unrelated branches. Shared files such as the vendor manifest may still require merge-conflict resolution. - -### Minimum Core compatibility slice - -PR 4a must migrate every caller of the changed Core APIs in the same PR, including callers outside vendor. This is a complete Core upgrade with local patches, paired with selected Loader changes; it is not a claim that Loader already equals 1.0.0-rc.8. - -- Adopt upstream raw `Fiber.config`, `internal/config(fiber, next)`, `internal/commit` and the new `internal/update` arguments and awaited result. Update the config accessors, provider hooks, boot observers and old Include's update listener together. The temporary commit listener writes through the old tree writer until PR 4c. -- Carry the required Loader entry/context awaiting chain, activation-failure observer and isolation changes with Core's `Impl.ctx`, `Impl.isolate`, `committed` and dependent tracking. Update direct implementation readers such as the preset registry. Include Group behavior owned by `vendor/loader/src/config/group.ts`; do not confuse it with the unchanged `vendor/group` entry package. Before retiring V20, ensure volatile updates and every other direct lifecycle-field access use the canonical `fiber.ctx.fiber`. -- Keep Include's nested-entry expressions literal until the owning child resolves them. Keep the namespace field needed by DSH HMR and preserve active volatile references through the agreed config mechanism. Update raw-config access in both HMR implementations without replacing the DSH module-replacement policy. -- Reapply the still-needed effect ownership, reentrant disposal and observer-containment guarantees to the new Core lifecycle. Remove patches already supplied by the imported Core source. Verify the combination with provider/dependent teardown before treating the compatibility slice as complete. - -Module resolution, structured tree-change reporting, journal reconciliation and the new vendor HMR algorithm are not prerequisites for these Core interfaces. Their PRs remain separate unless executable compatibility tests expose an additional dependency; amend this plan before broadening a PR silently. - -### Temporary compatibility code - -PR 4c changes tree mutation producers to `commit(change)` and adopts the journal Include in the same PR: upstream `patch.ts` clones file and inserted entries, while the old Include relied on sharing entry objects with the running tree for its cached data and generated ids. In-memory trees, including `PresetTree`, implement a no-op commit. Until PR 4f, both HMR providers find the journal Include through their existing scans and call its `refresh()`. - -The public patch export may remain an alias; it must not retain a second algorithm. Every temporary divergence has an owning introduction PR and a named removal PR. No runtime version detection or second Core event protocol is planned. - -PR 2 moves Include refresh ownership in one step: both HMR providers expose `watch()`, the existing Include registers its callback, and both providers stop their equivalent Include scans. The upstream HMR source no longer performs that scan, so importing it before migrating the Include consumer would lose config refresh. Moving the complete watch concern first avoids a temporary scan adapter and makes the later module-replacement and persistence decisions independent. - -### Decisions owned by individual PRs - -| Decision | Owning PR | Proposal and unresolved choice | -|---|---|---| -| Active effective config | 1, 4a | Store or expose the object actually supplied to the current instance. Resolving a candidate through `internal/config` must not overwrite it. Decide the publication point and invalidation rules before switching Core; a WeakMap alone does not establish those rules. | -| Persistence outcome | 4c | Use the journal's retry and reconciliation mechanism. Explicit `flush()` and `stop()` reject while changes remain unsaved; later successful retries clear previous errors. Keep this local adaptation minimal. | -| Nested config interpolation | 4a, 4c | Preserve child-owned expression evaluation. Keep the existing Include marker initially; any refinement that permits interpolation of Include's own fields while excluding child lists is a separate behavior change. | -| HMR replacement failure | 4e | Adopt upstream behavior for vendor HMR. Preserve DSH HMR's current source-reload rollback policy in this series; replacing that policy requires its own proposal and tests. | -| Effect cleanup guarantees | 4a | Retain guarantees not supplied by rc.11. Further upstreaming or retirement is separate work, not a prerequisite for reaching the release baseline. | - -## Acceptance criteria - -- Every implementation PR leaves supported applications usable and passes checks appropriate to its changes. A later PR may not be required to repair an earlier PR's startup, types, persistence or teardown. -- Each source-vendor update follows the [sync procedure](README.md#sync-procedure), including `pnpm run test` and `pnpm run build`, and updates its own manifest, local-modification log, affected documentation and generated references. The [pre-push workflow](../.agents/skills/dsh-pre-push-checks/SKILL.md) selects additional focused checks. Documentation freshness is not deferred to a final cleanup PR. -- Every changed behavior has an explicit decision and focused regression coverage. Tests for an intentionally superseded behavior change with its implementation and explain the new expectation. -- Once all implementation PRs are complete, Core, Loader, Include, vendor HMR and Timer use their selected rc.11-tag sources with enumerated remaining patches. Group, logger-console, Cosmokit and Schemastery keep their existing pins. All temporary writer and config adapters have been removed or reduced to the agreed permanent accessors. -- Final integration verification exercises settings and volatile updates, profile recomposition, both HMR providers, Include persistence and representative built application launches. This is an acceptance checkpoint, not an otherwise empty PR. - -## Risks - -PR 4a remains the largest necessary compatibility change: Core's service lifetime and configuration model cross repository package boundaries. The minimum slice is based on source inspection, not a completed migration experiment. Focused tests may identify additional inseparable changes. - -Intermediate Loader, Include and HMR copies intentionally combine an old baseline with documented upstream slices. Missing slice records would make a later sync unsafe. Deferred config, candidate validation, journal writes and asynchronous disposal must be tested in combination rather than inferred from independently passing unit cases. A new Include's type dependency on HMR must not force both concrete providers into the same incompatible `Context.hmr` declaration. From e89d2b031fe23b8bfe1386bc49db7516b1995cc5 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 01:03:59 +0800 Subject: [PATCH 077/103] fix(ui): show subagent descriptions above names without arrows (#7730) * fix(ui): show subagent descriptions above names without disclosure arrows * fix(ui): narrow subagent result cards * Revert "fix(ui): narrow subagent result cards" This reverts commit 23a5a353ac9daf0e322f28e19c9d2c2cfbb15acb. * test(web): sample agent row geometry in one browser task --- apps/web/tests/tool-details.e2e.ts | 10 ++++++ packages/client/locale/src/locales/de.ts | 2 -- packages/client/locale/src/locales/en.ts | 2 -- packages/client/locale/src/locales/es.ts | 2 -- packages/client/locale/src/locales/fr.ts | 2 -- packages/client/locale/src/locales/ja.ts | 2 -- packages/client/locale/src/locales/pt.ts | 2 -- packages/client/locale/src/locales/ru.ts | 2 -- packages/client/locale/src/locales/zh.ts | 2 -- packages/client/ui-tool/README.i18n.yaml | 4 +-- packages/client/ui-tool/README.md | 2 +- packages/client/ui-tool/README.zh.md | 2 +- .../tool/components/ToolDetails.module.css | 36 ------------------- .../client/tool/components/ToolDetails.tsx | 22 +++--------- .../tool/models/control-details-model.ts | 11 ++++-- .../tests/details-models.client.spec.ts | 10 +++--- .../ui-tool/tests/details-row.client.spec.tsx | 21 ++++------- snapshots/web/tool-details/ui.expected.md | 18 +++------- 18 files changed, 43 insertions(+), 109 deletions(-) diff --git a/apps/web/tests/tool-details.e2e.ts b/apps/web/tests/tool-details.e2e.ts index 8a51e66d44..93963c070e 100644 --- a/apps/web/tests/tool-details.e2e.ts +++ b/apps/web/tests/tool-details.e2e.ts @@ -62,6 +62,16 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => { expect(await row.locator('[class*="ioCard"]').count()).toBe(0) expect(await row.getByRole('button', { name: 'Inspect', exact: true }).count()).toBe(1) } + const agentRow = page.locator('[data-tool="list_agents"]').getByRole('listitem').first() + expect(await agentRow.getByRole('button').count()).toBe(0) + expect(await agentRow.locator('svg').count()).toBe(0) + // Read both positions in one browser task so scrolling cannot move the viewport between measurements. + const agentLayout = await agentRow.evaluate((element) => { + const description = element.querySelector('[class*="heading"] > span')!.getBoundingClientRect() + const name = element.querySelector('[class*="subtitle"]')!.getBoundingClientRect() + return { descriptionBottom: description.bottom, nameTop: name.top } + }) + expect(agentLayout.descriptionBottom).toBeLessThanOrEqual(agentLayout.nameTop) const changedTodos = page.locator('[data-tool="todo_write"]').nth(1) await changedTodos.getByText('1 added · 1 updated · 1 removed', { exact: true }).waitFor() for (const summary of await page.locator('[data-tool] details > summary').all()) await summary.click() diff --git a/packages/client/locale/src/locales/de.ts b/packages/client/locale/src/locales/de.ts index cb0bb45579..dd88cf6fc4 100644 --- a/packages/client/locale/src/locales/de.ts +++ b/packages/client/locale/src/locales/de.ts @@ -33,8 +33,6 @@ export const de = { 'more': 'Mehr', 'collapse': 'Einklappen', 'expand': 'Ausklappen', - 'subtitle.expand': 'Beschreibung für {name} ausklappen', - 'subtitle.collapse': 'Beschreibung für {name} einklappen', 'back': 'Zurück', 'brand.localBuild': 'Lokaler DSH-Build', 'workspace.defaultName': 'Standardarbeitsbereich', diff --git a/packages/client/locale/src/locales/en.ts b/packages/client/locale/src/locales/en.ts index 47a03d69ef..b649bbc3dc 100644 --- a/packages/client/locale/src/locales/en.ts +++ b/packages/client/locale/src/locales/en.ts @@ -32,8 +32,6 @@ export const en = { 'more': 'More', 'collapse': 'Collapse', 'expand': 'Expand', - 'subtitle.expand': 'Expand description for {name}', - 'subtitle.collapse': 'Collapse description for {name}', 'back': 'Back', 'brand.localBuild': 'DSH Local Build', 'workspace.defaultName': 'Default workspace', diff --git a/packages/client/locale/src/locales/es.ts b/packages/client/locale/src/locales/es.ts index 4fba984885..7eb95374e1 100644 --- a/packages/client/locale/src/locales/es.ts +++ b/packages/client/locale/src/locales/es.ts @@ -33,8 +33,6 @@ export const es = { 'more': 'Más', 'collapse': 'Contraer', 'expand': 'Expandir', - 'subtitle.expand': 'Expandir la descripción de {name}', - 'subtitle.collapse': 'Contraer la descripción de {name}', 'back': 'Atrás', 'brand.localBuild': 'Compilación local de DSH', 'workspace.defaultName': 'Espacio de trabajo predeterminado', diff --git a/packages/client/locale/src/locales/fr.ts b/packages/client/locale/src/locales/fr.ts index f0e5030f41..c57f1a3b11 100644 --- a/packages/client/locale/src/locales/fr.ts +++ b/packages/client/locale/src/locales/fr.ts @@ -33,8 +33,6 @@ export const fr = { 'more': 'Plus', 'collapse': 'Réduire', 'expand': 'Développer', - 'subtitle.expand': 'Développer la description de {name}', - 'subtitle.collapse': 'Réduire la description de {name}', 'back': 'Retour', 'brand.localBuild': 'Version locale de DSH', 'workspace.defaultName': 'Espace de travail par défaut', diff --git a/packages/client/locale/src/locales/ja.ts b/packages/client/locale/src/locales/ja.ts index 2b70cbb156..1186838c31 100644 --- a/packages/client/locale/src/locales/ja.ts +++ b/packages/client/locale/src/locales/ja.ts @@ -33,8 +33,6 @@ export const ja = { 'more': 'その他', 'collapse': '折りたたむ', 'expand': '展開', - 'subtitle.expand': '{name} の説明を展開', - 'subtitle.collapse': '{name} の説明を折りたたむ', 'back': '戻る', 'brand.localBuild': 'DSHローカルビルド', 'workspace.defaultName': 'デフォルトワークスペース', diff --git a/packages/client/locale/src/locales/pt.ts b/packages/client/locale/src/locales/pt.ts index adf711152d..75cdb19c29 100644 --- a/packages/client/locale/src/locales/pt.ts +++ b/packages/client/locale/src/locales/pt.ts @@ -33,8 +33,6 @@ export const pt = { 'more': 'Mais', 'collapse': 'Recolher', 'expand': 'Expandir', - 'subtitle.expand': 'Expandir descrição de {name}', - 'subtitle.collapse': 'Recolher descrição de {name}', 'back': 'Voltar', 'brand.localBuild': 'Versão local do DSH', 'workspace.defaultName': 'Espaço de trabalho padrão', diff --git a/packages/client/locale/src/locales/ru.ts b/packages/client/locale/src/locales/ru.ts index e75620fe21..a8a6d829da 100644 --- a/packages/client/locale/src/locales/ru.ts +++ b/packages/client/locale/src/locales/ru.ts @@ -33,8 +33,6 @@ export const ru = { 'more': 'Ещё', 'collapse': 'Свернуть', 'expand': 'Развернуть', - 'subtitle.expand': 'Развернуть описание {name}', - 'subtitle.collapse': 'Свернуть описание {name}', 'back': 'Назад', 'brand.localBuild': 'Локальная сборка DSH', 'workspace.defaultName': 'Рабочая область по умолчанию', diff --git a/packages/client/locale/src/locales/zh.ts b/packages/client/locale/src/locales/zh.ts index 6350caae3c..11ff789b8a 100644 --- a/packages/client/locale/src/locales/zh.ts +++ b/packages/client/locale/src/locales/zh.ts @@ -30,8 +30,6 @@ export const zh = { 'more': '更多', 'collapse': '收起', 'expand': '展开', - 'subtitle.expand': '展开{name}的描述', - 'subtitle.collapse': '收起{name}的描述', 'back': '返回', 'brand.localBuild': 'DSH 本地构建', 'workspace.defaultName': '默认工作区', diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 4182c93cfe..59dfd47110 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-tool/use-this-package: - en: 09231e7cc6515a01 - zh: c306bb141cf9bf9d + en: 4d8cb38024095705 + zh: 1baf6fa42f3fb80f /deepseek-ai-dsh-client-ui-tool/use-this-package/registering-a-business-tool-view: en: e458aff61e634190 zh: 650e417f450b3edf diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index b460da0f8f..448a4e197b 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -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. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Text agent lists show each agent name, or the historical ID, above a single-line description, with compact spacing and recorded status. Click the description to expand or collapse its full text; its accessible name follows the selected locale. +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. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Agent lists show the full description above the name, or the historical ID, with compact spacing and recorded status. Both lines wrap as needed and have no disclosure arrows; rows without a description show only the name. Settled foreground commands with a nonzero exit code, a terminating signal, or an explicit missing exit code keep their description in the ordinary gray text and show a neutral capsule with a red dot immediately after it. The capsule displays only the recorded code, signal, or localized missing-code status and stays on the same line; the description truncates with an ellipsis to reserve its space. Running, successful, and background calls omit it. Generic execution errors and stopped summaries retain their error and warning colors, including on hover. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 3b7811a823..37757c47a7 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。文本形式的智能体列表以紧凑间距展示智能体名称(历史记录为 ID)、下方的单行描述及记录中的状态。点击描述可展开或收起全文;其无障碍名称使用当前语言。 +工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。智能体列表以紧凑间距在上方展示完整描述,下方展示名称(历史记录为 ID),并保留记录中的状态。两行均按需换行,不带展开箭头;没有描述时只显示名称。 已结束的前台命令若返回非零退出码、终止信号,或明确记录为无退出码,描述保持普通灰色,后面紧接带红点的中性胶囊。胶囊仅显示记录的退出码、信号或本地化的“未正常退出”状态,并保持在同一行;描述超出可用宽度时显示省略号,为胶囊预留空间。运行中、成功和后台调用不显示胶囊。通用执行错误与停止摘要仍保留错误色和警告色,悬停时也不改变。 diff --git a/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css b/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css index 0180f9fa0d..44d9f2ef8d 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css +++ b/packages/client/ui-tool/src/client/tool/components/ToolDetails.module.css @@ -188,42 +188,6 @@ padding: 6px 10px 4px; } -.subtitleToggle { - display: flex; - align-items: flex-start; - gap: 4px; - width: 100%; - padding: 0; - border: 0; - background: transparent; - color: var(--dsw-alias-label-tertiary); - font: inherit; - font-size: 12px; - text-align: left; - cursor: pointer; -} - -.subtitleToggle > span { - min-width: 0; - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; -} - -.subtitleToggle > svg { - flex: none; - margin-top: 3px; -} - -.subtitleToggle[aria-expanded='true'] > span { - white-space: pre-wrap; - overflow-wrap: anywhere; -} - -.subtitleToggle[aria-expanded='true'] > svg { - transform: rotate(90deg); -} - .description { margin: 6px 0; color: var(--dsw-alias-label-caption); diff --git a/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx b/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx index 84ee30b93b..65e4db7c84 100644 --- a/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx +++ b/packages/client/ui-tool/src/client/tool/components/ToolDetails.tsx @@ -1,5 +1,4 @@ /** Compact, read-only fields and lists for recorded Tool results. */ -import { useState } from 'react' import { CodeBlock, MarkdownText, IconCheckOutlineRegular, IconChevronRightOutlineRegular, IconPlayOutlineRegular, } from '@deepseek-ai/dsh-client-ui-primitives' @@ -28,7 +27,7 @@ export interface ToolDetailItem { /** Localized display data shared by the built-in detail cards. */ export interface ToolDetailsModel { items: readonly ToolDetailItem[] - /** Tight rows with single-line subtitles that can expand in place. */ + /** Tight spacing for recorded entity rows. */ compact?: boolean summary?: string /** Header text while expanded, omitting a receipt status shown in the body. */ @@ -43,9 +42,8 @@ interface DetailContentProps { onOpenFile?: ((path: string, options?: OpenFileOptions) => void) | undefined } -function DetailItem({ item, compact, t, onOpenFile }: { item: ToolDetailItem; compact?: boolean | undefined } & DetailContentProps) { +function DetailItem({ item, t, onOpenFile }: { item: ToolDetailItem } & DetailContentProps) { const status = item.status - const [expanded, setExpanded] = useState(false) return (
  • {item.title !== undefined && ( @@ -77,19 +75,7 @@ function DetailItem({ item, compact, t, onOpenFile }: { item: ToolDetailItem; co )}
  • )} - {item.subtitle !== undefined && (compact ? ( - - ) :
    {item.subtitle}
    )} + {item.subtitle !== undefined &&
    {item.subtitle}
    } {item.description !== undefined &&

    {item.description}

    } {item.fields.length > 0 && (
    @@ -144,7 +130,7 @@ export function ToolDetails({ model, hasInspect = false, t, onOpenFile }: { {model.caption !== undefined &&
    {model.caption}
    } {model.items.length === 0 ?

    {model.empty}

    : (
      - {model.items.map((item, index) => )} + {model.items.map((item, index) => )}
    )} {model.unchanged !== undefined && ( diff --git a/packages/client/ui-tool/src/client/tool/models/control-details-model.ts b/packages/client/ui-tool/src/client/tool/models/control-details-model.ts index ef6fb9a8a5..c7f73005b0 100644 --- a/packages/client/ui-tool/src/client/tool/models/control-details-model.ts +++ b/packages/client/ui-tool/src/client/tool/models/control-details-model.ts @@ -29,7 +29,14 @@ function teamTaskItems(value: unknown, t: DetailTranslate): DetailItem[] { } function agentList(text: string, json: unknown, t: DetailTranslate): ToolDetailsModel | null { - if (Array.isArray(json)) return detailList(inspectionItems(json, t), t('detail.agents.count', { count: json.length }), t) + if (Array.isArray(json)) { + const items = inspectionItems(json, t).map((item) => { + if (item.title === undefined || item.description === undefined) return item + const { title, description, ...rest } = item + return { ...rest, title: description, subtitle: title } + }) + return { ...detailList(items, t('detail.agents.count', { count: json.length }), t), compact: true } + } if (text === '(no subagents)') return detailList([], t('detail.agents.count', { count: 0 }), t) const items: DetailItem[] = [] for (const line of text.split('\n')) { @@ -39,7 +46,7 @@ function agentList(text: string, json: unknown, t: DetailTranslate): ToolDetails const [, agent, state, title] = match if (agent === undefined || state === undefined) return null items.push({ - title: agent, ...(title === undefined ? {} : { subtitle: title }), + title: title || agent, ...(title ? { subtitle: agent } : {}), badge: detailBadge(state, t), fields: [], }) diff --git a/packages/client/ui-tool/tests/details-models.client.spec.ts b/packages/client/ui-tool/tests/details-models.client.spec.ts index 7147aff0f7..bbf9f5f2e8 100644 --- a/packages/client/ui-tool/tests/details-models.client.spec.ts +++ b/packages/client/ui-tool/tests/details-models.client.spec.ts @@ -93,20 +93,20 @@ describe('control detail adapters', () => { const agents = details('list_agents', 'lead [running] — root agent\nreviewer/checker [inactive] — Check tests\nold-id [unavailable]') expect(agents?.summary).toBe('3 agents') expect(agents?.items).toEqual([ - { title: 'lead', subtitle: 'root agent', badge: { label: 'Running', tone: 'info' }, fields: [] }, - { title: 'reviewer/checker', subtitle: 'Check tests', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, + { title: 'root agent', subtitle: 'lead', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'Check tests', subtitle: 'reviewer/checker', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, { title: 'old-id', badge: { label: 'Unavailable', tone: 'neutral' }, fields: [] }, ]) const historical = details('list_agents', 'a1 [running] — Build\na2 [ready] parent=a1 depth=1 — Review\na3 [diagnostic: corrupt] parent=a1 depth=1', { scope: 'descendants' }) expect(historical?.summary).toBe('3 agents') expect(historical?.items).toEqual([ - { title: 'a1', subtitle: 'Build', badge: { label: 'Running', tone: 'info' }, fields: [] }, - { title: 'a2', subtitle: 'Review', badge: { label: 'Ready', tone: 'neutral' }, fields: [] }, + { title: 'Build', subtitle: 'a1', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'Review', subtitle: 'a2', badge: { label: 'Ready', tone: 'neutral' }, fields: [] }, { title: 'a3', badge: { label: 'diagnostic: corrupt', tone: 'neutral' }, fields: [] }, ]) const structured = details('list_agents', JSON.stringify([{ name: 'lead', status: 'running', description: 'root agent' }, { name: 'reviewer', status: 'inactive' }])) expect(structured?.items).toEqual([ - { title: 'lead', description: 'root agent', badge: { label: 'Running', tone: 'info' }, fields: [] }, + { title: 'root agent', subtitle: 'lead', badge: { label: 'Running', tone: 'info' }, fields: [] }, { title: 'reviewer', badge: { label: 'Inactive', tone: 'warning' }, fields: [] }, ]) expect(details('list_agents', 'reviewer running')).toBeNull() diff --git a/packages/client/ui-tool/tests/details-row.client.spec.tsx b/packages/client/ui-tool/tests/details-row.client.spec.tsx index b5dde4a667..e21206109f 100644 --- a/packages/client/ui-tool/tests/details-row.client.spec.tsx +++ b/packages/client/ui-tool/tests/details-row.client.spec.tsx @@ -153,26 +153,17 @@ describe('todosDetail', () => { }) describe('DetailsRow', () => { - it('puts agent names first and lets a compact description expand and collapse', () => { + it('shows the full agent description above its name without a disclosure', () => { const description = 'Verify every construction bound. '.repeat(20) const block = { ...result('list_agents', null), content: [{ type: 'text' as const, text: `reviewer/checker [running] — ${description}` }] } const model = detailsCardModel(block, t, 'en')! render() const name = screen.getByText('reviewer/checker') - const toggle = screen.getByRole('button', { name: 'Expand description for reviewer/checker' }) - expect(name.compareDocumentPosition(toggle) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() - expect(toggle.textContent).toBe(description) - fireEvent.click(toggle) - expect(screen.getByRole('button', { name: 'Collapse description for reviewer/checker' }).getAttribute('aria-expanded')).toBe('true') - fireEvent.click(toggle) - expect(toggle.getAttribute('aria-expanded')).toBe('false') - }) - - it('uses an unqualified accessible name when a compact description has no title', () => { - render() - const toggle = screen.getByRole('button', { name: 'Expand' }) - fireEvent.click(toggle) - expect(screen.getByRole('button', { name: 'Collapse' })).toBe(toggle) + const title = screen.getByText(description.trim()) + expect(title.compareDocumentPosition(name) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy() + expect(screen.getByRole('listitem').textContent).toBe(`${description}Runningreviewer/checker`) + expect(screen.queryByRole('button')).toBeNull() + expect(screen.getByRole('listitem').querySelector('svg')).toBeNull() }) it('expands fields with the keyboard and keeps Inspect available', () => { diff --git a/snapshots/web/tool-details/ui.expected.md b/snapshots/web/tool-details/ui.expected.md index a069e23631..e55e355f3f 100644 --- a/snapshots/web/tool-details/ui.expected.md +++ b/snapshots/web/tool-details/ui.expected.md @@ -477,15 +477,9 @@ - button "List subagents 3 agents" [expanded] - text: Recorded result - list: - - listitem: - - text: agent-demo-review Running - - button "Expand description for agent-demo-review": 检查工具卡片布局 - - listitem: - - text: agent-demo-docs Idle - - button "Expand description for agent-demo-docs": 整理工具展示清单 - - listitem: - - text: agent-demo-icons Ready - - button "Expand description for agent-demo-icons": 检查状态图标 + - listitem: 检查工具卡片布局 Running agent-demo-review + - listitem: 整理工具展示清单 Idle agent-demo-docs + - listitem: 检查状态图标 Ready agent-demo-icons - button "Inspect" - button "Send message agent-demo-review" [expanded] - text: Recorded result @@ -658,8 +652,7 @@ - term: Role - definition: lead - listitem: - - text: ui-review Running - - paragraph: 检查工具卡片的可读性 + - text: 检查工具卡片的可读性 Running ui-review - term: ID - definition: agent-demo-review - term: Role @@ -669,8 +662,7 @@ - term: Context - definition: fresh - listitem: - - text: docs Inactive - - paragraph: 整理工具清单 + - text: 整理工具清单 Inactive docs - term: ID - definition: agent-demo-docs - term: Role From 8e98ccff62008a84a8b887778543872730ac8f3b Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Thu, 5 Nov 2026 13:47:14 +0800 Subject: [PATCH 078/103] fix(ui-subagent): read direct child catalogs on explicit expansion --- .../migration-required-child.expected.md | 8 +- .../unread-catalog.expected.md | 12 + apps/web/tests/forge-panel.e2e.ts | 5 +- apps/web/tests/subagent-conversation.e2e.ts | 80 ++++- packages/client/ui-subagent/README.i18n.yaml | 12 +- packages/client/ui-subagent/README.md | 8 +- packages/client/ui-subagent/README.zh.md | 8 +- .../client/SubagentHeaderLineage.module.css | 7 +- .../src/client/SubagentHeaderLineage.tsx | 93 +++--- .../client/ui-subagent/src/client/index.ts | 13 + .../client/ui-subagent/src/client/locales.ts | 8 - .../tests/browser-plugin.client.spec.ts | 40 ++- .../tests/conversation-ui.client.spec.tsx | 289 +++++++++++++++--- .../disclosures.expected.md | 8 + 14 files changed, 451 insertions(+), 140 deletions(-) create mode 100644 apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md create mode 100644 snapshots/web/subagent-conversation/disclosures.expected.md diff --git a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md index b60114ef0f..b86fcda5f5 100644 --- a/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md +++ b/apps/web/tests/expected/subagent-conversation/migration-required-child.expected.md @@ -1,13 +1,13 @@ # Before opening the child - tree "Subagent sessions": - - treeitem "historical researcher migration-catalog-child · Migration required · not running" [level=1]: - - text: historical researcher migration-catalog-child Migration required + - treeitem "historical researcher migration-catalog-child · continuable · not running" [level=1]: + - text: historical researcher migration-catalog-child - button "Open historical researcher in sidebar" # After opening the child - tree "Subagent sessions": - - treeitem "historical editor migration-catalog-grandchild · Migration required · not running" [level=1]: - - text: historical editor migration-catalog-grandchild Migration required + - treeitem "historical editor migration-catalog-grandchild · continuable · not running" [level=1]: + - text: historical editor migration-catalog-grandchild - button "Open historical editor in sidebar" diff --git a/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md b/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md new file mode 100644 index 0000000000..b1ccd511e5 --- /dev/null +++ b/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md @@ -0,0 +1,12 @@ +- tree "Subagent sessions": + - treeitem "event-sourcing researcher agent-1 · continuable · completed 7.9K tok · {{duration}}" [expanded] [level=1]: + - button "Collapse event-sourcing researcher descendants" + - text: event-sourcing researcher agent-1 7.9K tok {{duration}} + - button "Open event-sourcing researcher in sidebar" + - group: + - treeitem "example editor recorded-grandchild · continuable · completed 0 tok · {{duration}}" [level=2]: + - text: example editor recorded-grandchild 0 tok {{duration}} + - button "Open example editor in sidebar" + - treeitem "event-sourcing reviewer recorded-one-shot · one-shot · completed 0 tok · {{duration}}" [level=1]: + - text: event-sourcing reviewer recorded-one-shot 0 tok ~6mo 12d + - button "Open event-sourcing reviewer in sidebar" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 44f24a6a58..0392e51260 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -462,7 +462,10 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'), await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE) - expect(events.flatMap((event) => { + // Reference lookup can finish after the turn; the visible card confirms its binding was appended. + await scaffold.ctx.sessionPersistence.flush() + const boundEvents = await readPersistedEvents(scaffold, sessionId) + expect(boundEvents.flatMap((event) => { const record = pluginRecordOf(event) return record?.type === 'plugin:forge-session/binding' ? [record.data] : [] })).toEqual([{ action: 'reference', url: PULL }]) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 9690154afe..71993bbe52 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -365,6 +365,54 @@ describe('web e2e: persisted subagent conversation and human continuation', () = if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed') }) + it('discovers cold descendants one level at a time without leaving the parent conversation', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog')) + const reads = apiCalls.filter(path => path === '/api/session/projections').length + const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') + const projections = vi.spyOn(scaffold.ctx.sessionController, 'projections') + try { + const trigger = page.getByRole('button', { name: '2 subagents', exact: true }) + await page.locator('[data-composer-input]').first().hover() + await trigger.hover() + const tree = page.getByRole('tree', { name: 'Subagent sessions' }) + const child = tree.getByRole('treeitem', { name: new RegExp(LABEL) }) + await child.waitFor() + expect(await child.getAttribute('aria-expanded')).toBeNull() + expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0) + expect(await tree.getByText(/Loading subagents|unknown/u).count()).toBe(0) + expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads) + expect(observe).not.toHaveBeenCalled() + const parentUrl = page.url() + await trigger.click() + const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }) + await expand.waitFor() + await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId]) + expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false) + const lastRead = page.waitForResponse('**/api/session/projections') + await expand.click() + await (await lastRead).finished() + await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)) + .toEqual([parentId, childId, oneShotId, grandchildId]) + const grandchild = tree.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }) + await grandchild.waitFor() + expect(await grandchild.getAttribute('aria-expanded')).toBeNull() + await compareOrRefreshGolden( + fileURLToPath(new URL('./expected/subagent-conversation/unread-catalog.expected.md', import.meta.url)), + await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE, + ) + expect(page.url()).toBe(parentUrl) + expect(scaffold.ctx.agents.get(childId)).toBeUndefined() + expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() + await mkdir('.playwright-mcp/catalog-expand', { recursive: true }) + await page.screenshot({ path: '.playwright-mcp/catalog-expand/discovery.png' }) + await page.keyboard.press('Escape') + await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' }) + } finally { + observe.mockRestore() + projections.mockRestore() + } + }) + it('lists direct subagents by label in the reference menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-reference-title')) expect(liveReferenceOptions.some(text => text.includes(LABEL))).toBe(true) @@ -438,8 +486,9 @@ describe('web e2e: persisted subagent conversation and human continuation', () = } }) - it('recovers a current-format cold child catalog cache miss without activating either level', async () => { + it('expands locally available cold catalogs without requesting or activating either level', async () => { onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree')) + const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length await page.getByRole('button', { name: '2 subagents' }).hover() const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' }) expect(await catalogTree.evaluate((element) => { @@ -453,6 +502,10 @@ describe('web e2e: persisted subagent conversation and human continuation', () = name: `Expand ${ONE_SHOT_LABEL} descendants`, }) expect(await oneShotDisclosure.count()).toBe(0) + await compareOrRefreshGolden( + fileURLToPath(new URL('../../../snapshots/web/subagent-conversation/disclosures.expected.md', import.meta.url)), + await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE, + ) const oneShotRow = page.getByRole('treeitem', { name: new RegExp(ONE_SHOT_LABEL) }) expect(await oneShotRow.locator('[data-state="done"]').count()).toBe(1) expect(await oneShotRow.getByText('~6mo 12d', { exact: true }).count()).toBe(1) @@ -501,18 +554,13 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(await page.getByText(PARENT_PROMPT, { exact: true }).isVisible()).toBe(true) expect(await page.locator('[data-sidebar-chat]').count()).toBe(0) } - const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') - try { - const projections = page.waitForResponse(response => new URL(response.url()).pathname === '/api/session/projections') - await clickDisclosureGutter(3) - await projections - await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ timeout: 15_000 }) - expect(await sectionHeader.count()).toBe(0) - expect(observe.mock.calls.some(([id]) => id === childId)).toBe(true) - expect(observe.mock.calls.some(([id]) => id === grandchildId)).toBe(false) - } finally { - observe.mockRestore() - } + await clickDisclosureGutter(3) + const grandchildRow = page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }) + await grandchildRow.waitFor({ timeout: 15_000 }) + expect(await catalogTree.getByText('Loading subagents…', { exact: true }).count()).toBe(0) + expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull() + expect(await grandchildRow.getByRole('button', { name: `Expand ${NESTED_LABEL} descendants` }).count()).toBe(0) + expect(await sectionHeader.count()).toBe(0) await clickDisclosureGutter(26) await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).waitFor({ state: 'detached' }) expect(await childRow.getAttribute('aria-expanded')).toBe('false') @@ -571,6 +619,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = scaffold.workspaceCwd, ) await compareOrRefreshGolden(TREE_EXPECTED, snapshot, MODE) + expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(catalogReads) await page.getByRole('treeitem', { name: new RegExp(NESTED_LABEL) }).getByText(grandchildId, { exact: true }).click() await page.getByText(NESTED_PROMPT).waitFor() const hierarchy = page.getByRole('navigation', { name: 'Session hierarchy' }) @@ -994,10 +1043,9 @@ describe('web e2e: migration-required subagent catalog', () => { const tree = page.getByRole('tree', { name: 'Subagent sessions' }) const childRow = tree.getByRole('treeitem', { name: new RegExp(childLabel) }) await childRow.waitFor() - await expect.poll(() => childRow.textContent()).toContain('Migration required') await expect.poll(() => childRow.getByRole('button', { name: `Expand ${childLabel} descendants`, exact: true }).count()).toBe(0) expect(await childRow.getAttribute('aria-expanded')).toBeNull() - expect(await childRow.textContent()).toContain('Migration required') + expect(await childRow.textContent()).not.toContain('Migration required') expect(await childRow.textContent()).not.toContain('unknown mode') expect(await childRow.getByRole('button', { name: `Open ${childLabel} in sidebar`, exact: true }).isEnabled()).toBe(true) expect(await tree.getByRole('treeitem').count()).toBe(1) @@ -1015,7 +1063,7 @@ describe('web e2e: migration-required subagent catalog', () => { await page.getByRole('button', { name: '1 subagent', exact: true }).hover() const grandchildRow = tree.getByRole('treeitem', { name: new RegExp(grandchildLabel) }) await grandchildRow.waitFor() - expect(await grandchildRow.textContent()).toContain('Migration required') + expect(await grandchildRow.textContent()).not.toContain('Migration required') expect(await grandchildRow.getAttribute('aria-expanded')).toBeNull() expect(await grandchildRow.getByRole('button', { name: `Expand ${grandchildLabel} descendants`, exact: true }).count()).toBe(0) expect(projections).not.toHaveBeenCalled() diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 32d15ae638..37ef8fd189 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-subagent/use-this-package: - en: bc1c5164849937a8 - zh: e03adf54d2d5a668 + en: c7a9485c0cdcd9de + zh: 903ad54e44d79eae /deepseek-ai-dsh-client-ui-subagent/use-this-package/browsing-the-tree: - en: 5ea28139189887e9 - zh: f5a51f041c39b0fa + en: 35e983f0276188d0 + zh: df588dc1523031da /deepseek-ai-dsh-client-ui-subagent/use-this-package/continuing-a-conversation: en: e4ec261d3b122eb5 zh: 320bb2efc93dccdc @@ -30,8 +30,8 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 45772c086f8a55f1 - zh: c80584bf49897b8f + en: 22b8ca76ca8d64a6 + zh: 300231110a4a208d /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: en: dcbc58d4cad47fa8 zh: e962a8cbdfd4a914 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 764025ddfa..74810feff4 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -25,7 +25,7 @@ Browse local subagent conversations and external tasks from the parent header. L ## Use this package -The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and loads nested catalogs only when their rows expand. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. +The session header uses the session title for ordinary breadcrumbs. Subagent breadcrumbs prefer the original creation description (`entry.label`), then the agent name (`entry.name`), then the Session id. Ordinary and subagent breadcrumb titles both use 14px text with a 20px line height. When the session's direct catalog has entries or a read has failed, the descendant-count trigger renders after the preset label in the header actions band, with no breadcrumb separator. An absent or empty catalog hides the count trigger unless the root Session has an enabled, available Team board with shared tasks or a task-record error. Enabling Team mode alone does not show an empty entry. The trigger opens that direct catalog, uses the total count as its accessible name and the running count as its accessible description, and discovers the next level on explicit activation. Select a local child at any depth to open that child's conversation with its exact `{parentSessionId, childSessionId, mode}` address, or use a noncurrent local row's trailing arrow to open the same address in the right Sidebar, preferring a separate pane when room permits. This package registers the `dsh-resource://subagentchat/session/?parent=&mode=` resource and builtin Sidebar tab type. The resource retains the child `SessionReference` directly from its address without refreshing the parent catalog, and releases the reference when the tab record closes. The tab renders the shared `conversation.content` Factory through `sidebar.chat.conversation`, fixes the local View to Chat, and omits the main Conversation header and width controls. @@ -39,7 +39,7 @@ The wide root count trigger shows a 14px Users icon in its 14px slot when no chi Count, owner, and sidebar-action tooltips appear after 500ms of hover. Hovering a text-visible trigger opens its catalog after 150ms; leaving both trigger and catalog closes it after 120ms. Clicking the descendant-count trigger opens and pins its catalog, or closes an already pinned catalog. The icon-only count trigger does not open on hover, including when a pending hover crosses into the narrow layout. Clicking toggles its pinned menu; ArrowDown opens and pins the menu and focuses its first row. Outside click or Escape dismisses a pinned menu. Clicking moves focus into the panel, where ArrowDown/Home enters the first tree row and ArrowUp/End enters the last; Escape returns focus when it was inside. Breadcrumb-title clicks navigate to the corresponding conversation. -Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. A row is a known leaf only after its own catalog loads empty. +Rows show the creation description, or an available Session title, above the agent name, which is unique among its siblings. Entries recorded without a name show the Session id in its place. Without either description, the row shows only the name or Session id. Navigation, row identity, and Sidebar addresses always use the Session id. Local rows use compact 4px vertical padding; their clickable content uses 6px horizontal padding and 7px gaps, aligned with shared-task rows while retaining the tree's left offset. A decorative trailing check marks the current conversation and is not an action; other local rows retain the sidebar arrow. Primary titles use 13px text and secondary names use 12px. All rows wrap descriptions and names in full, including on touch screens. Running uses the shared ongoing loader, an inactive child whose latest closed turn completed normally uses the shared success dot, and other inactive children use the shared idle dot. Every row reserves the same 14px status column, centering smaller dots so titles align with the loader state. The text-visible header trigger vertically centers its activity glyph and count with a 4px gap. The trailing column stacks total durable provider usage above active-turn duration. Keyboard navigation works with ArrowRight/ArrowLeft to expand and collapse branches and ArrowUp/ArrowDown, Home, End, and Escape to navigate or close the tree. An unlabeled one-shot row falls back to its session id. Only rows with confirmed children show an expansion arrow. Clicking or keyboard-opening the menu reads its catalog and its direct children; expanding a branch does the same for that branch. Each activation reads direct children sequentially through the existing projection reader, which reuses completed reads and merges in-flight requests. It does not recursively discover deeper descendants. Hover and rendering do not initiate reads. Once started, a level read may finish after the menu closes. Missing catalogs show no expansion arrow or unknown marker; shared projection updates reveal confirmed branches while preserving the agent activity marker. Failed reads keep navigation available and offer Retry. ### Continuing a conversation @@ -61,11 +61,11 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `projectionsBySession` through the standard `useSessions` hook. The renderer selects `subagentCatalog` from each Session’s shared values for membership, disclosure, and counts. Activity prefers the unified UI status and falls back to Session summaries; summaries supply titles and usage. Expanding a row reads its target's projections, including ordinary cold history. A list row with `formatStatus: migration-required` displays “Migration required” before expansion and keeps its history-opening actions without descendant expansion or changing its subagent mode; a projection read requiring migration without a catalog supplies the same notice. Opening the Session supplies its catalog through history and control projections. Otherwise, an available catalog remains usable, including an explicit empty catalog. Live projection frames update every loaded level without menu subscriptions or repeated membership queries. Other rows remain expandable while their catalogs are absent, loading, or failed, and become known leaves after ready empty catalogs. External rows are always leaves and do not load child Sessions. +The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering, hovering, and expanding the tree use only local projections and never request missing catalogs. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Opening a catalog dropdown does not request its root catalog. Child-catalog expansion and failed-read retries call `refreshProjection`; shared projection-value changes update the display automatically. +Opening a catalog dropdown does not request its root catalog. Only explicit failed-read retries call `refreshProjection`; the Session object layer owns request deduplication and reconnect recovery. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 52d9abc110..3ea5bef7e9 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并且只在行展开时加载嵌套目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 +会话页头的普通面包屑使用会话标题。subagent 面包屑优先使用创建时的原始描述(`entry.label`),其次使用智能体名称(`entry.name`),最后回退到 Session id。普通与 subagent 面包屑标题均使用 14px 文字和 20px 行高。当会话的直接目录有子项或读取失败时,后代数量触发器渲染在页头操作区中预设标签之后,不带任何面包屑分隔符。目录缺席或为空时隐藏数量触发器,除非根 Session 已开启且可用的 Team 任务板有共享任务或任务记录错误。仅开启 Team 模式不会显示空入口。触发器打开该直接目录,以总数作为无障碍名称、运行数作为无障碍描述,并在用户显式打开时发现下一层目录。选择任意深度,即可用该子会话的确切 `{parentSessionId, childSessionId, mode}` 地址打开其对话;也可以使用非当前本地行的行尾箭头在右侧 Sidebar 打开同一地址,并在空间允许时优先使用独立分栏。 本包注册 `dsh-resource://subagentchat/session/?parent=&mode=` 资源与 builtin Sidebar tab 类型。资源直接根据地址保留 child 的 `SessionReference`,不刷新 parent 目录,并在 tab 记录关闭时释放 reference。tab 通过 `sidebar.chat.conversation` 渲染共享 `conversation.content` Factory,把局部 View 固定为 Chat,并省略主 Conversation 的 Header 与宽度控制。 @@ -39,7 +39,7 @@ kind: "package-reference" 数量、负责人及侧边栏操作的工具提示在悬停 500ms 后显示。悬停文字可见的触发器 150ms 后打开目录;指针离开触发器和目录后,经过 120ms 关闭。点击后代数量触发器会打开并固定目录,或关闭已固定的目录。纯图标数量触发器不会因悬停而打开,包括等待悬停打开期间切换到窄布局的情况。点击可切换固定菜单的开关状态;ArrowDown 会打开并固定菜单,并将焦点移至首行。点击外部或按 Escape 可关闭已固定的菜单。点击会将焦点移入面板,此时 ArrowDown/Home 进入首个树行,ArrowUp/End 进入最后一个树行;Escape 在焦点原本位于面板内时将其送回。点击面包屑标题会导航至对应会话。 -目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有一行自身的目录加载为空后,它才是已知叶子。 +目录行在智能体名称上方显示创建描述,缺少创建描述时使用可用的 Session title;名称在同级子智能体中唯一。没有名称的历史目录项在相同位置显示 Session id。两者均缺少时,该行仅显示名称或 Session id。导航、行身份与 Sidebar 地址始终使用 Session id。本地行使用紧凑的 4px 垂直内边距;可点击内容使用 6px 水平内边距和 7px 间距,与共享任务行对齐,同时保留树的左侧偏移。当前对话在行尾显示装饰性对勾,该对勾不是操作控件;其他本地行保留侧边栏箭头。主标题使用 13px 文字,次级名称使用 12px。所有行均将描述与名称换行完整展示,包括在触屏上。running 使用共享 ongoing loading,最近一个已结束轮次正常完成的 inactive child 使用共享 success 绿点,其他 inactive child 使用共享 idle 灰点。每行都为状态图标预留相同的 14px 列宽,并将较小的圆点居中,使 title 与 loading 状态对齐。文字可见的页头触发器会垂直居中活动图标与数量,并保留 4px 水平间距。尾随列在上行显示提供方的持久化 token 用量总计,在下行显示活跃轮次耗时。键盘导航:ArrowRight/ArrowLeft 展开和折叠分支;ArrowUp/ArrowDown、Home、End 与 Escape 用于导航或关闭树。没有 label 的 one-shot 行回退到其会话 id。只有确认存在下级的行才显示展开箭头。点击或通过键盘打开菜单时,读取当前目录及其直属子节点的目录;展开分支时对该分支执行相同操作。每次打开操作通过现有投影读取器依次读取直接子节点,复用已完成的读取并合并进行中的请求,不递归发现更深层后代。悬停与渲染不触发读取。已开始的单层读取可能在菜单关闭后完成。缺少目录的行不显示展开箭头或未知标记;共享投影更新确认存在下级后显示箭头,并保持 agent 活动状态图标。读取失败时保留导航操作并提供重试。 ### 续接对话 @@ -61,11 +61,11 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子读取 `projectionsBySession`。renderer 从每个 Session 的共享值中选择 `subagentCatalog`,用于成员关系、展开控件与数量。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要提供标题与用量。展开行读取目标投影,包括普通冷历史。列表行的 `formatStatus` 为 `migration-required` 时,行在展开前即显示“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode;投影读取需要迁移且缺少目录时,也显示同一提示。打开会话后,历史与 control 投影提供其目录。其他情况下,已有目录仍可使用,包括显式空目录。实时 projection 帧更新所有已加载层级,无需菜单订阅或重复成员查询。其他行在目录缺席、加载中或失败时保持可展开,并在目录就绪且为空后成为已知叶子。外部行始终为叶子,不加载子 Session。 +页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染、悬停和展开目录树仅使用本地投影,不会请求缺失目录。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -打开目录下拉菜单不会请求其根目录。展开子节点目录或重试失败读取时调用 `refreshProjection`;共享投影值的变化会自动更新显示。 +打开目录下拉菜单不会请求其根目录。只有显式重试失败读取时才调用 `refreshProjection`;Session 对象层负责请求去重和重连恢复。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css index d3f58ad409..570c6cd7ef 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css @@ -350,8 +350,7 @@ } .label, -.secondaryLabel, -.summary { +.secondaryLabel { white-space: normal; overflow-wrap: anywhere; } @@ -370,14 +369,10 @@ color: var(--dsw-alias-label-tertiary); } -.summary, .metrics { color: var(--dsw-alias-label-tertiary); font-size: 10px; line-height: 15px; -} - -.metrics { display: grid; grid-template-rows: 17px 15px; flex: none; diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index 92a802ac66..ab2b6e6a4b 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -19,7 +19,7 @@ import type {} from './slots.ts' import css from './SubagentHeaderLineage.module.css' type SubagentCatalogSnapshot = Omit & { - state: 'loading' | 'ready' | 'migration-required' | 'error' + state: 'idle' | 'loading' | 'ready' | 'migration-required' | 'error' entries: (SessionProjectionMap['subagentCatalog'][number] & { activity: 'running' | 'inactive' })[] } type Catalogs = Readonly> @@ -29,6 +29,8 @@ export type SubagentCatalogInjected = { openChild: (address: SubagentAddress) => void openChildAside: (address: SubagentAddress) => void refreshProjection: (parentSessionId: SessionId) => void + /** Read this catalog and its direct children after explicit activation. */ + prepareCatalog: (parentSessionId: SessionId) => Promise } /** Root catalog actions and availability of its optional footer. */ @@ -203,9 +205,11 @@ function CatalogLoadingRows({ t }: { t: TranslateNS }) { return
    {t('loading.label')}
    } -/** A child becomes a known leaf only after its own authoritative catalog loads empty. */ -function isKnownLeaf(catalog: SubagentCatalogSnapshot | undefined): boolean { - return catalog?.state === 'ready' && catalog.entries.length === 0 +/** Only confirmed child membership exposes a branch disclosure. */ +function canExpandCatalog(entry: SubagentCatalogSnapshot['entries'][number], catalogs: Catalogs, summaries: CatalogRowsProps['summaries']): boolean { + return entry.mode !== 'external' && (catalogs[entry.id]?.entries.length ?? 0) > 0 + && summaries[entry.id]?.formatStatus !== 'migration-required' + && catalogs[entry.id]?.state !== 'migration-required' } /** The agent name unique among the row's siblings, or the Session ID for entries recorded without one. */ @@ -251,11 +255,8 @@ function CatalogRows({ const timer = setInterval(() => { setNow(Date.now()) }, 1_000) return () => { clearInterval(timer) } }, [running]) - const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 - const reserveDisclosure = catalog.entries.some(entry => - entry.mode !== 'external' && !isKnownLeaf(catalogs[entry.id]) - && summaries[entry.id]?.formatStatus !== 'migration-required' - && catalogs[entry.id]?.state !== 'migration-required') + const emptyLoading = (catalog.state === 'loading' || catalog.state === 'idle') && catalog.entries.length === 0 + const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) return ( <> {emptyLoading && ( @@ -278,13 +279,10 @@ function CatalogRows({ const external = entry.mode === 'external' const childCatalog = catalogs[entry.id] const isCurrent = entry.id === currentSessionId - const knownLeaf = external || isKnownLeaf(childCatalog) const requiresOpening = summaries[entry.id]?.formatStatus === 'migration-required' || childCatalog?.state === 'migration-required' - const canExpand = !knownLeaf && !requiresOpening + const canExpand = canExpandCatalog(entry, catalogs, summaries) const isExpanded = canExpand && expanded.has(entry.id) - const childLoading = childCatalog === undefined - || (childCatalog.state === 'loading' && childCatalog.entries.length === 0) const summary = summaries[entry.id] const description = entry.label || summary?.title const name = entryName(entry) @@ -298,7 +296,7 @@ function CatalogRows({ : completed ? t('activity.completed') : t('activity.inactive') - const secondary = [secondaryLabel, requiresOpening ? t('catalog.migrationRequired') : mode, activity] + const secondary = [secondaryLabel, mode, activity] .filter(value => value !== undefined) .join(' · ') const totalTokens = tokenTotal(summary?.projectionValues?.tokenUsage) @@ -385,7 +383,6 @@ function CatalogRows({ {secondaryLabel !== undefined && ( {secondaryLabel} )} - {requiresOpening && {t('catalog.migrationRequired')}} {metrics !== '' && ( @@ -426,31 +423,35 @@ function CatalogRows({ )}
    - {isExpanded && ( + {!isExpanded && !external && !requiresOpening && childCatalog?.state === 'error' && ( +
    + {t('load.error')} + +
    + )} + {childCatalog !== undefined && isExpanded && (
    - {childCatalog === undefined - ? - : ( - - )} +
    )}
    @@ -497,7 +498,7 @@ type CatalogDropdownProps = CatalogDropdownSharedProps & ( function CatalogDropdown(props: CatalogDropdownProps) { const { rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t, hasSharedTasks = false, + useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t, hasSharedTasks = false, } = props const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined const projections = useSessions(state => state.projectionsBySession) @@ -507,7 +508,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { return Object.fromEntries(Object.entries(projections).map(([id, snapshot]) => { const projected = snapshot.values.subagentCatalog const state = snapshot.state === 'idle' - ? projected === undefined ? 'loading' : 'ready' + ? projected === undefined ? 'idle' : 'ready' : snapshot.state === 'migration-required' && projected !== undefined ? 'ready' : snapshot.state return [id, { state, @@ -521,6 +522,11 @@ function CatalogDropdown(props: CatalogDropdownProps) { })) }, [projections, summaries, statuses]) const catalog = catalogs[rootSessionId] + const prepareLevel = (sessionId: SessionId): void => { + void prepareCatalog(sessionId).catch((error: unknown) => { + console.error('[ui-subagent] catalog discovery failed:', error) + }) + } const [open, setOpen] = useState(false) const [expanded, setExpanded] = useState>(() => new Set()) const rootRef = useRef(null) @@ -622,7 +628,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { return } setExpanded(current => new Set(current).add(childSessionId)) - refreshProjection(childSessionId) + prepareLevel(childSessionId) } useEffect(() => { @@ -736,6 +742,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { } pinnedRef.current = true if (!open) changeOpen(true) + prepareLevel(rootSessionId) queueMicrotask(() => { menuRef.current?.focus() }) } : () => { @@ -748,6 +755,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { event.preventDefault() if (variant === 'count' && !allowsHoverOpen()) pinnedRef.current = true if (!open) changeOpen(true) + prepareLevel(rootSessionId) queueMicrotask(() => { focusAt(0) }) }} > @@ -841,7 +849,7 @@ export function SubagentCatalogAction(props: SubagentCatalogActionProps) { /** Bind task-board visibility only in root conversations. */ function RootCatalogAction({ sessionId, useProjection, useSessions, useSessionStatus, useFooterAvailable, - openChild, openChildAside, refreshProjection, t, renderSlot, + openChild, openChildAside, refreshProjection, prepareCatalog, t, renderSlot, }: SubagentCatalogActionProps) { const hasSharedTasks = useProjection('agentTeam', team => team?.enabled === true && team.tasks.some(task => task.status !== 'deleted')) @@ -860,6 +868,7 @@ function RootCatalogAction({ openChild={openChild} openChildAside={openChildAside} refreshProjection={refreshProjection} + prepareCatalog={prepareCatalog} t={t} /> ) @@ -872,7 +881,7 @@ function RootCatalogAction({ */ export function SubagentHeaderLineage({ lineageSessionId, displayTitle, openTitle, - useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, t, + useSessions, useSession, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t, }: SubagentHeaderLineageProps) { const address = useSession(session => session.subagent?.address) const parentId = useSessions((state) => { @@ -883,7 +892,7 @@ export function SubagentHeaderLineage({ const summary = state.byId[lineageSessionId] return summary?.origin === 'subagent' ? summary.parentId : undefined }) - const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, t } + const shared = { useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t } // Root sessions carry no breadcrumb; their descendant count lives in the // header actions band (SubagentCatalogAction). if (parentId === undefined) return null diff --git a/packages/client/ui-subagent/src/client/index.ts b/packages/client/ui-subagent/src/client/index.ts index a84992246d..b44d4f8e55 100644 --- a/packages/client/ui-subagent/src/client/index.ts +++ b/packages/client/ui-subagent/src/client/index.ts @@ -62,6 +62,19 @@ export function apply(ctx: ClientContext): void { preferNewPane: true, }) }, + async prepareCatalog(parentSessionId: SessionId) { + await ctx.sessions.refreshProjections(parentSessionId) + const parent = ctx.sessions.list.getSnapshot().projectionsBySession[parentSessionId] + if (parent?.state !== 'ready') return + for (const entry of parent.values.subagentCatalog ?? []) { + if (entry.mode === 'external') continue + const state = ctx.sessions.list.getSnapshot() + if (state.byId[entry.id]?.formatStatus === 'migration-required' + || state.projectionsBySession[entry.id]?.state === 'migration-required' + || state.projectionsBySession[entry.id]?.state === 'error') continue + await ctx.sessions.refreshProjections(entry.id) + } + }, refreshProjection(parentSessionId: SessionId) { void ctx.sessions.refreshProjections(parentSessionId) }, diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index 27a5b61391..e7edefbb2c 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -27,7 +27,6 @@ export const zh = { 'tokens.total': '{value} tok', 'loading.label': '正在加载子智能体…', 'load.error': '无法加载子智能体', - 'catalog.migrationRequired': '需要迁移', 'retry': '重试', 'mode.external': '外部任务', 'mode.oneShot': '一次性', @@ -78,7 +77,6 @@ export const en: Record = { 'tokens.total': '{value} tok', 'loading.label': 'Loading subagents…', 'load.error': 'Unable to load subagents', - 'catalog.migrationRequired': 'Migration required', 'retry': 'Retry', 'mode.external': 'External task', 'mode.oneShot': 'one-shot', @@ -132,7 +130,6 @@ export const ja = { 'tokens.total': '{value} tok', 'loading.label': 'サブエージェントを読み込み中…', 'load.error': 'サブエージェントを読み込めません', - 'catalog.migrationRequired': '移行が必要です', 'retry': '再試行', 'mode.external': '外部タスク', 'mode.oneShot': '単発', @@ -183,7 +180,6 @@ export const es = { 'tokens.total': 'Tok {value}', 'loading.label': 'Cargando subagentes…', 'load.error': 'No se pueden cargar subagentes', - 'catalog.migrationRequired': 'Migración requerida', 'retry': 'Reintentar', 'mode.external': 'tarea externa', 'mode.oneShot': 'un solo disparo', @@ -234,7 +230,6 @@ export const fr = { 'tokens.total': 'Jeton {value}', 'loading.label': 'Chargement des sous-agents…', 'load.error': 'Impossible de charger les sous-agents', - 'catalog.migrationRequired': 'Migration requise', 'retry': 'Réessayer', 'mode.external': 'Tâche externe', 'mode.oneShot': 'un coup', @@ -285,7 +280,6 @@ export const de = { 'tokens.total': '{value}-Token', 'loading.label': 'Subagenten werden geladen…', 'load.error': 'Subagenten können nicht geladen werden', - 'catalog.migrationRequired': 'Migration erforderlich', 'retry': 'Erneut versuchen', 'mode.external': 'Externe Aufgabe', 'mode.oneShot': 'One-Shot', @@ -336,7 +330,6 @@ export const ru = { 'tokens.total': '{value} ток', 'loading.label': 'Загрузка субагентов…', 'load.error': 'Невозможно загрузить субагенты', - 'catalog.migrationRequired': 'Требуется миграция', 'retry': 'Повторить', 'mode.external': 'Внешняя задача', 'mode.oneShot': 'одноразовый', @@ -387,7 +380,6 @@ export const pt = { 'tokens.total': '{value} valor', 'loading.label': 'Carregando subagentes…', 'load.error': 'Não foi possível carregar subagentes', - 'catalog.migrationRequired': 'Migração necessária', 'retry': 'Tentar novamente', 'mode.external': 'Tarefa externa', 'mode.oneShot': 'tiro único', diff --git a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts index b5006a277b..83c5839e8d 100644 --- a/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts +++ b/packages/client/ui-subagent/tests/browser-plugin.client.spec.ts @@ -4,7 +4,7 @@ import { Context } from '@deepseek-ai/cordis' import { stubConfigForm } from '@deepseek-ai/dsh-client-test-runtime' import { describe, expect, it, onTestFinished, vi } from 'vitest' import type { - SessionListState, SessionSnapshot, SessionSummary, + SessionListState, SessionSnapshot, SessionSummary, SessionProjectionSnapshot, } from '@deepseek-ai/dsh-api-session-controller/client' import type { SubagentAddress } from '@deepseek-ai/dsh-subagent/client' import { SlotRegistry } from '@deepseek-ai/dsh-client-ui-renderer/client' @@ -35,7 +35,8 @@ const sid = (id: string) => id as SessionId function sessionsWith(sessions: SessionSummary[]) { const byId: Record = {} for (const s of sessions) byId[s.id] = s - const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: {} } + const projections: Record = {} + const snapshot: SessionListState = { ids: sessions.map(s => s.id), byId, phase: 'ready', projectionsBySession: projections } const actionCalls: { method: string; args: unknown[] }[] = [] const address: SubagentAddress = { parentSessionId: sid('parent'), @@ -48,6 +49,7 @@ function sessionsWith(sessions: SessionSummary[]) { subscribe: () => () => {}, }, actionCalls, + projections, subagentAddress: (childSessionId: SessionId) => childSessionId === address.childSessionId ? address : undefined, @@ -121,6 +123,40 @@ describe('apply', () => { expect(ctx.slots.entries('conversation.session.header.actions.subagent.footer')).toHaveLength(1) }) + it('reads direct child catalogs sequentially after reading the parent', async () => { + const { ctx, face } = await fullBench([...FAMILY, summary({ id: sid('legacy'), formatStatus: 'migration-required' })]) + onTestFinished(() => ctx.fiber.dispose()) + const entry = ctx.slots.entries('conversation.session.header.lineage') + .find(entry => entry.component === SubagentHeaderLineage)! + const actions = (entry.inject as (id: SessionId) => SubagentCatalogInjected)(sid('parent')) + const projections = face.projections + const held = Promise.withResolvers() + const refresh = vi.spyOn(face, 'refreshProjections').mockImplementation(async (id) => { + if (id === sid('parent')) projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [ + { id: sid('external'), mode: 'external', createdAt: 1 }, + ...['c1', 'c2', 'legacy', 'blocked', 'failed'].map(id => ({ id: sid(id), mode: 'one-shot' as const, createdAt: 1 })), + ] } } + if (id === sid('c1')) { + await held.promise + projections[id] = { state: 'ready', error: null, values: { subagentCatalog: [ + { id: sid('grandchild'), mode: 'one-shot', createdAt: 1 }, + ] } } + } + }) + onTestFinished(() => { refresh.mockRestore() }) + projections[sid('blocked')] = { state: 'migration-required', error: null, values: {} } + projections[sid('failed')] = { state: 'error', error: null, values: {} } + const reading = actions.prepareCatalog(sid('parent')) + await vi.waitFor(() => { expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')]]) }) + held.resolve(undefined) + await reading + expect(refresh.mock.calls).toEqual([[sid('parent')], [sid('c1')], [sid('c2')]]) + await actions.prepareCatalog(sid('c2')) + projections[sid('c2')] = { state: 'ready', error: null, values: {} } + await actions.prepareCatalog(sid('c2')) + expect(refresh.mock.calls.slice(3)).toEqual([[sid('c2')], [sid('c2')]]) + }) + it('registers catalog actions and selects read-only subagent composers from session facts', async () => { const { ctx, face } = await fullBench(FAMILY) const catalogEntry = ctx.slots.entries('conversation.session.header.lineage') diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index 43d2255936..ea189bcd8e 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -75,31 +75,44 @@ function props( ) { const catalogs = value === undefined ? nested : { [PARENT]: value, ...nested } const statuses: SessionStatusSnapshot = new Map() + const byId: Record = { + ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { + id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, projectionValues: { subagentCatalog: [] }, + }]))), + [CHILD]: { + id: CHILD, + title: '正在扫描项目文件', + displayTitle: 'worker', + running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), + retainedBy: {}, + blank: false, + updatedAt: Date.now(), + projectionValues: { subagentCatalog: [] }, + }, + ...summaries, + } const state = { ids: [CHILD], - byId: summaries ?? { - ...Object.fromEntries(Object.values(catalogs).flatMap(catalog => catalog.entries.map(entry => [entry.id, { - id: entry.id, displayTitle: entry.label ?? entry.id, running: entry.activity === 'running', blank: false, updatedAt: 1, retainedBy: {}, - }]))), - [CHILD]: { - id: CHILD, - title: '正在扫描项目文件', - displayTitle: 'worker', - running: Object.values(catalogs).some(catalog => catalog.entries.some(entry => entry.id === CHILD && entry.activity === 'running')), - retainedBy: {}, - blank: false, - updatedAt: Date.now(), - }, - }, + byId, phase: 'ready', - projectionsBySession: Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { - state: catalog.state, error: catalog.error, - values: { - ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, - subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), - }, - }])) , + projectionsBySession: { + ...Object.fromEntries(Object.entries(byId).flatMap(([id, entry]) => entry.projectionValues === undefined ? [] : [[id, { + state: 'idle' as const, error: null, values: entry.projectionValues, + }]])), + ...Object.fromEntries(Object.entries(catalogs).map(([id, catalog]) => [id, { + state: catalog.state, error: catalog.error, + values: { + ...byId[id as SessionId]?.projectionValues, + ...catalog.team === undefined ? {} : { agentTeam: catalog.team }, + subagentCatalog: catalog.entries.map(({ activity: _activity, ...entry }) => ({ ...entry, createdAt: 1 })), + }, + }])), + }, } satisfies SessionListState + for (const [id, entry] of Object.entries(byId)) { + const projection = state.projectionsBySession[id] + if (projection !== undefined) byId[id as SessionId] = { ...entry, projectionValues: projection.values } + } function useSessions(select: (snapshot: SessionListState) => T): T { return select(state) } @@ -142,6 +155,7 @@ function props( openChild: vi.fn(), openChildAside: vi.fn(), refreshProjection: vi.fn(), + prepareCatalog: vi.fn<(id: SessionId) => Promise>().mockResolvedValue(), renderSlot: vi.fn(() => null), lineageSessionId: PARENT, displayTitle: 'Parent title', @@ -528,8 +542,8 @@ describe('SubagentHeaderLineage', () => { expect(screen.getByText('worker')).toBeTruthy() expect(screen.queryByText('正在扫描项目文件')).toBeNull() expect(screen.getByRole('treeitem', { name: /reviewer child-2 · 一次性 · 当前未运行/ })).toBeTruthy() - expect(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })).toBeTruthy() - expect(screen.getByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByRole('button', { name: '展开 reviewer 的下级子智能体' })).toBeNull() const sidebarButton = within(screen.getByRole('treeitem', { name: /worker/ })) .getByRole('button', { name: '在侧边栏打开 worker' }) @@ -732,8 +746,11 @@ describe('SubagentHeaderLineage', () => { expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(1) }) - it('aligns a known leaf with siblings whose child catalog is still unknown', () => { - render() + it('aligns a known leaf with siblings whose child catalog contains descendants', () => { + render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) expect(screen.getByRole('treeitem', { name: /worker/ }).children).toHaveLength(2) @@ -1043,6 +1060,7 @@ describe('SubagentHeaderLineage', () => { origin: 'subagent' as const, running: activity === 'running', projectionValues: { + subagentCatalog: [], subagentTiming: { settledMs, ...(id === 'finished' @@ -1111,6 +1129,7 @@ describe('SubagentHeaderLineage', () => { origin: 'subagent', running: true, projectionValues: { + subagentCatalog: [], subagentTiming: { settledMs: 0, active: { since: now - 5_000, through: now } }, }, }, @@ -1147,7 +1166,7 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(input.refreshProjection).toHaveBeenCalledWith(CHILD) + expect(input.refreshProjection).not.toHaveBeenCalled() const nested = screen.getByRole('treeitem', { name: /indexer/ }) expect(nested.getAttribute('aria-level')).toBe('2') @@ -1158,15 +1177,15 @@ describe('SubagentHeaderLineage', () => { }) }) - it('keeps ordinary cold descendants loading until their real catalog arrives', () => { + it('reveals cold descendants only when shared catalog data arrives', () => { const secondGrandchild = 'grandchild-2' as SessionId const summaries = { [CHILD]: { ...summary(CHILD, 1), running: true }, [GRANDCHILD]: { - ...summary(GRANDCHILD, 1), parentId: CHILD, origin: 'subagent' as const, + ...summary(GRANDCHILD, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const, }, [secondGrandchild]: { - ...summary(secondGrandchild, 1), parentId: CHILD, origin: 'subagent' as const, + ...summary(secondGrandchild, 1), projectionValues: { subagentCatalog: [] }, parentId: CHILD, origin: 'subagent' as const, running: true, }, } @@ -1176,11 +1195,11 @@ describe('SubagentHeaderLineage', () => { const current = { ...deferred, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) } const view = render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() - expect(deferred.refreshProjection).toHaveBeenCalledWith(CHILD) - expect(screen.getByRole('group').getAttribute('aria-busy')).toBe('true') - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(deferred.refreshProjection).not.toHaveBeenCalled() + expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByRole('treeitem', { name: '正在加载子智能体' })).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() @@ -1193,7 +1212,7 @@ describe('SubagentHeaderLineage', () => { }, } view.rerender() - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() @@ -1213,16 +1232,161 @@ describe('SubagentHeaderLineage', () => { }, summaries) state = { ...state, projectionsBySession: ready.useSessions(value => value.projectionsBySession) } view.rerender() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) expect(screen.getByRole('group').getAttribute('aria-busy')).toBeNull() expect(screen.getByRole('treeitem', { name: /indexer/ }).querySelector('[data-state="idle"]')).not.toBeNull() expect(screen.getByRole('treeitem', { name: /critic/ }).querySelector('[data-state="ongoing"]')).not.toBeNull() expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryByText(/模式未知/)).toBeNull() - expect(deferred.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(deferred.refreshProjection).not.toHaveBeenCalled() expect(deferred.openChild).not.toHaveBeenCalled() }) - it.each([false, true])('shows list migration status before expanding, with cached descendants=%s', (cached) => { + it.each([ + { running: true, completed: false, dot: 'ongoing' }, + { running: false, completed: true, dot: 'done' }, + { running: false, completed: false, dot: 'idle' }, + ])('preserves the $dot activity marker while an unknown directory loads', ({ running, completed, dot }) => { + const input = props(catalog({ entries: [{ + id: CHILD, mode: 'continuable', label: 'worker', activity: running ? 'running' : 'inactive', + }] }), {}, { [CHILD]: { + ...summary(CHILD, 1), running, + projectionValues: { subagentTiming: { settledMs: 0, lastTurnCompleted: completed } }, + } }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '1 个子智能体' })) + const row = screen.getByRole('treeitem', { name: /worker/ }) + const marker = row.querySelector(`[data-state="${dot}"]`) + expect(marker).not.toBeNull() + expect(row.children).toHaveLength(1) + expect(input.refreshProjection).not.toHaveBeenCalled() + + state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: { + ...state.projectionsBySession[CHILD]!, state: 'loading', + } } } + view.rerender() + expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(row) + expect(row.querySelector(`[data-state="${dot}"]`)).toBe(marker) + expect(screen.queryByText('正在加载子智能体…')).toBeNull() + expect(row.hasAttribute('aria-busy')).toBe(false) + expect(row.hasAttribute('aria-expanded')).toBe(false) + expect(within(row).getByRole('button', { name: '在侧边栏打开 worker' }).hasAttribute('disabled')).toBe(false) + expect(input.refreshProjection).not.toHaveBeenCalled() + }) + + it('leaves missing catalogs unread and retries only an explicitly selected failure', () => { + const input = props(catalog(), {}, { [CHILD]: summary(CHILD, 1) }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() + + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, + [CHILD]: { state: 'error', values: {}, error: new RemoteError('gateway/internal', 'private diagnostic', {}) }, + } } + view.rerender() + expect(screen.getByRole('alert').textContent).toContain('无法加载子智能体') + expect(screen.queryByText('private diagnostic')).toBeNull() + expect(screen.queryByRole('status')).toBeNull() + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '重试' })) + expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(input.openChild).not.toHaveBeenCalled() + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, [CHILD]: { state: 'ready', values: { subagentCatalog: [] }, error: null }, + } } + view.rerender() + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(screen.getByRole('treeitem', { name: /worker/ }).getAttribute('aria-busy')).toBeNull() + }) + + it('expands cached shared projections without reading the next level', () => { + const childSummary = { ...summary(CHILD, 1), projectionValues: { subagentCatalog: [ + { id: GRANDCHILD, createdAt: 1, mode: 'continuable' as const, label: 'indexer' }, + ] } } + const input = props(catalog(), {}, { [CHILD]: childSummary, [GRANDCHILD]: summary(GRANDCHILD, 1) }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy() + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull() + + state = { ...state, projectionsBySession: { + ...state.projectionsBySession, [CHILD]: { state: 'ready', error: null, values: { subagentCatalog: [] } }, + } } + view.rerender() + expect(screen.queryByRole('button', { name: '收起 worker 的下级子智能体' })).toBeNull() + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + }) + + it('updates disclosure when a visible leaf gains children without fetching any level', () => { + const input = props(catalog()) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + const worker = screen.getByRole('treeitem', { name: /worker/ }) + expect(worker.hasAttribute('aria-expanded')).toBe(false) + state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: { + state: 'idle', error: null, values: { + subagentCatalog: [{ id: GRANDCHILD, createdAt: 1, mode: 'continuable', label: 'indexer' }], + }, + } } } + view.rerender() + expect(screen.getByRole('treeitem', { name: /worker/ })).toBe(worker) + expect(worker.getAttribute('aria-expanded')).toBe('false') + expect(input.refreshProjection).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + expect(screen.getByRole('treeitem', { name: /indexer/ })).toBeTruthy() + }) + + it('prepares only explicitly opened levels', () => { + const input = props(catalog(), { + [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), + }) + render() + const trigger = screen.getByRole('button', { name: /\d+ 个子智能体$/ }) + hoverCatalog(trigger) + expect(input.prepareCatalog).not.toHaveBeenCalled() + fireEvent.click(trigger) + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]]) + fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) + fireEvent.keyDown(screen.getByRole('dialog'), { key: 'Escape' }) + expect(input.prepareCatalog).toHaveBeenCalledTimes(2) + fireEvent.keyDown(trigger, { key: 'ArrowDown' }) + expect(input.prepareCatalog.mock.calls.at(-1)).toEqual([PARENT]) + }) + + it('reports an unexpected explicit catalog failure', async () => { + const input = props(catalog()) + const failure = new Error('projection reader failed') + input.prepareCatalog.mockRejectedValueOnce(failure) + const report = vi.spyOn(console, 'error').mockImplementation(() => {}) + try { + render() + fireEvent.click(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) + await vi.waitFor(() => { expect(report).toHaveBeenCalledWith('[ui-subagent] catalog discovery failed:', failure) }) + } finally { + report.mockRestore() + } + }) + + it.each([false, true])('keeps legacy rows navigable without a migration notice, with cached descendants=%s', (cached) => { const input = props(catalog(), cached ? { [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), } : {}, { @@ -1235,7 +1399,8 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(trigger) const child = screen.getByRole('treeitem', { name: /worker/ }) - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() fireEvent.keyDown(child, { key: 'ArrowRight' }) expect(input.refreshProjection).not.toHaveBeenCalled() @@ -1248,8 +1413,13 @@ describe('SubagentHeaderLineage', () => { view.rerender() hoverCatalog(trigger) expect(screen.queryByText(/需要迁移/)).toBeNull() - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + if (cached) { + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(input.refreshProjection).not.toHaveBeenCalled() + } else { + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() + expect(input.refreshProjection).not.toHaveBeenCalled() + } }) it.each(['ready', 'migration-required'] as const)('stops at a migration-required child until its real catalog arrives with %s read state', (readState) => { @@ -1272,7 +1442,7 @@ describe('SubagentHeaderLineage', () => { const current = { ...input, useSessions: (select: (snapshot: SessionListState) => T): T => select(state) } const view = render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) - fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 worker 的下级子智能体' })).toBeNull() expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() state = { @@ -1287,15 +1457,15 @@ describe('SubagentHeaderLineage', () => { expect(screen.queryByRole('treeitem', { name: /grandchild/ })).toBeNull() expect(screen.queryByRole('treeitem', { name: /ordinary-fork/ })).toBeNull() const child = screen.getByRole('treeitem', { name: /worker/ }) - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByText(/模式未知/)).toBeNull() - expect(en['catalog.migrationRequired']).toBe('Migration required') expect(child.hasAttribute('aria-expanded')).toBe(false) expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() expect(screen.queryByRole('group')).toBeNull() expect(screen.queryByText('正在加载子智能体…')).toBeNull() fireEvent.keyDown(child, { key: 'ArrowRight' }) - expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(input.refreshProjection).not.toHaveBeenCalled() expect(input.openChild).not.toHaveBeenCalled() fireEvent.click(child) expect(input.openChild).toHaveBeenCalledExactlyOnceWith({ @@ -1347,7 +1517,8 @@ describe('SubagentHeaderLineage', () => { fireEvent.keyDown(child, { key: 'ArrowRight' }) fireEvent.keyDown(child, { key: 'ArrowRight' }) expect(input.refreshProjection).not.toHaveBeenCalled() - expect(within(child).getByText(/需要迁移/)).toBeTruthy() + expect(within(child).queryByText(/需要迁移/)).toBeNull() + expect(child.getAttribute('aria-label')).not.toContain('需要迁移') expect(within(child).queryByText(/模式未知/)).toBeNull() expect(child.hasAttribute('aria-expanded')).toBe(false) expect(within(child).queryByRole('button', { name: /下级子智能体/ })).toBeNull() @@ -1406,7 +1577,30 @@ describe('SubagentHeaderLineage', () => { expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() }) - it('closes expanded descendants even when their own catalogs have not arrived', () => { + it('collapses expanded descendants whose catalog is removed before their parent closes', () => { + const input = props(catalog(), { + [CHILD]: catalog({ entries: [{ id: GRANDCHILD, mode: 'continuable', label: 'indexer', activity: 'inactive' }] }), + [GRANDCHILD]: catalog({ entries: [{ id: 'great-grandchild' as SessionId, mode: 'continuable', label: 'deep', activity: 'inactive' }] }), + }) + let state = input.useSessions(value => value) + const current = { ...input, useSessions: (select: (value: SessionListState) => T): T => select(state) } + const view = render() + fireEvent.click(screen.getByRole('button', { name: '2 个子智能体' })) + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' })) + const { [GRANDCHILD]: _projection, ...projectionsBySession } = state.projectionsBySession + const { [GRANDCHILD]: _summary, ...byId } = state.byId + state = { ...state, projectionsBySession, byId } + view.rerender() + fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) + expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() + state = input.useSessions(value => value) + view.rerender() + fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) + expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-expanded')).toBe('false') + }) + + it('closes a branch while the visible descendants are loading', () => { const input = props(catalog(), { [CHILD]: catalog({ entries: [{ @@ -1414,11 +1608,12 @@ describe('SubagentHeaderLineage', () => { label: 'indexer', activity: 'running', }], }), - }) + }, { [GRANDCHILD]: summary(GRANDCHILD, 1) }) render() hoverCatalog(screen.getByRole('button', { name: /\d+ 个子智能体$/ })) fireEvent.click(screen.getByRole('button', { name: '展开 worker 的下级子智能体' })) - fireEvent.click(screen.getByRole('button', { name: '展开 indexer 的下级子智能体' })) + expect(screen.queryByRole('button', { name: '展开 indexer 的下级子智能体' })).toBeNull() + expect(screen.getByRole('treeitem', { name: /indexer/ }).getAttribute('aria-busy')).toBeNull() fireEvent.click(screen.getByRole('button', { name: '收起 worker 的下级子智能体' })) expect(screen.queryByRole('treeitem', { name: /indexer/ })).toBeNull() diff --git a/snapshots/web/subagent-conversation/disclosures.expected.md b/snapshots/web/subagent-conversation/disclosures.expected.md new file mode 100644 index 0000000000..fa9997580d --- /dev/null +++ b/snapshots/web/subagent-conversation/disclosures.expected.md @@ -0,0 +1,8 @@ +- tree "Subagent sessions": + - treeitem "event-sourcing researcher agent-1 · continuable · completed 7.9K tok · {{duration}}" [level=1]: + - button "Expand event-sourcing researcher descendants" + - text: event-sourcing researcher agent-1 7.9K tok {{duration}} + - button "Open event-sourcing researcher in sidebar" + - treeitem "event-sourcing reviewer recorded-one-shot · one-shot · completed 0 tok · {{duration}}" [level=1]: + - text: event-sourcing reviewer recorded-one-shot 0 tok ~6mo 12d + - button "Open event-sourcing reviewer in sidebar" From c867b5cc7e0aeb24f962d61d8417a57e7ae96cae Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Thu, 5 Nov 2026 15:49:11 +0800 Subject: [PATCH 079/103] docs(ui-subagent): align catalog preparation descriptions --- .../2026-09-29-explicit-session-history-preparation.i18n.yaml | 4 ++-- .../2026-09-29-explicit-session-history-preparation.md | 2 +- .../2026-09-29-explicit-session-history-preparation.zh.md | 2 +- packages/client/ui-subagent/README.i18n.yaml | 4 ++-- packages/client/ui-subagent/README.md | 4 ++-- packages/client/ui-subagent/README.zh.md | 4 ++-- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml index ddd6d80912..5a918c8cc1 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.i18n.yaml @@ -9,8 +9,8 @@ en: ab63c8127d68d294 zh: d3f99489c96ff1d4 /agent-note-open-the-session-when-migration-is-required/decision: - en: 32627d744a6e7410 - zh: 2836a95ee5390111 + en: 310ff84cece51901 + zh: a9a29e3ba30e03a8 /agent-note-open-the-session-when-migration-is-required/alternatives-considered: en: baea781018a49252 zh: bcc452029bf229fd diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md index 84b30b6cb4..c452ae85ae 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.md @@ -18,7 +18,7 @@ Other fork callers omit that option and allow automatic migration. The `formatStatus` returned by `stat` carries the migration library's existing classification; `header` remains the current logical format. It describes the stored format, not migration-task progress or prepared in-memory history. -When migration is required and `subagentCatalog` is absent, Web marks the Session's row “Migration required” and keeps its history-opening actions without descendant expansion or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch. +When migration is required and `subagentCatalog` is absent, Web keeps the Session row's history-opening actions without a format notice, descendant expansion, or changing its subagent mode. Opening the Session supplies its catalog through history and control projections. Available catalogs remain usable, including empty catalogs. Session-list lineage resolves navigation addresses, not missing catalog membership. Ordinary loading, cancellation, and storage errors do not become this migration branch. Create/adopt, full-text search, and ordinary history opening allow automatic migration. diff --git a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md index 31925f7a9f..e68747a9b6 100644 --- a/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md +++ b/.agents/notes/implemented/architecture/2026-09-29-explicit-session-history-preparation.zh.md @@ -18,7 +18,7 @@ WorkspaceBrowser 行菜单的 fork 请求携带 `allowMigration: false`,由 Ho `stat` 返回的 `formatStatus` 携带迁移库已有的分类;`header` 仍是当前逻辑格式。它描述存储格式,不描述迁移任务进度或内存准备缓存。 -在需要迁移且缺少 `subagentCatalog` 时,Web 将该会话行标为“需要迁移”,保留打开历史的操作,但不能展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。 +在需要迁移且缺少 `subagentCatalog` 时,Web 保留该会话行打开历史的操作,不显示格式提示,不展开下级,也不改变子会话的 mode。打开会话后,历史与 control 投影提供其目录。已有目录仍可使用,包括空目录。会话列表的谱系用于解析导航地址,不用于补齐缺失的目录成员。普通加载、取消和存储错误不转换成这一迁移分支。 create/adopt、全文搜索和普通历史打开允许自动迁移。 diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index 37ef8fd189..ae80fd109c 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -30,8 +30,8 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 22b8ca76ca8d64a6 - zh: 300231110a4a208d + en: c7a6ed23ce7ec331 + zh: 92b60359a490b270 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: en: dcbc58d4cad47fa8 zh: e962a8cbdfd4a914 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 74810feff4..325dde5777 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -61,11 +61,11 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering, hovering, and expanding the tree use only local projections and never request missing catalogs. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. +The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Opening a catalog dropdown does not request its root catalog. Only explicit failed-read retries call `refreshProjection`; the Session object layer owns request deduplication and reconnect recovery. +Explicit menu activation and branch expansion call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. Failed-read retry buttons call `refreshProjection`; the Session object layer deduplicates reads and refreshes previously requested projections after reconnect. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 3ea5bef7e9..fea6f5d76c 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -61,11 +61,11 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染、悬停和展开目录树仅使用本地投影,不会请求缺失目录。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 +页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -打开目录下拉菜单不会请求其根目录。只有显式重试失败读取时才调用 `refreshProjection`;Session 对象层负责请求去重和重连恢复。 +显式激活菜单或展开分支时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。失败读取的重试按钮调用 `refreshProjection`;Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 From 42abd55ef224fa03d52f561d9567935eb1428154 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Sat, 7 Nov 2026 01:31:34 +0800 Subject: [PATCH 080/103] test(web): stabilize history paging e2e against auto-prefetch --- apps/web/tests/chat-scroll-contract.e2e.ts | 87 +++++++++++++++++----- apps/web/tests/preview-boot.e2e.ts | 9 ++- 2 files changed, 76 insertions(+), 20 deletions(-) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 1a0c751c8d..bccac447e1 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -367,13 +367,71 @@ async function flingTranscript(page: Page, deltaY: number): Promise { await nextPaint(page) } -async function wheelToHistoryStart(page: Page): Promise { - for (let attempt = 0; attempt < 12; attempt += 1) { - if ((await scrollGeometry(page)).scrollTop <= 1) break - await wheelTranscript(page, -2_400) +/** + * Hold paging responses so auto-prefetch cannot publish a page mid-gesture. + * @param page - Chat page under test. + * @returns an idempotent release that resumes held responses and awaits them. + */ +async function holdHistoryPages(page: Page): Promise<() => Promise> { + const gate = Promise.withResolvers() + const pending = new Set>() + const hold = (route: Route): Promise => { + const work = gate.promise.then(() => route.continue()) + pending.add(work) + return work.finally(() => { pending.delete(work) }) } - await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 }) - .toBeLessThanOrEqual(1) + await page.route('**/api/session/page', hold) + let released = false + return async () => { + if (released) return + released = true + gate.resolve(undefined) + // Resume held requests before removing the handler: unregistering with a + // hold still pending lets Playwright handle that route itself, after which + // the delayed continue() fails with "Route is already handled". + while (pending.size > 0) await Promise.all([...pending]) + await page.unroute('**/api/session/page', hold) + } +} + +/** + * Wait until a released page has landed and the history control stopped changing. + * @param page - Chat page under test. + * @returns the settled rendered row count. + */ +async function settleHistoryPaging(page: Page): Promise { + let rows = -1 + await expect.poll(async () => { + if (await page.locator('[data-chat-history]').getAttribute('data-chat-history') === 'loading') return false + const current = await loadedFlowRows(page) + const stable = current === rows + rows = current + return stable + }, { timeout: 30_000 }).toBe(true) + await nextPaint(page) + return rows +} + +/** + * Wheel back to the start of the loaded window. + * @param page - Chat page under test. + * @param options - holdPaging keeps auto-prefetch from publishing a page that re-anchors the viewport mid-scroll. + */ +async function wheelToHistoryStart(page: Page, options: { holdPaging?: boolean } = {}): Promise { + const release = options.holdPaging === true ? await holdHistoryPages(page) : undefined + try { + for (let attempt = 0; attempt < 12; attempt += 1) { + if ((await scrollGeometry(page)).scrollTop <= 1) break + await wheelTranscript(page, -2_400) + } + await expect.poll(async () => (await scrollGeometry(page)).scrollTop, { timeout: 10_000 }) + .toBeLessThanOrEqual(1) + } finally { + await release?.() + } + // A held page is released at the history edge, where the client publishes it + // as soon as it arrives; settle that prepend before the caller measures. + if (options.holdPaging === true) await settleHistoryPaging(page) } async function wheelUntilMounted(page: Page, selector: string, deltaY: number): Promise { @@ -478,14 +536,7 @@ async function expectMarkerAboveComposer(page: Page, marker: string): Promise { // Auto-prefetch may start while scrolling to the button. Hold its response until the reading anchor is captured. - const gate = Promise.withResolvers() - const pending = new Set>() - const hold = (route: Route): Promise => { - const work = gate.promise.then(() => route.continue()) - pending.add(work) - return work.finally(() => { pending.delete(work) }) - } - await page.route('**/api/session/page', hold) + const release = await holdHistoryPages(page) try { await wheelToHistoryStart(page) const history = page.locator('[data-chat-history]') @@ -495,7 +546,7 @@ async function loadEarlierWithAnchor(page: Page): Promise { const anchor = await visibleFlowAnchor(page) const before = await loadedFlowRows(page) await older.click() - gate.resolve(undefined) + await release() await expect.poll(async () => ( await loadedFlowRows(page) > before && await history.getAttribute('data-chat-history') === 'idle' ), { timeout: 30_000 }).toBe(true) @@ -507,9 +558,7 @@ async function loadEarlierWithAnchor(page: Page): Promise { await expectSameFlowTop(page, anchor) return true } finally { - gate.resolve(undefined) - await page.unroute('**/api/session/page', hold) - await Promise.all([...pending]) + await release() } } @@ -1754,7 +1803,7 @@ describe('web e2e: long Chat scroll contract', () => { ) await loadEarlierWithAnchor(world.page) await loadEarlierWithAnchor(world.page) - await wheelToHistoryStart(world.page) + await wheelToHistoryStart(world.page, { holdPaging: true }) await wheelTranscript(world.page, 1_300) const sessionAnchor = await visibleFlowAnchor(world.page) diff --git a/apps/web/tests/preview-boot.e2e.ts b/apps/web/tests/preview-boot.e2e.ts index f1ea40b25c..72ce0e6872 100644 --- a/apps/web/tests/preview-boot.e2e.ts +++ b/apps/web/tests/preview-boot.e2e.ts @@ -551,7 +551,14 @@ async function bootPreview(site: Site, manifest: ImageManifest, browser: Browser await catalog.getByRole('treeitem', { name: /Continue preview verification/ }).waitFor() await catalog.press('Escape') - await page.getByRole('button', { name: 'Load earlier', exact: true }).click() + // Auto-prefetch may already have published the page, and a pointer click can + // land on whatever moved under it; activate the control only while it still + // offers a page, then wait for the oldest seeded row. + const historyEdge = page.locator('[data-chat-history]') + await historyEdge.getByRole('button').evaluate((button) => { + if (!(button instanceof HTMLButtonElement)) throw new Error('history control is not a button') + if (!button.disabled) button.click() + }) await page.getByText(SHOWCASE_OLDEST, { exact: true }).waitFor({ timeout: 15_000 }) await requestLazyChunk(page, site, manifest) From f8237c051ec95acf055777d482e8e44fd5d5e9d4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 11:34:09 +0800 Subject: [PATCH 081/103] Describe mouseMove as a request to move to the target --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/types.ts | 7 ++++--- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../session/ptc-script-retained/system-prompt.expected.md | 2 +- 7 files changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 9a388e5d0c..46b035112e 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -210,7 +210,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 1ae598bdc9..341796b8c4 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -210,7 +210,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 0ce5da8944..745ccfe9be 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -32,7 +32,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 9f13f5b3c4..b84663f9e2 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -191,12 +191,13 @@ export interface CuaWindow extends CuaSurface { */ getScreenshot(options?: CuaObservationOptions): Promise /** - * Hover over an element or a point without pressing a button. The provider reports the route and whether the system pointer moved. + * Request a mouse move to an element or a point without pressing a button. + * The provider reports the route and whether the system pointer moved. * Returning and subsequent observations do not restore the previous pointer position. - * Other input and application changes can interrupt hover; observe before continuing. + * Other input and application changes can interrupt the interaction; observe before continuing. * @param target - current element id or screenshot-local [x,y]. * @param options - coordinate mode; applies only to [x,y]. - * @returns dispatch evidence and the selected route; observe the resulting UI after its hover delay. + * @returns dispatch evidence and the selected route; observe the resulting UI after any UI delay. */ mouseMove(target: CuaElementId | readonly [number, number], options?: CuaCoordinateOptions): Promise /** diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index a67bc45042..0b9c1b29f6 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -67,7 +67,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 000bbe3322..587436227a 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -69,7 +69,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 09031991fc..dd88fa8d9e 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -69,7 +69,7 @@ Element ids are opaque strings from the latest successful tree; the object facad ## Simulated mouse Use an explicit window for screenshots and pointer input. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. -- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — hover over the target without pressing; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying. - scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. - drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. From 636c34f5a6610541d725a3ee0ea2b683c71ce289 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 12:17:15 +0800 Subject: [PATCH 082/103] feat(cua): support overlapping macOS key presses --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 4 +- .../Sources/CuaNative/KeyboardInput.swift | 109 ++++++++---------- .../Sources/CuaNative/RequestAdmission.swift | 9 ++ .../cua-macos/native/protocol.schema.json | 16 ++- .../native/tests/capabilities_e2e.py | 6 + .../tests/swift/KeyboardChordTests.swift | 36 ++++++ .../cua-macos/tests/guidance.spec.ts | 4 +- packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/protocol.ts | 2 +- packages/experimental/cua/src/types.ts | 6 +- packages/experimental/cua/tests/api.spec.ts | 5 +- .../cua-native/system-prompt.expected.md | 2 +- .../cua-native/tool-schemas.expected.json | 16 ++- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 24 files changed, 158 insertions(+), 91 deletions(-) create mode 100644 packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 0d83c6e538..bcc12b8ecc 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 533ed4dd11af5126 - zh: 03036e8c949d6aca + en: e3643640ef764471 + zh: 5d25e833cb78bf9b /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 46b035112e..63e1c495d2 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -79,7 +79,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. `getApp` returns the `appHandle` used by every app-targeted operation, and `app.getWindow(windowId)` returns the object that owns screenshots and pointer input. -`pressKey(key, modifiers?)` presses and releases one key. Pass modifier names separately, for example `pressKey('Tab', ['shift'])` or `pressKey('+')`; an omitted modifier array means none. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. On macOS, use `pressKey` on the App object. The shared `sendKeyEvent` operation returns `NOT_IMPLEMENTED` on this provider. +`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct keys. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass modifier names separately, for example `pressKey('Tab', ['shift'])` or `pressKey('+')`; an omitted modifier array means none. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. On macOS, use `pressKey` on the App object. The shared `sendKeyEvent` operation returns `NOT_IMPLEMENTED` on this provider. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -221,7 +221,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 341796b8c4..276f725cb3 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -79,7 +79,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。`getApp` 返回每个面向应用的操作所需的 `appHandle`,`app.getWindow(windowId)` 返回负责截图和指针输入的对象。 -`pressKey(key, modifiers?)` 按下并释放一个键。修饰键名称单独传入,例如 `pressKey('Tab', ['shift'])` 或 `pressKey('+')`;省略修饰键数组表示不按修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。在 macOS 上,通过 App 对象调用 `pressKey`。调用共享接口 `sendKeyEvent` 会收到 `NOT_IMPLEMENTED`。 +`pressKey(key, modifiers?)` 接受单个键名或由不同键名组成的非空数组。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。修饰键名称单独传入,例如 `pressKey('Tab', ['shift'])` 或 `pressKey('+')`;省略修饰键数组表示不按修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。在 macOS 上,通过 App 对象调用 `pressKey`。调用共享接口 `sendKeyEvent` 会收到 `NOT_IMPLEMENTED`。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -221,7 +221,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 8d43fbd6b8..6e9294f0ce 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 88a59904ca4ebedc zh: 14f2b666d7382145 /dsh-cua-native-helper/observation-and-input: - en: 2d380e942a4057e4 - zh: fe7c9339ec63a6e5 + en: d19180b1a6db2e48 + zh: c6279db9957218eb /dsh-cua-native-helper/verification: en: 49f4cce2a4cc3114 zh: e9d65c92ef35fe24 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index bc80110951..b94d053746 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -103,7 +103,7 @@ Clicks send mouse-down and mouse-up events at the element center or the supplied Capture and pointer delivery read CG bounds before and after an exact-window AX frame query. Movement during the query returns WINDOW_CHANGED. Valid AX/CG frames must have equal outward-rounded integral point rectangles; a known mismatch returns WINDOW_CHANGED before mouse movement, priming or button delivery. The helper preserves both coordinate sources rather than substituting AX geometry for CG geometry. Missing or unusable AX geometry remains unknown, while AX communication, permission and invalid-element errors propagate. Capture without Accessibility permission retains its CG/SCK checks. Advertised AX actions bypass this pointer preflight; an AX action error does not trigger pointer input. These reads do not lock the window against later movement, and no geometry check activates or raises it. -`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses and releases one key while holding its `modifiers` array, sends PID-targeted modifier transitions, and releases those modifiers in reverse order; these events do not use the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. +`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses its modifiers followed by the requested keys in order, then releases all pressed keys in reverse order, including on cancellation; these events do not use the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 0927a82bce..7ddde7d4f4 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -103,7 +103,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 截图和鼠标输入在精确窗口的 AX 边界查询前后读取 CG 边界,查询期间移动会返回 WINDOW_CHANGED。有效的 AX/CG 边界向外取整后必须一致;已知不一致会在移动、预备事件或按键发送前返回 WINDOW_CHANGED。helper 保留两个坐标来源,不用 AX 几何替换 CG 几何。缺失或无效的 AX 几何仍表示未知,AX 通信、权限和无效元素错误继续传递。无辅助功能权限的截图保留 CG/SCK 检查。声明的 AX 动作不经过鼠标预检,AX 动作失败也不改用鼠标输入。这些读取不会锁住窗口以阻止后续移动,几何检查不激活或抬起窗口。 -`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 在按住所列 `modifiers` 时按下并释放一个键,先向 PID 发送修饰键变化,再发送主键,并逆序释放修饰键,不使用全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 +`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和指定按键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index c4cc6066c8..da1afe5a3d 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -118,7 +118,7 @@ actor AXWorker { if let keyboard, let pointer { return (keyboard, pointer) } let poster = PIDEventPoster() let latch = cancellation - let key = KeyboardInput(poster: poster, textEventInterval: textEventInterval, checkCancellation: { try latch.check() }) + let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, checkCancellation: { try latch.check() }) let mouse = WindowPointerInput(poster: poster, checkCancellation: { try latch.check() }) keyboard = key; pointer = mouse return (key, mouse) @@ -335,7 +335,7 @@ actor AXWorker { let recipient = try ax().keyboardRecipient(identity, catalog: catalog) try NativePlatform.verify(recipient) if method == "typeText" { try inputs().0.typeText(params.string("text"), to: recipient.pid) } - else { try inputs().0.pressKey(params.string("key"), modifiers: params.modifiers(), to: recipient.pid) } + else { try inputs().0.pressKey(params.pressKeys(), modifiers: params.modifiers(), to: recipient.pid) } case "setValue": try ax().setAttribute(element(handle, params), "AXValue", params.values["value"]) case "performAction": try ax().performAction(element(handle, params), action: params.string("action"), argument: params.values["argument"]) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index be75257f1c..2dbf648ecf 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -4,76 +4,62 @@ import Foundation /// Balanced PID-targeted chords and scalar-based Unicode input on one serial worker. final class KeyboardInput { - private struct Modifier { + private struct Key { let keyCode: CGKeyCode let flag: CGEventFlags } - private struct ModifierEvents { - let down: CGEvent - let up: CGEvent - } - - private let poster: PIDEventPoster + private let post: (CGEvent, Int32) -> Void private let textEventInterval: Double private let checkCancellation: @Sendable () throws -> Void - init(poster: PIDEventPoster, textEventInterval: Double, checkCancellation: @escaping @Sendable () throws -> Void = {}) { - self.poster = poster + init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, checkCancellation: @escaping @Sendable () throws -> Void = {}) { + self.post = post self.textEventInterval = textEventInterval self.checkCancellation = checkCancellation } - /// Construct the entire chord before posting; cleanup releases only keys pressed by this call. - func pressKey(_ key: String, modifiers: [String], to pid: Int32) throws { + /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. + func pressKey(_ keys: [String], modifiers: [String], to pid: Int32) throws { try checkCancellation() - var names = modifiers - let isPlus = key == "+" || key.lowercased() == "plus" - if isPlus { names.append("shift") } - let code = try Self.keyCode(isPlus ? "=" : key) - var selected: [Modifier] = [] - for name in names { - let modifier = try Self.modifier(name) - if !selected.contains(where: { $0.keyCode == modifier.keyCode }) { - selected.append(modifier) + var modifierNames = modifiers + let mainKeys = try keys.map { name -> Key in + if name == "+" || name.lowercased() == "plus" { + modifierNames.append("shift") + return Key(keyCode: try Self.keyCode("="), flag: []) } + if let modifier = Self.namedModifier(name) { return modifier } + return Key(keyCode: try Self.keyCode(name), flag: []) } - let source = try Self.source() + guard Set(mainKeys.map(\.keyCode)).count == mainKeys.count else { + throw RequestParameters.invalid("A chord must contain distinct physical keys") + } + var selected = Set() var flags: CGEventFlags = [] - var modifierEvents: [ModifierEvents] = [] - for modifier in selected { + var events: [(down: CGEvent, up: CGEvent)] = [] + let source = try Self.source() + for key in try modifierNames.map(Self.modifier) + mainKeys where selected.insert(key.keyCode).inserted { let releasedFlags = flags - flags.insert(modifier.flag) - modifierEvents.append(ModifierEvents( - down: try Self.keyEvent(source: source, code: modifier.keyCode, down: true, flags: flags), - up: try Self.keyEvent(source: source, code: modifier.keyCode, down: false, flags: releasedFlags) + flags.formUnion(key.flag) + events.append(( + down: try Self.keyEvent(source: source, code: key.keyCode, down: true, flags: flags), + up: try Self.keyEvent(source: source, code: key.keyCode, down: false, flags: releasedFlags) )) } - let down = try Self.keyEvent(source: source, code: code, down: true, flags: flags) - let up = try Self.keyEvent(source: source, code: code, down: false, flags: flags) - var heldModifiers = 0 - var keyHeld = false + var pressed = 0 do { defer { - if keyHeld { poster.post(up, to: pid) } - for index in (0.. 0 { Thread.sleep(forTimeInterval: 0.008) } } } - for events in modifierEvents { + for event in events { try checkCancellation() - poster.post(events.down, to: pid) - heldModifiers += 1 + post(event.down, pid) + pressed += 1 Thread.sleep(forTimeInterval: 0.008) } - try checkCancellation() - poster.post(down, to: pid) - keyHeld = true - Thread.sleep(forTimeInterval: 0.008) - try checkCancellation() - poster.post(up, to: pid) - keyHeld = false } try checkCancellation() } @@ -104,16 +90,16 @@ final class KeyboardInput { do { defer { if keyHeld { - poster.post(up, to: pid) + post(up, pid) Thread.sleep(forTimeInterval: textEventInterval) } } try checkCancellation() - poster.post(down, to: pid) + post(down, pid) keyHeld = true Thread.sleep(forTimeInterval: textEventInterval) try checkCancellation() - poster.post(up, to: pid) + post(up, pid) keyHeld = false Thread.sleep(forTimeInterval: textEventInterval) } @@ -139,22 +125,30 @@ final class KeyboardInput { return event } - private static func modifier(_ name: String) throws -> Modifier { + private static func namedModifier(_ name: String) -> Key? { switch name.lowercased() { - case "command", "cmd": return Modifier(keyCode: 55, flag: .maskCommand) - case "shift": return Modifier(keyCode: 56, flag: .maskShift) - case "option", "alt": return Modifier(keyCode: 58, flag: .maskAlternate) - case "control", "ctrl": return Modifier(keyCode: 59, flag: .maskControl) - case "fn": return Modifier(keyCode: 63, flag: .maskSecondaryFn) - default: throw NativeFailure(code: "INVALID_ARGUMENT", message: "Unsupported key modifier: \(name)") + case "command", "cmd": return Key(keyCode: 55, flag: .maskCommand) + case "shift": return Key(keyCode: 56, flag: .maskShift) + case "option", "alt": return Key(keyCode: 58, flag: .maskAlternate) + case "control", "ctrl": return Key(keyCode: 59, flag: .maskControl) + case "fn": return Key(keyCode: 63, flag: .maskSecondaryFn) + default: return nil } } + private static func modifier(_ name: String) throws -> Key { + guard let modifier = namedModifier(name) else { + throw NativeFailure(code: "INVALID_ARGUMENT", message: "Unsupported key modifier: \(name)") + } + return modifier + } + static func modifierFlags(_ names: [String]) throws -> CGEventFlags { try names.reduce(into: CGEventFlags()) { flags, name in flags.formUnion(try modifier(name).flag) } } static func keyCode(_ key: String) throws -> CGKeyCode { + if let modifier = namedModifier(key) { return modifier.keyCode } switch key.lowercased() { case "kp_0": return 82 case "kp_1": return 83 @@ -180,12 +174,7 @@ final class KeyboardInput { case "space": return 49 case "delete", "backspace": return 51 case "escape", "esc": return 53 - case "command", "cmd": return 55 - case "shift": return 56 case "capslock": return 57 - case "option", "alt": return 58 - case "control", "ctrl": return 59 - case "fn": return 63 case "home": return 115 case "pageup": return 116 case "del", "forward_delete": return 117 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 5eb70381e4..ef2b6dc101 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -36,6 +36,15 @@ struct RequestParameters: Sendable { return path } } + func pressKeys() throws -> [String] { + if let name = values["key"]?.string { + guard !name.isEmpty else { throw Self.invalid("key must not be empty") } + return [name] + } + let names = try strings("key") + guard !names.isEmpty else { throw Self.invalid("key must name at least one key") } + return names + } func optionalString(_ key: String) throws -> String? { contains(key) ? try string(key) : nil } func optionalBoolean(_ key: String) throws -> Bool? { guard let raw = values[key] else { return nil } diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index b0d74a84dc..aa6d201dcb 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -993,8 +993,20 @@ "maximum": 4294967295 }, "key": { - "type": "string", - "minLength": 1 + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + ] }, "modifiers": { "type": "array", diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 650aff14e9..95a94c97b6 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -191,6 +191,12 @@ def main(): call("drag", {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80, "toY": point["y"] + 20, "durationMs": 200, "steps": 10, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 27 and event.get("button") == 2 and event["shift"] for event in value["events"])) + call("pressKey", {**owner, "key": ["w", "d"]}) + expected_chord = [(10, 13), (10, 2), (11, 2), (11, 13)] + state = wait_for_state(state_file, lambda value: any( + event["type"] == 11 and event.get("keyCode") == 13 for event in value["events"])) + assert [(event["type"], event["keyCode"]) for event in state["events"] + if event.get("keyCode") in (13, 2)] == expected_chord, state["events"] call("pressKey", {**owner, "key": "KP_0"}) call("pressKey", {**owner, "key": "KP_Enter"}) state = wait_for_state(state_file, lambda value: {82, 76}.issubset({event.get("keyCode") for event in value["events"]})) diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift new file mode 100644 index 0000000000..ae98c891d6 --- /dev/null +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -0,0 +1,36 @@ +// Observe the actual CoreGraphics events without sending keyboard input to the desktop. +import CoreGraphics +import Testing +@testable import CuaNative + +@Test func chordKeepsModifiersThroughBothLetterReleases() throws { + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, pid in + #expect(pid == 42) + events.append(event) + }, textEventInterval: 0) + try input.pressKey(["w", "d"], modifiers: ["shift"], to: 42) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 13, 56]) + #expect(events.map(\.type) == [.flagsChanged, .keyDown, .keyDown, .keyUp, .keyUp, .flagsChanged]) + #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, true, false]) +} + +@Test(arguments: [1, 2]) +func cancelledChordReleasesOnlyPressedKeys(_ cancelAfter: Int) { + let cancellation = CancellationLatch() + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, _ in + events.append(event) + if events.count == cancelAfter { cancellation.cancel() } + }, textEventInterval: 0, checkCancellation: cancellation.check) + #expect(throws: NativeFailure.self) { try input.pressKey(["w", "d"], modifiers: [], to: 42) } + let held = [Int64(13), 2].prefix(cancelAfter) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == Array(held) + held.reversed()) + #expect(events.map(\.type) == Array(repeating: .keyDown, count: cancelAfter) + Array(repeating: .keyUp, count: cancelAfter)) +} + +@Test(arguments: [["w", "unknown"], ["w", "W"], ["Enter", "Return"]]) +func invalidChordPostsNoInput(_ keys: [String]) { + let input = KeyboardInput(post: { _, _ in Issue.record("Invalid chord posted input") }, textEventInterval: 0) + #expect(throws: NativeFailure.self) { try input.pressKey(keys, modifiers: ["shift"], to: 42) } +} diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index c4a6aeec7d..f3e530b7de 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -89,7 +89,7 @@ it('preserves image formats and pointer modifier enums without restricting keybo for (const name of ['click', 'drag']) { expect(lines.find(line => line.startsWith(`- ${name}(`))).toContain("modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[]") } - expect(COMMON_GUIDANCE).toContain('pressKey(key: string, modifiers?: string[])') + expect(COMMON_GUIDANCE).toContain('pressKey(key: string | string[], modifiers?: string[])') expect(COMMON_GUIDANCE).toContain('Key and modifier names are platform-defined strings') }) @@ -130,7 +130,7 @@ it('documents facade initialization, emitted observations, and separate key argu expect(COMMON_GUIDANCE).toContain('host-provided bridge initialization once') expect(COMMON_GUIDANCE).toContain('not a preinstalled global') expect(COMMON_GUIDANCE).toContain('void await') - expect(COMMON_GUIDANCE).toContain('do not pack them into a chord string') + expect(COMMON_GUIDANCE).toContain("pressKey(['w', 'd']) presses W then D and releases D then W") expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index f4abb13c43..0d16bc4b02 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: 2ab74a1ff120459e - zh: 39b3ef198989f133 + en: e38d57709aa6d001 + zh: 231b2dcaf826d386 /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index c95e4ae8ec..e6c0f0778f 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and de Provider startup capabilities are fixed at installation: platform, methods, app-level accessibility, keyboard scopes, browser support, and coordinate space. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges both layers for the model-visible result. The raw RPC remains a common operation representation rather than a capability inventory, so provider guidance states the actions its platform supports. -Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers; `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. +Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` holds the listed modifiers while pressing the requested keys in order and releasing them in reverse. For example, `pressKey(['w', 'd'])` holds W through the D keystroke; `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. Platform providers import `CuaConfigFields` from `@deepseek-ai/dsh-cua/config` to extend the shared configuration. The root Host entry exports `installCua`, `CuaConfig`, and the Typert-discovered `CuaAccess` service; its `apply()` only marks the optional Client contribution. `/client` loads the permission UI through the existing module loader. Separate Host and Client compiler projects keep React, CSS, and browser registrations out of headless imports. `/api` owns the app/window API and its types; `/bridge`, `/native-client`, and `/protocol` retain runtime and platform consumers. `/types` exports only the named types required by generated Remote declarations. The Client uses package-local types. `/typert` supplies Host reflection and `/remote` supplies generated browser descriptors and codecs; permission authority remains on the Host. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index c1c5ed863c..2f8e31b77c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 提供方启动能力在安装时固定:平台、方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。原生 RPC 仍是通用操作表示,而不是能力清单,因此 provider 指引说明其平台支持的动作。 -通过 `await cua.getCapabilities()` 返回的 `methods` 和 `keyboard` 确认支持的操作和输入范围。`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键;`sendKeyEvent(key, direction)` 只发送一次按下或抬起。`typeText` 和 `paste` 在 provider 声明的键盘作用域内传送字面文本。键盘修饰键名称是 provider 解释的普通字符串。 +通过 `await cua.getCapabilities()` 返回的 `methods` 和 `keyboard` 确认支持的操作和输入范围。`pressKey(key, modifiers?)` 按住所列修饰键,依次按下指定的键,再逆序释放。例如,`pressKey(['w', 'd'])` 在按下和松开 D 期间持续按住 W。`sendKeyEvent(key, direction)` 只发送一次按下或抬起。`typeText` 和 `paste` 在 provider 声明的键盘作用域内传送字面文本。键盘修饰键名称是 provider 解释的普通字符串。 平台提供方从 `@deepseek-ai/dsh-cua/config` 导入 `CuaConfigFields` 来扩展共享配置。根 Host 入口导出 `installCua`、`CuaConfig` 和供 Typert 发现的 `CuaAccess` 服务,`apply()` 只标记可选 Client 贡献。`/client` 通过现有模块加载器加载权限界面。Host 和 Client 使用独立编译项目,headless 导入不会加载 React、CSS 或浏览器注册。`/api` 提供应用、窗口 API 及其类型;`/bridge`、`/native-client` 和 `/protocol` 保留运行时和平台消费者。`/types` 仅导出生成 Remote 声明所需的命名类型,Client 使用包内类型。`/typert` 提供 Host 反射,`/remote` 提供浏览器描述和编解码,权限判断仍由 Host 执行。 diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 745ccfe9be..0677be5433 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -43,6 +43,6 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 538c95cfe6..8488f32af3 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -62,7 +62,7 @@ export const Request = z.discriminatedUnion('method', [ selectionType: z.enum(['text', 'cursor_before', 'cursor_after']).optional() }), operation('typeText', { ...app, windowId: id.optional(), text: z.string() }), operation('paste', { ...app, windowId: id.optional(), text: z.string(), format: z.enum(['text', 'html']).optional() }), - operation('pressKey', { ...app, windowId: id.optional(), key: z.string().min(1), modifiers: z.array(z.string()).optional() }), + operation('pressKey', { ...app, windowId: id.optional(), key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]), modifiers: z.array(z.string()).optional() }), operation('sendKeyEvent', { ...app, windowId: id.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('scroll'), params: z.union([ z.object({ ...absoluteCoordinate, diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index b84663f9e2..875418d805 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -160,13 +160,13 @@ export interface CuaSurface { */ paste(text: string, options?: CuaPasteOptions): Promise /** - * Press and release one key at the current input focus. + * Press the keys in order at the current focus, then release them in reverse order. * Rejects when the provider does not support keyboard input at this scope. - * @param key - Provider-defined key name to press and release; not a chord. + * @param key - One provider-defined key name or a nonempty array of distinct keys to hold together. * @param modifiers - Platform- or provider-defined modifier names held for this keystroke; omitted means none. * @returns Whether the provider successfully executed the requested operation. */ - pressKey(key: string, modifiers?: string[]): Promise + pressKey(key: string | string[], modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. * Does not send the opposite event. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index cbaa419951..f5b3452dc3 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -683,6 +683,8 @@ describe('input actions', () => { ['fractional scroll', ({ window }) => window.scroll({ x: 0, y: 0, deltaLinesX: 0.5, deltaLinesY: 0 })], ['negative drag point', ({ window }) => window.drag([0, 0], [-1, 3])], ['empty key', ({ app }) => app.pressKey('')], + ['empty chord', ({ app }) => app.pressKey([])], + ['empty chord member', ({ app }) => app.pressKey(['w', ''])], ] it.each<[string, (surfaces: Surfaces) => Promise]>([ ['getState windowId: Too small: expected number to be >0', ({ app }) => app.getWindow(0)], @@ -708,7 +710,8 @@ describe('input actions', () => { expect(f.dispatch).toHaveBeenCalledTimes(calls) }) - it.each<[string, string[] | undefined, string[]]>([ + it.each<[string | string[], string[] | undefined, string[]]>([ + [['w', 'd'], undefined, []], ['+', undefined, []], ['plus', [], []], ['+', ['command'], ['command']], diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 0b9c1b29f6..a39b9145d4 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -78,7 +78,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 33f3636750..8f608ec54e 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -1032,8 +1032,20 @@ "maximum": 4294967295 }, "key": { - "type": "string", - "minLength": 1 + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "minItems": 1, + "type": "array", + "items": { + "type": "string", + "minLength": 1 + } + } + ] }, "modifiers": { "type": "array", diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 587436227a..017e5b103b 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -80,7 +80,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index dd88fa8d9e..ef58a12bd2 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -80,7 +80,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From ee8f1d8dabf08bd2bb63667d0f578c0e7cc1708b Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 12:24:27 +0800 Subject: [PATCH 083/103] fix(ui-subagent): prepare child catalogs on retry --- apps/web/tests/subagent-conversation.e2e.ts | 11 ++++++++++- packages/client/ui-subagent/README.i18n.yaml | 4 ++-- packages/client/ui-subagent/README.md | 2 +- packages/client/ui-subagent/README.zh.md | 2 +- .../ui-subagent/src/client/SubagentHeaderLineage.tsx | 6 +++--- .../ui-subagent/tests/conversation-ui.client.spec.tsx | 6 ++++-- 6 files changed, 21 insertions(+), 10 deletions(-) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 71993bbe52..018f5e3f18 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -365,7 +365,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = if (failures.length > 1) throw new AggregateError(failures, 'subagent Web teardown failed') }) - it('discovers cold descendants one level at a time without leaving the parent conversation', async () => { + it('retries a failed cold catalog and discovers descendants without reopening the menu', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-subagent-unread-catalog')) const reads = apiCalls.filter(path => path === '/api/session/projections').length const observe = vi.spyOn(scaffold.ctx.sessionQuery, 'observeSession') @@ -383,7 +383,15 @@ describe('web e2e: persisted subagent conversation and human continuation', () = expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads) expect(observe).not.toHaveBeenCalled() const parentUrl = page.url() + await page.route('**/api/session/projections', route => route.abort('failed'), { times: 1 }) await trigger.click() + const retry = tree.getByRole('button', { name: 'Retry', exact: true }) + await retry.waitFor() + expect(await tree.getByRole('button', { name: /^(Expand|Collapse) /u }).count()).toBe(0) + expect(apiCalls.filter(path => path === '/api/session/projections')).toHaveLength(reads + 1) + expect(projections).not.toHaveBeenCalled() + await retry.click() + await retry.waitFor({ state: 'detached' }) const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }) await expand.waitFor() await expect.poll(() => projections.mock.calls.map(([request]) => request.sessionId)).toEqual([parentId, childId, oneShotId]) @@ -408,6 +416,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await page.keyboard.press('Escape') await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' }) } finally { + await page.unroute('**/api/session/projections') observe.mockRestore() projections.mockRestore() } diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index ae80fd109c..e4ce63e820 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -30,8 +30,8 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: c7a6ed23ce7ec331 - zh: 92b60359a490b270 + en: 08735d4cc7569cfa + zh: 517309ca6a540adf /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: en: dcbc58d4cad47fa8 zh: e962a8cbdfd4a914 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 325dde5777..357453d99e 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -65,7 +65,7 @@ The header lineage renderer reads `subagentCatalog` only from `projectionsBySess Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. -Explicit menu activation and branch expansion call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. Failed-read retry buttons call `refreshProjection`; the Session object layer deduplicates reads and refreshes previously requested projections after reconnect. +Explicit menu activation, branch expansion, and failed-read retries call `prepareCatalog` to read the current catalog and its direct children. Ancestor-title clicks navigate to that Session. The Session object layer deduplicates reads and refreshes previously requested projections after reconnect. Breadcrumb addresses derive from the Provider-bound Session address, loaded parent catalogs, or already-listed subagent lineage, including never-selected ancestors. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index fea6f5d76c..5498652e1b 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -65,7 +65,7 @@ kind: "package-reference" 每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 -显式激活菜单或展开分支时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。失败读取的重试按钮调用 `refreshProjection`;Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 +显式激活菜单、展开分支或重试失败读取时,`prepareCatalog` 读取当前目录及其直接子节点。点击祖先标题会导航到该 Session。Session 对象层合并重复读取,并在重连后刷新之前请求过的投影。 面包屑地址从 Provider 所绑定的 Session 地址、已加载的 parent 目录或已列出的 subagent 谱系推导,也包括从未选中过的祖先。 diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index ab2b6e6a4b..cffac90f99 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -29,7 +29,7 @@ export type SubagentCatalogInjected = { openChild: (address: SubagentAddress) => void openChildAside: (address: SubagentAddress) => void refreshProjection: (parentSessionId: SessionId) => void - /** Read this catalog and its direct children after explicit activation. */ + /** Read this catalog and its direct children after explicit activation or retry. */ prepareCatalog: (parentSessionId: SessionId) => Promise } @@ -498,7 +498,7 @@ type CatalogDropdownProps = CatalogDropdownSharedProps & ( function CatalogDropdown(props: CatalogDropdownProps) { const { rootSessionId, currentSessionId, displayTitle, openTitle, variant, - useSessions, useSessionStatus, openChild, openChildAside, refreshProjection, prepareCatalog, t, hasSharedTasks = false, + useSessions, useSessionStatus, openChild, openChildAside, prepareCatalog, t, hasSharedTasks = false, } = props const ancestorSwitcher = variant === 'switcher' && openTitle !== undefined const projections = useSessions(state => state.projectionsBySession) @@ -812,7 +812,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { level={1} openChild={openChild} openChildAside={openChildAside} - refreshProjection={refreshProjection} + refreshProjection={prepareLevel} toggleBranch={toggleBranch} closeCatalog={() => { changeOpen(false) }} t={t} diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index ea189bcd8e..e3234cfef1 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -1297,7 +1297,8 @@ describe('SubagentHeaderLineage', () => { expect(screen.queryByRole('status')).toBeNull() expect(input.refreshProjection).not.toHaveBeenCalled() fireEvent.click(screen.getByRole('button', { name: '重试' })) - expect(input.refreshProjection).toHaveBeenCalledExactlyOnceWith(CHILD) + expect(input.prepareCatalog.mock.calls).toEqual([[PARENT], [CHILD]]) + expect(input.refreshProjection).not.toHaveBeenCalled() expect(input.openChild).not.toHaveBeenCalled() state = { ...state, projectionsBySession: { ...state.projectionsBySession, [CHILD]: { state: 'ready', values: { subagentCatalog: [] }, error: null }, @@ -1638,7 +1639,8 @@ describe('SubagentHeaderLineage', () => { hoverCatalog(screen.getByRole('button', { name: /0 个子智能体/ })) expect(screen.getByText('index down')).toBeTruthy() fireEvent.click(screen.getByRole('button', { name: /重试/ })) - expect(failed.refreshProjection).toHaveBeenCalledWith(PARENT) + expect(failed.prepareCatalog).toHaveBeenCalledExactlyOnceWith(PARENT) + expect(failed.refreshProjection).not.toHaveBeenCalled() }) it.each(['absent', 'idle', 'loading', 'ready'] as const)('does not expose header-only descendants when the projection read is %s', (state) => { From ef34a844de6dd855aacb49c1fdd215273cd0b114 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 12:56:23 +0800 Subject: [PATCH 084/103] fix(forge-panel): refuse commit runs off the first-parent line and harden review state - Shift-chosen commits must follow each other as first parents; the picker says why it keeps a run that leaves the line, and the Host refuses one with forgePanel/commits-not-linear for the Branch scope and change requests. - The Branch scope lists its newest maxCommits commits with --no-show-signature, so log.showSignature cannot corrupt the listing. - Viewed marks merge with the stored entry on each write and follow the storage event, so tabs of one Session keep each other's marks. - .gitattributes patterns follow Git's wildmatch rules, checked against git check-attr; change digests include file mode lines. - GitHub commit pagination refuses a repeated cursor or a changed count; commits validates the repository before its host like the other reads. - The commit list is read once per head, base, or refresh; the lens menu hides the count of the disabled Tests lens. --- docs/config-catalog.md | 4 +- docs/config-catalog.zh.md | 4 +- docs/subsystems/forge.md | 15 ++- docs/subsystems/forge.zh.md | 15 ++- .../client-ui-forge/README.i18n.yaml | 12 +- .../experimental/client-ui-forge/README.md | 6 +- .../experimental/client-ui-forge/README.zh.md | 6 +- .../client-ui-forge/src/client/ChangesTab.tsx | 12 +- .../src/client/CommitMenu.module.css | 9 ++ .../client-ui-forge/src/client/CommitMenu.tsx | 58 ++++++--- .../src/client/ReviewControls.tsx | 14 +- .../client-ui-forge/src/client/locales.ts | 32 +++-- .../src/client/viewed-files.ts | 71 +++++++--- .../client-ui-forge/src/commit-range.ts | 27 ++++ .../experimental/client-ui-forge/src/diff.ts | 12 +- .../experimental/client-ui-forge/src/index.ts | 20 +-- .../client-ui-forge/src/layers.ts | 17 ++- .../client-ui-forge/src/local-diff.ts | 32 +++-- .../experimental/client-ui-forge/src/types.ts | 17 ++- .../client-ui-forge/src/wildmatch.ts | 121 ++++++++++++++++++ .../tests/changes-tab.client.spec.tsx | 29 ++++- .../tests/controller.host.spec.ts | 28 +++- .../client-ui-forge/tests/diff.host.spec.ts | 12 ++ .../tests/local-diff.host.spec.ts | 59 ++++++++- .../tests/review-controls.client.spec.tsx | 40 +++++- .../tests/viewed-files.client.spec.ts | 42 ++++++ .../tests/wildmatch.host.spec.ts | 59 +++++++++ .../client-ui-forge/tsconfig.client.json | 1 + .../client-ui-forge/tsconfig.host.json | 2 + .../forge-github/README.i18n.yaml | 4 +- packages/experimental/forge-github/README.md | 2 +- .../experimental/forge-github/README.zh.md | 2 +- .../experimental/forge-github/src/commits.ts | 18 +-- .../experimental/forge-github/src/provider.ts | 3 +- .../forge-github/tests/provider.spec.ts | 25 +++- .../extensions/tool-cordis/src/api-catalog.ts | 8 +- 36 files changed, 690 insertions(+), 148 deletions(-) create mode 100644 packages/experimental/client-ui-forge/src/commit-range.ts create mode 100644 packages/experimental/client-ui-forge/src/wildmatch.ts create mode 100644 packages/experimental/client-ui-forge/tests/wildmatch.host.spec.ts diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 435668a4da..d85683e33e 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1081,7 +1081,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:374`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1109,7 +1109,7 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number - /** Most commits of the `branch` scope listed, oldest first. */ + /** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */ maxCommits?: number /** * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index c5713d0173..ceab76dfec 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1083,7 +1083,7 @@ export interface CotTranslationPreferences { ## `@deepseek-ai/dsh-experimental-client-ui-forge` - `inject`: `forge` · `forgeSession` · `sessionProjections` · `workingDirectory` · `fs` · `subprocess` · `sandbox` · `sandboxPolicy` · `agents` -- `source`: [`packages/experimental/client-ui-forge/src/types.ts:374`](../packages/experimental/client-ui-forge/src/types.ts) +- `source`: [`packages/experimental/client-ui-forge/src/types.ts:381`](../packages/experimental/client-ui-forge/src/types.ts) ```ts config-catalog /** Host settings of the forge panel Remote. */ @@ -1111,7 +1111,7 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number - /** Most commits of the `branch` scope listed, oldest first. */ + /** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */ maxCommits?: number /** * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 12407f64f4..b5156c101f 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -771,8 +771,15 @@ interface ForgeChangeRequestDiff { ``` ```ts type-equiv -/** Commits of the `branch` scope, which the changes view can show one or several of. */ -type ForgeLocalCommits = ForgeCommitList +/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */ +interface ForgeLocalCommits { + /** HEAD commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with HEAD's commit. */ + readonly commits: readonly ForgeCommit[] + /** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */ + readonly truncated: boolean +} ``` ```ts type-equiv @@ -1084,6 +1091,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @@ -1095,7 +1103,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param session - Session whose checkout is read. * @param base - the base ref of the `branch` scope, or null for its automatic fork point. * @param signal - request cancellation. - * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. */ @@ -1155,6 +1163,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index e8c5566df0..2ca42cde71 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -771,8 +771,15 @@ interface ForgeChangeRequestDiff { ``` ```ts type-equiv -/** Commits of the `branch` scope, which the changes view can show one or several of. */ -type ForgeLocalCommits = ForgeCommitList +/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */ +interface ForgeLocalCommits { + /** HEAD commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with HEAD's commit. */ + readonly commits: readonly ForgeCommit[] + /** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */ + readonly truncated: boolean +} ``` ```ts type-equiv @@ -1084,6 +1091,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @@ -1095,7 +1103,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @param session - Session whose checkout is read. * @param base - the base ref of the `branch` scope, or null for its automatic fork point. * @param signal - request cancellation. - * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. */ @@ -1155,6 +1163,7 @@ Serves the forge panel. Following a Session inspects the checkout of its current * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 0ced27cb60..5b25741184 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,11 +15,11 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: bc552fc8409a6101 - zh: 7462332ce44e56e0 + en: 05ee6d9ba0b8d2c7 + zh: 98c988e8f957511f /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 37dc1481037fac8a - zh: 910bd56856fe2896 + en: 7495fe1e0d0ee643 + zh: f820a5790ae6e2a7 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b @@ -30,8 +30,8 @@ en: 2bc25a99e17789c4 zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: - en: 2f96a33996a89344 - zh: a3ed868a4c2747c9 + en: 5e29ac36aad15d02 + zh: e46339bb637a69ef /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 36832b09d6..27ff8a01c3 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -40,7 +40,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. - **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. -- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first; a click shows one commit and a Shift click the commits from the last one clicked; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and a chosen commit that is gone offers Show all commits. +- **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. The checks row initially shows the polling preview. While it is incomplete, the card uses the host’s aggregate outcome without a failure count and labels the loaded check count as partial. Opening the list loads the remaining pages for that PR through `changeRequestChecks`; its deadline is independent of polling. A failed read keeps the preview and offers Retry. Closing the list, changing the head, or unmounting cancels the read; late results are ignored. Reopening reads current details. The Remote requires a visible Session binding and rejects a response for a different head commit. @@ -69,7 +69,7 @@ Restoration records `restoring` before mutation and `restored` only after succes Each inspection also decides whether the worktree is missing: the Session's directory lies inside the created worktree, `ctx.fs.lstat` finds no directory there, and `show-ref` in the source repository tells whether the branch still exists. -`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, and hunks, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point with `log --topo-order --reverse`, at most `maxCommits`. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. +`localDiff` takes the fork point from the created worktree's `baseCommit` when the Session works in it, else, for each remote in the code host order, from `symbolic-ref --quiet --short refs/remotes//HEAD` and `merge-base HEAD`; without one the `branch` scope refuses with `forgePanel/no-fork-point`. A `branch` scope that names a base ref under `refs/heads/` or `refs/remotes/` instead takes `merge-base HEAD` with it once `show-ref --verify` finds the ref, refusing with `forgePanel/base-missing` when the ref does not exist and with `forgePanel/no-fork-point` when HEAD shares no history with it; another ref name is refused before Git runs. It runs `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M` with fixed `a/` and `b/` prefixes and `core.quotePath=false` against the fork point, against HEAD (the empty tree before the first commit), against the index, or with `--cached` against HEAD. Before patches and statistics, Git configuration is read to apply command-local clean/process filter overrides. A failed or truncated configuration read stops the comparison: `localDiff` reports `forgePanel/filter-config-failed`, with a retry after correcting Git configuration or the output limit; failed statistics leave the local changes card hidden. Filter enumeration uses `maxDiffBytes` for patches and `maxOutputBytes` for statistics. Untracked files, at most `maxUntrackedFiles` with the rest counted as omitted, come from `ls-files --others --exclude-standard -z` and are read through `ctx.fs` as new files, binary when their first 8,000 bytes hold a NUL byte or they are not UTF-8. A patch, file list, or file over `maxDiffBytes` refuses with `forgePanel/diff-too-large`, and a directory outside a checkout with `forgePanel/not-a-checkout`. The Host parses patches with jsdiff into files and hunks, so the browser receives no raw patch. It gives each file a digest of its paths, status, hunks, and `old mode` and `new mode` lines, plus the blob names of a binary change or the content of an untracked binary file, and a layer from the `dsh-review-layer` and `linguist-generated` lines of the root `.gitattributes`, later lines overriding earlier ones and a value other than a layer name leaving the layer unspecified, with patterns matched by Git's wildmatch rules in [`src/wildmatch.ts`](src/wildmatch.ts) and negated patterns skipped as Git skips them, then from picomatch matches, with dot files included, of `testPaths`, `interfacePaths`, and the built-in rules in [`src/layers.ts`](src/layers.ts), with `.gitattributes` read from the index for Staged, the working tree for the other local scopes, the last chosen commit for chosen commits, and the head or last chosen commit through `fileText` for a change request, where a missing file reads as none. `localCommits` lists the commits between the fork point and HEAD with `log --no-show-signature --topo-order --reverse`, the newest `maxCommits` of them, so the list ends with HEAD's commit. A Branch scope with chosen commits compares the first one's first parent, or the empty tree for a root commit, with the last, refusing commits that are not full object names, not listed, or out of order with `forgePanel/commits-missing`, and a chosen commit whose first parent is not the commit listed before it with `forgePanel/commits-not-linear`; `localText` reads that last commit through `show`. `localText` reads the new side of one file, from the index through `show :` for Staged and through `ctx.fs` otherwise, and refuses a path that leaves the checkout. `changeRequestDiff` and `changeRequestText` act only on a visible binding a provider serves, else they refuse with `forgePanel/not-bound`; they read the head commit of the binding's latest status through the provider's `diff` and `fileText`, refuse a `too-large` failure with `forgePanel/diff-too-large`, a `stale` failure, meaning the head moved past that status, with `forgePanel/stale-head`, and refuse with `forgePanel/diff-failed` before a status was read or when the host refuses otherwise. A `stale` diff polls the change request at once, once per head commit, and is not cached, so no patch is ever kept under a head it does not describe. The Host keeps the patches `changeRequestDiff` read with their attributes, one per change request at its head commit and base branch, and drops the least recently read once they exceed `maxCachedDiffBytes`; a later read at the same head and base answers from memory for any Session, and a failed read is not kept. `changeRequestCommits` returns the provider's `commits` list, or null when the provider does not read commits; `changeRequestDiff` with chosen commits finds them in that list, refuses them as the Branch scope does, and reads `compare` from the first one's parent to the last, uncached. The commits the checkout has beyond the head come from `symbolic-ref`, `cat-file -e`, and `rev-list --count`, and are null when the checked-out branch is not the head branch, the head commit is absent, or Git fails. `changeRequestStates` streams, for the Session list, the last known number, title, state, draft flag, checks rollup, review decision, and mergeability of every change request that a listed Session the caller may read binds: a `baseline` frame, then `changed` frames. One run serves every stream. Cancellation is observed before initialization and between frames; the last stream and plugin disposal await initialization and accepted writes, then close the run’s storage domain. A later run waits for that closure before reopening the domain and reading its stored states. Binding updates received during listing override its initial snapshot. It lists Sessions through `sessionQuery` without loading them, takes the visible bindings of a loaded Session from `ctx.forgeSession` and of another from its cached `forgeChangeRequests` summary, follows binding changes of loaded Sessions, and subscribes to each bound change request through `ctx.forge.watch`; closed requests use the idle polling cadence, and merged requests remain subscribed for explicit refresh. It stores every changed state in the `forge_panel_change_requests` storage domain under the SHA-256 digest of its URL and drops unbound stored states only when every listed Session has known bindings; a failed write is logged and the state stays in memory. The stream fails when the Host lacks the Session query, projection cache, storage, or Session store service. @@ -141,7 +141,7 @@ None for a new worktree, as its notice belongs to the first request of the Sessi - **Large changes** — a local patch over `maxDiffBytes` shows no files, and a change request diff over the size limit of the host or its provider shows no files and offers only View in browser. Without wrapping, the side-by-side view cuts long lines at the column edge. - **Viewed files on the code host** — viewed marks of a change request stay in this browser and are not read from or written to GitHub's viewed state (`markFileAsViewed`) until the provider's review operations exist; another browser or device starts without them. - **Review layers** — the built-in rules cover common conventions only, so a repository records others in `.gitattributes`; a path cannot show Rust's inline `#[cfg(test)]` modules or which declarations a language exports, and the Interface layer keeps whole files, so finding changed exports needs a language analyzer that a later lens extension point can supply. `linguist-generated` is read only from the root `.gitattributes`, without nested `.gitattributes` files or attribute macros. -- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, 250 for GitHub, and a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. +- **Chosen commits** — a change request lists at most `maxCommits` commits of the provider, the oldest 250 for GitHub, while the Branch scope lists its newest `maxCommits`; a run must follow first parents, so commits of a merged branch can be shown one at a time but not together with the branch's own; a commit range is read from the host on every view; comments on chosen commits can only be added to the input, as a GitHub review addresses the head. - **Review page** — deferred: a left-navigation page that lists the user's change requests from the selected provider; the [decision note](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.md) records where it attaches. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 6dc7618038..4aca1d2c38 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -40,7 +40,7 @@ kind: "package-reference" - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 - **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 -- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在时提供“查看全部提交”。 +- **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 检查行先显示轮询预览。不完整时,卡片使用托管平台的总体状态而不显示失败总数,并注明已加载的检查数量尚不完整。打开列表后,经 `changeRequestChecks` 单独读取该 PR 的后续页,时限独立于轮询。读取失败时保留预览并提供重试。关闭列表、head 变化或组件卸载会取消读取,忽略迟到结果;重新打开会读取当前详情。Remote 要求 URL 是该 Session 可见的绑定,并拒绝 head 提交不一致的响应。 @@ -69,7 +69,7 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo 每次检查还会判断 worktree 是否缺失:Session 的目录位于所创建的 worktree 内,`ctx.fs.lstat` 在那里找不到目录,再由源仓库中的 `show-ref` 判断分支是否还在。 -Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态与 hunk 组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --topo-order --reverse` 列出分叉点之后的提交,最多 `maxCommits` 个。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 +Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。`branch` 范围指定了 `refs/heads/` 或 `refs/remotes/` 下的基准引用时,`show-ref --verify` 找到该引用后改用 `merge-base HEAD` 与它的结果;引用不存在时以 `forgePanel/base-missing` 拒绝,HEAD 与它没有共同历史时以 `forgePanel/no-fork-point` 拒绝;其他引用名在运行 Git 之前即被拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --submodule=short --ignore-submodules=dirty --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。读取补丁与统计前会查询 Git 配置,应用命令级 clean/process filter 覆盖。配置读取失败或被截断时停止比较:`localDiff` 报告 `forgePanel/filter-config-failed`,修正 Git 配置或读取上限后可重试;统计失败时本地变更卡片保持隐藏。过滤器枚举在读取补丁时使用 `maxDiffBytes` 上限,统计时使用 `maxOutputBytes` 上限。未跟踪文件由 `ls-files --others --exclude-standard -z` 列出,最多 `maxUntrackedFiles` 个,其余计为未列出;它们经 `ctx.fs` 读取并作为新文件加入,前 8,000 字节含 NUL 字节或不是 UTF-8 时视为二进制。补丁、文件列表或文件超过 `maxDiffBytes` 时以 `forgePanel/diff-too-large` 拒绝,目录不在检出中时以 `forgePanel/not-a-checkout` 拒绝。宿主用 jsdiff 把补丁解析为文件与 hunk,浏览器不会收到原始补丁。Host 为每个文件计算由路径、状态、hunk 以及 `old mode` 与 `new mode` 行组成的摘要(二进制改动加上 blob 名,未跟踪的二进制文件加上内容),并先按根目录 `.gitattributes` 中的 `dsh-review-layer` 与 `linguist-generated` 行确定分层(后面的行覆盖前面的行,不是层名的值视为未指定;模式按 [`src/wildmatch.ts`](src/wildmatch.ts) 中 Git 的 wildmatch 规则匹配,取反模式与 Git 一样跳过),再用 picomatch(包含点文件)依次匹配 `testPaths`、`interfacePaths` 与 [`src/layers.ts`](src/layers.ts) 中的内置规则。`.gitattributes` 的读取来源:“已暂存”读暂存区,其他本地范围读工作树,所选提交读最后一个提交,变更请求经 `fileText` 读 head 或最后一个所选提交,文件不存在时按没有处理。`localCommits` 用 `log --no-show-signature --topo-order --reverse` 列出分叉点到 HEAD 之间最新的 `maxCommits` 个提交,因此列表以 HEAD 的提交结尾。带所选提交的“分支”范围比较第一个提交的第一个父提交(根提交用空树)与最后一个提交;不是完整对象名、不在列表中或顺序颠倒的提交以 `forgePanel/commits-missing` 拒绝,第一父提交不是列表中前一个提交的所选提交以 `forgePanel/commits-not-linear` 拒绝;`localText` 经 `show` 读取那个最后的提交。`localText` 读取一个文件的新版本:“已暂存”经 `show :` 从暂存区读取,其余经 `ctx.fs` 读取;离开检出的路径会被拒绝。`changeRequestDiff` 与 `changeRequestText` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;它们经提供方的 `diff` 与 `fileText` 读取绑定最新状态中的 head 提交,`too-large` 失败以 `forgePanel/diff-too-large` 拒绝,`stale` 失败(head 已越过该状态)以 `forgePanel/stale-head` 拒绝,尚未读到状态或托管平台以其他原因拒绝时以 `forgePanel/diff-failed` 拒绝。`stale` 的 diff 会立即重新轮询该变更请求(每个 head 提交一次)且不缓存,因此不会有补丁被存放在它不描述的 head 下。Host 保留 `changeRequestDiff` 读到的补丁及其属性,每个变更请求一份,按 head 提交与目标分支区分,总量超过 `maxCachedDiffBytes` 时丢弃最久未读的;之后在同一 head 与目标分支下的读取不论来自哪个 Session 都从内存返回,读取失败的结果不保留。`changeRequestCommits` 返回提供方 `commits` 的列表,提供方不读取提交时返回 null;带所选提交的 `changeRequestDiff` 在该列表中找到它们,按与“分支”范围相同的规则拒绝,并从第一个提交的父提交到最后一个提交读取 `compare`,不缓存。本地分支比 head 多出的提交数由 `symbolic-ref`、`cat-file -e` 与 `rev-list --count` 得出;当前检出分支不是源分支、本地没有 head 提交或 Git 失败时为 null。 `changeRequestStates` 为会话列表推送调用方可读的、已列出的 Session 所绑定的每个变更请求的最近编号、标题、状态、草稿标记、检查汇总、评审结论与可合并性:先是一个 `baseline` 帧,之后是 `changed` 帧。所有流共用一次运行。初始化之前和帧之间均响应取消;最后一条流结束及插件卸载会等待初始化与已接受的写入完成,再关闭本次运行的存储域。后续运行会等待该域关闭后重新打开,并读取已存状态。列举期间收到的绑定更新优先于初始快照。它经 `sessionQuery` 列出 Session 而不加载它们,已加载 Session 的可见绑定取自 `ctx.forgeSession`,其他 Session 的取自缓存的 `forgeChangeRequests` 摘要;它跟随已加载 Session 的绑定变化,并经 `ctx.forge.watch` 订阅每个已绑定的变更请求;已关闭的按空闲间隔轮询,已合并的保留订阅以接收显式刷新结果。每个变化了的状态以其 URL 的 SHA-256 摘要为键存入 `forge_panel_change_requests` 存储域,仅在所有已列出 Session 的绑定均已知时删除无人绑定的已存状态;写入失败时记录日志,状态仍保留在内存中。宿主缺少 Session 查询、投影缓存、存储或 Session 存储服务时,流以失败结束。 @@ -141,7 +141,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi - **大型变更**——本地补丁超过 `maxDiffBytes` 时不显示任何文件;超过托管平台或其提供方大小上限的变更请求 diff 不显示任何文件,只提供“在浏览器中查看”。不自动换行时,左右对比会在栏边截断长行。 - **代码托管平台上的已审阅状态**——变更请求的已审阅标记只保存在本浏览器中,在提供方评审接口完成之前,不读取也不写入 GitHub 的已审阅状态(`markFileAsViewed`);换浏览器或设备后没有这些标记。 - **分层**——内置规则只覆盖常见约定,其他约定由仓库写在 `.gitattributes` 中;按路径无法识别 Rust 的内联 `#[cfg(test)]` 模块,也无法判断一种语言导出了哪些声明,“接口”层保留整个文件,找出变更的导出需要语言分析器,可由之后的透镜扩展点提供。`linguist-generated` 只读取根目录的 `.gitattributes`,不读子目录中的 `.gitattributes`,也不展开属性宏。 -- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为 250 个),每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 +- **所选提交**——变更请求最多列出提供方的 `maxCommits` 个提交(GitHub 为最早的 250 个),“分支”范围则列出最新的 `maxCommits` 个;范围必须沿第一父提交相连,因此已合并分支的提交只能逐个查看,不能与本分支的提交一起查看;每次查看提交范围都从托管平台读取;所选提交上的评论只能添加到输入框,因为 GitHub 评审针对 head。 - **代码审查页**——待办:在左侧导航中新增一个页面,列出用户在所选提供方上的变更请求;[决策笔记](../../../.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md)记录了它的接入位置。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 5c46b6f850..f57bb937bb 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -165,6 +165,7 @@ const FAILURE: Partial> = { 'forgePanel/diff-too-large': 'diff.tooLarge', 'forgePanel/filter-config-failed': 'diff.filterConfigFailed', 'forgePanel/commits-missing': 'commits.missing', + 'forgePanel/commits-not-linear': 'commits.notLinear', } /** Failures of a chosen base branch, which offer the automatic fork point instead of a retry. */ @@ -520,8 +521,10 @@ export function ChangesTab({ const pending = entry !== undefined && entry.ref !== null && entry.update === null const head = entry?.snapshot?.headSha ?? (pending ? null : '') const version = state === null ? null : source.kind === 'local' ? `${scope}\n${JSON.stringify(state.local)}` : head - // The commits change with the head of a change request, and with the local branch or its base. - const commitsVersion = source.kind === 'local' ? `${baseRef ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? '' + const headCommit = state !== null && state.checkout.state === 'ready' ? state.checkout.checkout.commit : null + // The commits change with the head of a change request, with the local HEAD, branch, or base, and on a refresh. + const commitsVersion = `${attempt}\n${source.kind === 'local' + ? `${baseRef ?? ''}\n${headCommit ?? ''}\n${JSON.stringify(state?.local ?? null)}` : head ?? ''}` const dataKey = source.kind === 'local' ? JSON.stringify(localScope) : `change\n${JSON.stringify(changeCommits)}` const [loaded, setLoaded] = useState<{ readonly key: string; readonly data: ChangesData } | null>(null) const [failure, setFailure] = useState<{ readonly key: string; readonly code: string } | null>(null) @@ -606,7 +609,7 @@ export function ChangesTab({ const retry = baseFailure === undefined && (message === undefined || failed === 'forgePanel/filter-config-failed') const automaticBase = baseFailure !== undefined ? ( - ) : failed === 'forgePanel/commits-missing' && ( + ) : (failed === 'forgePanel/commits-missing' || failed === 'forgePanel/commits-not-linear') && ( ) @@ -851,7 +854,8 @@ export function ChangesTab({ const treeShown = allFiles.length > 0 && treePosition !== 'hidden' const lensProps = { lens, counts: lensCounts, hideTests, choose: (next: ChangesLens) => { actions.lensed(tab.id, next) }, t } const commitMenu = source.kind === 'local' && scope !== 'branch' ? null : { actions.committed(tab.id, next) }} t={t} /> const toolbarStyle: CSSProperties & { '--forge-tree-width': string } = { '--forge-tree-width': `${treeWidth}px` } return ( diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css index 34159de448..5cf60040eb 100644 --- a/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.module.css @@ -128,3 +128,12 @@ font-size: 11px; line-height: 16px; } + +/* Why a Shift click left the shown commits unchanged; outside the scrolled rows so it stays in view. */ +.rejected { + padding: 8px 12px; + border-top: 0.5px solid var(--dsw-alias-border-l3); + color: var(--dsw-alias-label-secondary); + font-size: 11px; + line-height: 16px; +} diff --git a/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx index 58e7702b75..17ba7fbd89 100644 --- a/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx +++ b/packages/experimental/client-ui-forge/src/client/CommitMenu.tsx @@ -1,6 +1,7 @@ /** * Commit picker of the changes header: every commit, or one commit, or with Shift a run of consecutive commits of a - * change request or of the local `branch` scope, listed oldest first like the code host's commit list. + * change request or of the local `branch` scope, listed oldest first like the code host's commit list. A run is + * accepted only when each of its commits has the one listed before it as its first parent. */ import { useEffect, useRef, useState, type ReactNode } from 'react' @@ -11,7 +12,8 @@ import { import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' import type { ForgeCommitList } from '@deepseek-ai/dsh-experimental-forge/types' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' -import type { ForgeCommitRange } from '../types.ts' +import { rangeStart } from '../commit-range.ts' +import type { ForgeCommitRange, ForgeLocalCommits } from '../types.ts' import { formatAgo } from './format.ts' import type { NS } from './locales.ts' import css from './CommitMenu.module.css' @@ -26,8 +28,10 @@ export interface CommitMenuProps extends PropsLocale { /** Whether the owning tab is visible; a hidden tab keeps the menu closed. */ readonly visible: boolean /** Read the commits; null means the source cannot show single commits. `signal` aborts the read. */ - readonly list: (signal: AbortSignal) => Promise> - /** Changes when the commits may have changed, such as a new head commit; the next opening reads them again. */ + readonly list: (signal: AbortSignal) => Promise> + /** Which commits a truncated list keeps: a change request lists its oldest ones, the local branch its newest ones. */ + readonly kept: 'oldest' | 'newest' + /** Changes when the commits may have changed, such as a new head commit or a refresh; the commits are read once per value. */ readonly version: string /** Show consecutive commits, or every commit for null. */ readonly choose: (commits: ForgeCommitRange | null) => void @@ -51,39 +55,54 @@ export function commitsLabel(chosen: ForgeCommitRange | null, t: PropsLocale } | null>(null) + const [rejected, setRejected] = useState(false) + const [listing, setListing] = useState<{ + readonly key: string + readonly result: RemoteResult + } | null>(null) const shift = useRef(false) const anchor = useRef(chosen?.from ?? null) const loaded = useRef(null) const shown = visible && open - const current = listing?.version === version ? listing.result : null - // The list is read once per version, which tells whether the source has commits to pick, and again on each opening. + const key = `${version}\n${String(attempt)}` + const current = listing?.key === key ? listing.result : null + // The list is read once per version, which also tells whether the source has commits to pick, and again on a retry. useEffect(() => { - if (!visible || (!shown && loaded.current === version)) return + if (!visible || loaded.current === key) return const controller = new AbortController() void list(controller.signal).then((result) => { if (controller.signal.aborted) return - loaded.current = version - setListing({ version, result }) + loaded.current = key + setListing({ key, result }) }) return () => { controller.abort() } - }, [visible, shown, version, attempt, list]) + }, [visible, key, list]) if (current?.ok === true && current.value === null) return null const commits = current?.ok === true && current.value !== null ? current.value : null - const pick = (sha: string | null): void => { + const close = (): void => { setOpen(false) + setRejected(false) + } + const pick = (sha: string | null): void => { if (sha === null || commits === null) { + close() anchor.current = null if (chosen !== null) choose(null) return } const order = commits.commits.map(commit => commit.sha) const start = shift.current && anchor.current !== null && order.includes(anchor.current) ? anchor.current : sha - if (!shift.current || start === sha) anchor.current = sha const [from, to] = order.indexOf(start) <= order.indexOf(sha) ? [start, sha] : [sha, start] + // Two ends cannot name a run that leaves the first-parent line, so the menu stays open and says why. + if (rangeStart(commits.commits, { from, to }) === 'not-linear') { + setRejected(true) + return + } + close() + if (!shift.current || start === sha) anchor.current = sha if (from !== chosen?.from || to !== chosen.to) choose({ from, to }) } const inChosen = (index: number): boolean => { @@ -126,7 +145,11 @@ export function CommitMenu({ chosen, visible, list, version, choose, t }: Commit ) })} - {commits.truncated &&
    {t('commits.truncated', { count: commits.commits.length })}
    } + {commits.truncated && ( +
    + {t(kept === 'oldest' ? 'commits.truncatedOldest' : 'commits.truncatedNewest', { count: commits.commits.length })} +
    + )} } @@ -139,12 +162,12 @@ export function CommitMenu({ chosen, visible, list, version, choose, t }: Commit align="end" className={css.anchor} listClassName={css.menu} - onClose={() => { setOpen(false) }} + onClose={close} anchor={( @@ -157,6 +180,7 @@ export function CommitMenu({ chosen, visible, list, version, choose, t }: Commit onKeyDownCapture={(event) => { shift.current = event.shiftKey }}> {body}
    + {rejected &&
    {t('commits.notLinear')}
    } ) } diff --git a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx index ba68601ede..735c0148c4 100644 --- a/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx +++ b/packages/experimental/client-ui-forge/src/client/ReviewControls.tsx @@ -82,11 +82,15 @@ export function LensControl({ lens, counts, hideTests, choose, t }: LensProps): */ export function LensMenu({ lens, counts, hideTests, choose, visible, t }: LensProps & { readonly visible: boolean }): ReactNode { const [open, setOpen] = useState(false) - const items: MenuEntry[] = LENSES.map(item => ({ - id: item, - disabled: item === 'test' && hideTests, - label: {t(LENS_LABEL[item])}{counts[item]}, - })) + const items: MenuEntry[] = LENSES.map((item) => { + // Like the segment, a disabled lens shows no count, since hidden test files are not counted. + const disabled = item === 'test' && hideTests + return { + id: item, + disabled, + label: {t(LENS_LABEL[item])}{disabled ? '' : counts[item]}, + } + }) return ( { setOpen(false) }} diff --git a/packages/experimental/client-ui-forge/src/client/locales.ts b/packages/experimental/client-ui-forge/src/client/locales.ts index 9804e0d655..81cb739802 100644 --- a/packages/experimental/client-ui-forge/src/client/locales.ts +++ b/packages/experimental/client-ui-forge/src/client/locales.ts @@ -199,9 +199,11 @@ export const zh = { 'commits.shiftHint': '按住 Shift 选择连续多个提交', 'commits.loading': '正在读取提交…', 'commits.failed': '无法读取提交', - 'commits.truncated': '只列出了最早的 {count} 个提交', + 'commits.truncatedOldest': '只列出了最早的 {count} 个提交', + 'commits.truncatedNewest': '只列出了最新的 {count} 个提交', 'commits.aria': '查看的提交:{commits}', 'commits.missing': '所选的提交已不在其中', + 'commits.notLinear': '这些提交不在同一条提交链上', 'commits.showAll': '查看全部提交', 'diff.noMatchingFiles': '没有匹配的文件', 'diff.refresh': '刷新变更', @@ -507,9 +509,11 @@ export const en: Record = { 'commits.shiftHint': 'Hold Shift to select consecutive commits', 'commits.loading': 'Loading commits…', 'commits.failed': 'Could not load commits', - 'commits.truncated': 'Only the earliest {count} commits are listed', + 'commits.truncatedOldest': 'Only the earliest {count} commits are listed', + 'commits.truncatedNewest': 'Only the latest {count} commits are listed', 'commits.aria': 'Commits shown: {commits}', 'commits.missing': 'The selected commits are no longer included', + 'commits.notLinear': 'These commits are not on one line of history', 'commits.showAll': 'Show all commits', 'diff.noMatchingFiles': 'No matching files', 'diff.refresh': 'Refresh changes', @@ -819,9 +823,11 @@ export const ja: Record = { 'commits.shiftHint': 'Shift を押しながら連続するコミットを選択', 'commits.loading': 'コミットを読み込み中…', 'commits.failed': 'コミットを読み込めませんでした', - 'commits.truncated': '最初の {count} 件のコミットのみ表示しています', + 'commits.truncatedOldest': '最初の {count} 件のコミットのみ表示しています', + 'commits.truncatedNewest': '最新の {count} 件のコミットのみ表示しています', 'commits.aria': '表示中のコミット:{commits}', 'commits.missing': '選択したコミットは含まれなくなりました', + 'commits.notLinear': 'これらのコミットは 1 本の履歴上にありません', 'commits.showAll': 'すべてのコミットを表示', 'diff.noMatchingFiles': '一致するファイルがありません', 'diff.refresh': '変更を更新', @@ -1124,9 +1130,11 @@ export const es: Record = { 'commits.shiftHint': 'Mantén Mayús para seleccionar commits consecutivos', 'commits.loading': 'Cargando commits…', 'commits.failed': 'No se pudieron cargar los commits', - 'commits.truncated': 'Solo se muestran los {count} commits más antiguos', + 'commits.truncatedOldest': 'Solo se muestran los {count} commits más antiguos', + 'commits.truncatedNewest': 'Solo se muestran los {count} commits más recientes', 'commits.aria': 'Commits mostrados: {commits}', 'commits.missing': 'Los commits seleccionados ya no están incluidos', + 'commits.notLinear': 'Estos commits no están en una misma línea del historial', 'commits.showAll': 'Ver todos los commits', 'diff.noMatchingFiles': 'No hay archivos coincidentes', 'diff.refresh': 'Actualizar cambios', @@ -1429,9 +1437,11 @@ export const fr: Record = { 'commits.shiftHint': 'Maintenez Maj pour sélectionner des commits consécutifs', 'commits.loading': 'Chargement des commits…', 'commits.failed': 'Impossible de charger les commits', - 'commits.truncated': 'Seuls les {count} commits les plus anciens sont listés', + 'commits.truncatedOldest': 'Seuls les {count} commits les plus anciens sont listés', + 'commits.truncatedNewest': 'Seuls les {count} commits les plus récents sont listés', 'commits.aria': 'Commits affichés : {commits}', 'commits.missing': 'Les commits sélectionnés ne sont plus inclus', + 'commits.notLinear': 'Ces commits ne sont pas sur une même ligne d’historique', 'commits.showAll': 'Afficher tous les commits', 'diff.noMatchingFiles': 'Aucun fichier correspondant', 'diff.refresh': 'Actualiser les modifications', @@ -1734,9 +1744,11 @@ export const de: Record = { 'commits.shiftHint': 'Mit gedrückter Umschalttaste aufeinanderfolgende Commits wählen', 'commits.loading': 'Commits werden geladen…', 'commits.failed': 'Commits konnten nicht geladen werden', - 'commits.truncated': 'Nur die ältesten {count} Commits werden aufgeführt', + 'commits.truncatedOldest': 'Nur die ältesten {count} Commits werden aufgeführt', + 'commits.truncatedNewest': 'Nur die neuesten {count} Commits werden aufgeführt', 'commits.aria': 'Angezeigte Commits: {commits}', 'commits.missing': 'Die gewählten Commits sind nicht mehr enthalten', + 'commits.notLinear': 'Diese Commits liegen nicht auf einer Verlaufslinie', 'commits.showAll': 'Alle Commits anzeigen', 'diff.noMatchingFiles': 'Keine passenden Dateien', 'diff.refresh': 'Änderungen aktualisieren', @@ -2039,9 +2051,11 @@ export const ru: Record = { 'commits.shiftHint': 'Удерживайте Shift, чтобы выбрать несколько коммитов подряд', 'commits.loading': 'Загрузка коммитов…', 'commits.failed': 'Не удалось загрузить коммиты', - 'commits.truncated': 'Показаны только первые {count} коммитов', + 'commits.truncatedOldest': 'Показаны только первые {count} коммитов', + 'commits.truncatedNewest': 'Показаны только последние {count} коммитов', 'commits.aria': 'Показанные коммиты: {commits}', 'commits.missing': 'Выбранные коммиты больше не входят в список', + 'commits.notLinear': 'Эти коммиты не лежат на одной линии истории', 'commits.showAll': 'Показать все коммиты', 'diff.noMatchingFiles': 'Нет подходящих файлов', 'diff.refresh': 'Обновить изменения', @@ -2344,9 +2358,11 @@ export const pt: Record = { 'commits.shiftHint': 'Segure Shift para selecionar commits consecutivos', 'commits.loading': 'Carregando commits…', 'commits.failed': 'Não foi possível carregar os commits', - 'commits.truncated': 'Apenas os {count} commits mais antigos estão listados', + 'commits.truncatedOldest': 'Apenas os {count} commits mais antigos estão listados', + 'commits.truncatedNewest': 'Apenas os {count} commits mais recentes estão listados', 'commits.aria': 'Commits exibidos: {commits}', 'commits.missing': 'Os commits selecionados não estão mais incluídos', + 'commits.notLinear': 'Esses commits não estão em uma mesma linha do histórico', 'commits.showAll': 'Ver todos os commits', 'diff.noMatchingFiles': 'Nenhum arquivo correspondente', 'diff.refresh': 'Atualizar alterações', diff --git a/packages/experimental/client-ui-forge/src/client/viewed-files.ts b/packages/experimental/client-ui-forge/src/client/viewed-files.ts index a603a26a3e..cb07032b79 100644 --- a/packages/experimental/client-ui-forge/src/client/viewed-files.ts +++ b/packages/experimental/client-ui-forge/src/client/viewed-files.ts @@ -2,7 +2,8 @@ * Browser-persisted viewed marks of changed files. Each Session keeps one storage entry that maps a diff source, * such as a change request or a local scope with its base ref and chosen commits, to the digest of each file's * change when the reader marked it viewed. A mark whose digest differs from the file's current change reports the - * file as changed since it was viewed. + * file as changed since it was viewed. Several browser tabs of one Session share the entry: each mark rewrites the + * entry as storage holds it, and marks saved by another tab reach this one through the `storage` event. */ import { z } from 'zod' @@ -20,6 +21,8 @@ const source = z.object({ at: z.number(), files: z.record(z.string(), z.string() const saved = z.record(z.string(), source) const index = z.array(z.string()) +type Sources = Readonly>> + /** Viewed state of one file in the diff a reader sees. */ export type ViewedState = 'viewed' | 'changed' | 'unviewed' @@ -40,13 +43,15 @@ export function viewedStateOf(marks: ViewedMarks, path: string, digest: string): return marked === undefined ? 'unviewed' : marked === digest ? 'viewed' : 'changed' } -/** One Session's viewed marks; unreadable storage leaves the marks empty and refuses later writes. */ +/** + * One Session's viewed marks. Unreadable storage shows no marks and refuses writes while it stays unreadable. While + * anything subscribes, marks another tab saves replace the ones shown. + */ export class ViewedFiles { - private sources: Record> = {} + private sources: Sources private readonly listeners = new Set<() => void>() private readonly snapshots = new Map() private readonly key: string - private readonly readable: boolean /** * @param session - storage identity of the Session, such as its id. @@ -54,14 +59,7 @@ export class ViewedFiles { */ constructor(private readonly session: string, private readonly now: () => number = Date.now) { this.key = `${PREFIX}.${JSON.stringify(session)}` - let readable = true - try { - const raw = localStorage.getItem(this.key) - if (raw !== null) this.sources = saved.parse(JSON.parse(raw)) - } catch (_error) { - readable = false - } - this.readable = readable + this.sources = this.load() ?? {} } /** @@ -85,8 +83,16 @@ export class ViewedFiles { * @returns unsubscribe. */ readonly subscribe = (listener: () => void): (() => void) => { + // Storage events that arrived while nothing listened are lost, so the first subscriber reads storage again. + if (this.listeners.size === 0) { + window.addEventListener('storage', this.stored) + this.reload() + } this.listeners.add(listener) - return () => { this.listeners.delete(listener) } + return () => { + this.listeners.delete(listener) + if (this.listeners.size === 0) window.removeEventListener('storage', this.stored) + } } /** @@ -99,11 +105,13 @@ export class ViewedFiles { */ mark(key: string, files: readonly { readonly path: string; readonly digest: string }[], path: string, viewed: boolean): boolean { const file = files.find(item => item.path === path) - if (!this.readable || file === undefined) return false + // Another tab of the Session may have saved marks since this one last read them; the write keeps theirs. + const current = this.load() + if (current === undefined || file === undefined) return false const present = new Set(files.map(item => item.path)) - const kept = Object.entries(this.sources[key]?.files ?? {}).filter(([marked]) => marked !== path && present.has(marked)) + const kept = Object.entries(current[key]?.files ?? {}).filter(([marked]) => marked !== path && present.has(marked)) const sources = { - ...this.sources, + ...current, [key]: { at: this.now(), files: Object.fromEntries(viewed ? [...kept, [path, file.digest]] : kept) }, } const recent = Object.entries(sources).sort(([, left], [, right]) => right.at - left.at).slice(0, MAX_SOURCES) @@ -113,13 +121,38 @@ export class ViewedFiles { } catch (_error) { return false } - this.sources = next - this.snapshots.clear() + this.replace(next) this.remember() - for (const listener of this.listeners) listener() return true } + /** The saved marks of this Session, or undefined when storage cannot be read or holds an entry it cannot parse. */ + private load(): Sources | undefined { + try { + const raw = localStorage.getItem(this.key) + return raw === null ? {} : saved.parse(JSON.parse(raw)) + } catch (_error) { + return undefined + } + } + + /** Show the saved marks when they differ from the shown ones. */ + private reload(): void { + const sources = this.load() ?? {} + if (JSON.stringify(sources) !== JSON.stringify(this.sources)) this.replace(sources) + } + + private replace(sources: Sources): void { + this.sources = sources + this.snapshots.clear() + for (const listener of this.listeners) listener() + } + + /** Another document changed this Session's entry, or with a null key cleared the whole storage. */ + private readonly stored = (event: StorageEvent): void => { + if (event.key === this.key || event.key === null) this.reload() + } + /** Move this Session to the front of the index and drop the marks of Sessions beyond {@link MAX_SESSIONS}. */ private remember(): void { const key = `${PREFIX}.sessions` diff --git a/packages/experimental/client-ui-forge/src/commit-range.ts b/packages/experimental/client-ui-forge/src/commit-range.ts new file mode 100644 index 0000000000..b2624e1b11 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/commit-range.ts @@ -0,0 +1,27 @@ +/** + * Checks of a chosen run of commits against a commit list, shared by the Host, which reads the run's changes, and the + * commit picker, which refuses a run before asking for them. + */ + +import type { ForgeCommit } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ForgeCommitRange } from './types.ts' + +/** + * Find the first commit of a chosen run in a commit list. Two ends describe the run only when each commit after the + * first has the commit listed before it as its first parent, so the changes from the first commit's first parent to the + * last commit are exactly the run's changes. + * @param commits - listed commits, oldest first. + * @param range - the chosen run. + * @returns the first chosen commit; `missing` when an end is not listed or `to` is listed before `from`; `not-linear` + * when a commit of the run does not have the commit listed before it as its first parent. + */ +export function rangeStart(commits: readonly ForgeCommit[], range: ForgeCommitRange): ForgeCommit | 'missing' | 'not-linear' { + const first = commits.findIndex(commit => commit.sha === range.from) + const last = commits.findIndex(commit => commit.sha === range.to) + const start = commits[first] + if (start === undefined || last < first) return 'missing' + for (let index = first + 1; index <= last; index++) { + if (commits[index]?.parent !== commits[index - 1]?.sha) return 'not-linear' + } + return start +} diff --git a/packages/experimental/client-ui-forge/src/diff.ts b/packages/experimental/client-ui-forge/src/diff.ts index 4ec3d62b71..02c75bf06b 100644 --- a/packages/experimental/client-ui-forge/src/diff.ts +++ b/packages/experimental/client-ui-forge/src/diff.ts @@ -50,18 +50,20 @@ export function parseDiff(patch: string): ParsedDiffFile[] { // Each header matches its parsed section only when every section starts with a Git header. const header = binary && headers.length === parsed.length ? String(headers[index]) : '' const blobs = INDEX_LINE.exec(header)?.[1] ?? '' + // A mode change, such as `chmod +x`, shows only in the `old mode` and `new mode` header lines. + const modes = `${section.oldMode ?? ''}..${section.newMode ?? ''}` return [{ path, previousPath, status, binary, oversized: false, untracked: false, additions, deletions, hunks, - digest: changeDigest(path, previousPath, status, hunks, blobs), + digest: changeDigest(path, previousPath, status, hunks, blobs, modes), }] }) } -/** Digest of one change: its paths, status, hunks, and the identity of content that hunks do not show. */ +/** Digest of one change: its paths, status, hunks, file modes, and the identity of content that hunks do not show. */ function changeDigest( - path: string, previousPath: string | null, status: ForgeDiffStatus, hunks: readonly ForgeDiffHunk[], content: string, + path: string, previousPath: string | null, status: ForgeDiffStatus, hunks: readonly ForgeDiffHunk[], content: string, modes: string, ): string { - return createHash('sha256').update(JSON.stringify([path, previousPath, status, hunks, content])).digest('hex').slice(0, 32) + return createHash('sha256').update(JSON.stringify([path, previousPath, status, hunks, content, modes])).digest('hex').slice(0, 32) } /** @@ -103,7 +105,7 @@ function addedFile(path: string, hunks: readonly ForgeDiffHunk[], { binary, over }): ParsedDiffFile { return { path, previousPath: null, status: 'added', binary, oversized, untracked: true, - additions: hunks[0]?.newLines ?? 0, deletions: 0, hunks, digest: changeDigest(path, null, 'added', hunks, content), + additions: hunks[0]?.newLines ?? 0, deletions: 0, hunks, digest: changeDigest(path, null, 'added', hunks, content, ''), } } diff --git a/packages/experimental/client-ui-forge/src/index.ts b/packages/experimental/client-ui-forge/src/index.ts index 3dc9e37608..708eb757f4 100644 --- a/packages/experimental/client-ui-forge/src/index.ts +++ b/packages/experimental/client-ui-forge/src/index.ts @@ -23,9 +23,10 @@ import { gitIn, inspectCheckout, listBranches } from './git.ts' import type { Inspection } from './git.ts' import { parseDiff } from './diff.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, FilterConfigError, forkPoint, localCommits, localDiff, - localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, FilterConfigError, forkPoint, + localCommits, localDiff, localText, NoForkPoint, } from './local-diff.ts' +import { rangeStart } from './commit-range.ts' import { ATTRIBUTES_PATH, FileLayers } from './layers.ts' import { missingWorktree, SessionPanel } from './panel.ts' import { PatchCache } from './patch-cache.ts' @@ -286,6 +287,7 @@ export class ForgePanelController extends TypertRemoteService { * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch * chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without * a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before * any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails. */ @@ -307,7 +309,7 @@ export class ForgePanelController extends TypertRemoteService { * @param session - Session whose checkout is read. * @param base - the base ref of the `branch` scope, or null for its automatic fork point. * @param signal - request cancellation. - * @returns at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. + * @returns the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD's commit. * @throws `forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not * exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`. */ @@ -395,6 +397,7 @@ export class ForgePanelController extends TypertRemoteService { * @returns the files, the commit they end at, each file's web page, and the commits the checkout has beyond the head. * @throws `forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; * `forgePanel/commits-missing` when chosen commits are not among the change request's commits in order; + * `forgePanel/commits-not-linear` when a chosen commit's first parent is not the commit listed before it; * `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again; * `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; * `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host @@ -675,12 +678,10 @@ export class ForgePanelController extends TypertRemoteService { const list = await this.home.forge.commits(ref, signal) if (list === undefined) throw new RemoteError('forgePanel/diff-failed', 'The code host provider does not read commits', {}) if ('code' in list) throw readError(list) - const first = list.commits.findIndex(commit => commit.sha === commits.from) - const last = list.commits.findIndex(commit => commit.sha === commits.to) - if (first === -1 || last < first) { - throw new RemoteError('forgePanel/commits-missing', 'The chosen commits are no longer in the change request', {}) - } - const parent = list.commits[first]?.parent ?? null + const start = rangeStart(list.commits, commits) + if (start === 'missing') throw new RemoteError('forgePanel/commits-missing', 'The chosen commits are no longer in the change request', {}) + if (start === 'not-linear') throw new RemoteError('forgePanel/commits-not-linear', 'The chosen commits are not one run of first parents', {}) + const parent = start.parent if (parent === null) throw new RemoteError('forgePanel/diff-failed', 'The first chosen commit has no parent to compare with', {}) const patch = await this.home.forge.compare(ref, parent, commits.to, signal) if (typeof patch !== 'string') throw readError(patch) @@ -842,6 +843,7 @@ async function diffing(reading: Promise): Promise { if (error instanceof NoForkPoint) throw new RemoteError('forgePanel/no-fork-point', error.message, {}, { cause: error }) if (error instanceof BaseMissing) throw new RemoteError('forgePanel/base-missing', error.message, {}, { cause: error }) if (error instanceof CommitsMissing) throw new RemoteError('forgePanel/commits-missing', error.message, {}, { cause: error }) + if (error instanceof CommitsNotLinear) throw new RemoteError('forgePanel/commits-not-linear', error.message, {}, { cause: error }) throw error } } diff --git a/packages/experimental/client-ui-forge/src/layers.ts b/packages/experimental/client-ui-forge/src/layers.ts index c7ea40940e..8b6eb79a93 100644 --- a/packages/experimental/client-ui-forge/src/layers.ts +++ b/packages/experimental/client-ui-forge/src/layers.ts @@ -8,6 +8,7 @@ import picomatch from 'picomatch' import type { ParsedDiffFile } from './diff.ts' import type { ForgeDiffFile, ForgeFileLayer } from './types.ts' +import { wildmatch } from './wildmatch.ts' /** Path of the attributes file read beside each diff, relative to the repository root. */ export const ATTRIBUTES_PATH = '.gitattributes' @@ -81,9 +82,10 @@ function matcherOf(globs: readonly string[]): Matcher { * an earlier one. `dsh-review-layer=` names `test`, `interface`, or `implementation`; another value, * `-dsh-review-layer`, and `!dsh-review-layer` leave the layer unspecified. `linguist-generated` and `=true` set * the generated attribute, `-linguist-generated` and `=false` unset it, and `!linguist-generated` returns it to - * unspecified. A pattern without `/` matches a file name at any depth, and one with `/` matches from the repository - * root. Macro definitions, quoted patterns, and patterns ending in `/`, which name directories and so never match a - * file, are skipped. + * unspecified. Patterns follow Git's wildmatch rules, as {@link wildmatch} describes: a pattern without `/` matches a + * file name at any depth, and one with `/` matches the path from the repository root. Macro definitions, quoted + * patterns, negated patterns, which Git ignores in attributes, and patterns ending in `/`, which name directories and + * so never match a file, are skipped. * @param attributes - the text of the root `.gitattributes`, empty without one. * @returns the attributes of a repository-relative path. */ @@ -97,7 +99,7 @@ export function attributesOf(attributes: string): (path: string) => PathAttribut for (const raw of attributes.split(/\r?\n/)) { const [pattern, ...fields] = raw.trim().split(/\s+/) if (pattern === undefined || pattern === '' || pattern.startsWith('#') || pattern.startsWith('[attr]') - || pattern.startsWith('"') || pattern.endsWith('/')) continue + || pattern.startsWith('"') || pattern.startsWith('!') || pattern.endsWith('/')) continue let layer: ForgeFileLayer | null | undefined let generated: boolean | null | undefined for (const field of fields) { @@ -109,9 +111,10 @@ export function attributesOf(attributes: string): (path: string) => PathAttribut layer = isLayer(value) ? value : null } else if (field === `-${LAYER_ATTRIBUTE}` || field === `!${LAYER_ATTRIBUTE}`) layer = null } - if (layer === undefined && generated === undefined) continue - const anchored = pattern.replace(/^\//, '') - rules.push({ match: picomatch(anchored, { dot: true, basename: !pattern.includes('/') }), layer, generated }) + const test = wildmatch(pattern.replace(/^\//, '')) + if (test === undefined || (layer === undefined && generated === undefined)) continue + const match: Matcher = pattern.includes('/') ? test : path => test(path.slice(path.lastIndexOf('/') + 1)) + rules.push({ match, layer, generated }) } return (path) => { let layer: ForgeFileLayer | null | undefined diff --git a/packages/experimental/client-ui-forge/src/local-diff.ts b/packages/experimental/client-ui-forge/src/local-diff.ts index c17c443d13..88496f040c 100644 --- a/packages/experimental/client-ui-forge/src/local-diff.ts +++ b/packages/experimental/client-ui-forge/src/local-diff.ts @@ -10,6 +10,7 @@ import type { Context } from '@deepseek-ai/cordis' import { FsError } from '@deepseek-ai/dsh-fs' import type { Session } from '@deepseek-ai/dsh-session' import { assertNever } from '@deepseek-ai/dsh-util-values' +import { rangeStart } from './commit-range.ts' import { decodeText, oversizedUntrackedFile, parseDiff, parseNumstat, untrackedFile } from './diff.ts' import type { ParsedDiffFile } from './diff.ts' import { gitIn, GitOutputTooLarge } from './git.ts' @@ -65,6 +66,11 @@ export class CommitsMissing extends Error { override name = 'CommitsMissing' } +/** Thrown when chosen commits of the `branch` scope are not a run in which each commit's first parent is the one before it. */ +export class CommitsNotLinear extends Error { + override name = 'CommitsNotLinear' +} + /** A full SHA-1 or SHA-256 object name, the only form of a chosen commit Git receives. */ const COMMIT = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/ @@ -325,18 +331,23 @@ export async function aheadOf(git: Git, branch: string, commit: string): Promise * @param git - runner bound to the checkout, whose output limit bounds the listing. * @param fork - fork point of the `branch` scope. * @param limit - most commits listed. - * @returns the oldest `limit` commits and HEAD's commit. + * @returns the newest `limit` commits, ending with HEAD's commit, and HEAD's commit. * @throws an Error when Git fails or prints more than the runner's output limit. */ export async function localCommits(git: Git, fork: ForkPoint, limit: number): Promise { const head = (await git('head', ['rev-parse', '--verify', 'HEAD'])).stdout.trim() - const all = await branchCommits(git, fork) - return { headSha: head, commits: all.slice(0, limit), truncated: all.length > limit } + const listed = await branchCommits(git, fork, limit + 1) + return { headSha: head, commits: listed.slice(-limit), truncated: listed.length > limit } } -/** Every commit between the fork point and HEAD, parents before children. */ -async function branchCommits(git: Git, fork: ForkPoint): Promise { - const output = await git('log', ['log', '--topo-order', '--reverse', LOG_FORMAT, `${fork.commit}..HEAD`, '--']) +/** + * Commits between the fork point and HEAD, parents before children. + * @param limit - when given, only the newest `limit` commits in topological order. + */ +async function branchCommits(git: Git, fork: ForkPoint, limit?: number): Promise { + // A configured `log.showSignature` would print verification text before the fields and run the verifying program. + const count = limit === undefined ? [] : [`--max-count=${String(limit)}`] + const output = await git('log', ['log', '--no-show-signature', '--topo-order', '--reverse', ...count, LOG_FORMAT, `${fork.commit}..HEAD`, '--']) return output.stdout.split('\x1e').flatMap((record): ForgeCommit[] => { const fields = record.replace(/^\n/, '').split('\0') // The text after the last record holds no fields. @@ -349,12 +360,9 @@ async function branchCommits(git: Git, fork: ForkPoint): Promise /** The committed changes of consecutive commits of the `branch` scope, from the first commit's first parent to the last. */ async function commitsDiff(git: Git, fork: ForkPoint, chosen: ForgeCommitRange, layers: FileLayers): Promise { if (!COMMIT.test(chosen.from) || !COMMIT.test(chosen.to)) throw new CommitsMissing('The chosen commits are not full object names') - const commits = await branchCommits(git, fork) - const first = commits.findIndex(commit => commit.sha === chosen.from) - const start = commits[first] - if (start === undefined || commits.findIndex(commit => commit.sha === chosen.to) < first) { - throw new CommitsMissing('The chosen commits are no longer on the branch') - } + const start = rangeStart(await branchCommits(git, fork), chosen) + if (start === 'missing') throw new CommitsMissing('The chosen commits are no longer on the branch') + if (start === 'not-linear') throw new CommitsNotLinear('The chosen commits are not one run of first parents') // A first commit without a parent starts an unrelated history that HEAD merged; it adds every file. const parent = start.parent ?? await emptyTree(git) const overrides = await diffFilterOverrides(git) diff --git a/packages/experimental/client-ui-forge/src/types.ts b/packages/experimental/client-ui-forge/src/types.ts index 2a425cd2db..11dc7549e3 100644 --- a/packages/experimental/client-ui-forge/src/types.ts +++ b/packages/experimental/client-ui-forge/src/types.ts @@ -1,7 +1,7 @@ /** Browser-safe panel state, the worktree request record, Remote error codes, and Host configuration of the forge panel. */ import type {} from '@deepseek-ai/dsh-typert-protocol' -import type { ChangeRequestSnapshot, ForgeCommitList, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' +import type { ChangeRequestSnapshot, ForgeCommit, ForgeReadiness, ForgeRepository } from '@deepseek-ai/dsh-experimental-forge/types' import type { SessionChangeRequest } from '@deepseek-ai/dsh-experimental-forge-session/types' /** Git facts for the checkout that contains the Session's current directory. */ @@ -347,8 +347,15 @@ export interface ForgeChangeRequestDiff { readonly fileUrls: Readonly> } -/** Commits of the `branch` scope, which the changes view can show one or several of. */ -export type ForgeLocalCommits = ForgeCommitList +/** Commits of the `branch` scope at one HEAD commit, which the changes view can show one or several of. */ +export interface ForgeLocalCommits { + /** HEAD commit the list was read at. */ + readonly headSha: string + /** Commits oldest first, ending with HEAD's commit. */ + readonly commits: readonly ForgeCommit[] + /** Whether the branch has more commits than `maxCommits`; the listed ones are the newest. */ + readonly truncated: boolean +} /** One file the `branch` scope changes, without its hunks. */ export interface ForgeChangedFile { @@ -395,7 +402,7 @@ export interface Config { maxUntrackedFiles?: number /** Most UTF-8 bytes of change request diffs kept in memory for later reads at the same head commit and base branch. */ maxCachedDiffBytes?: number - /** Most commits of the `branch` scope listed, oldest first. */ + /** Most commits of the `branch` scope listed; a longer branch lists its newest ones. */ maxCommits?: number /** * Globs of files in the `test` layer, which the changes view can hide, beside the built-in rules and checked before @@ -459,6 +466,8 @@ declare module '@deepseek-ai/dsh-typert-protocol' { 'forgePanel/diff-failed': Record /** A chosen commit is no longer among the listed commits of the branch or change request, or the commits are out of order. */ 'forgePanel/commits-missing': Record + /** A chosen commit after the first lacks the commit listed before it as its first parent, so two ends cannot name the run. */ + 'forgePanel/commits-not-linear': Record } } diff --git a/packages/experimental/client-ui-forge/src/wildmatch.ts b/packages/experimental/client-ui-forge/src/wildmatch.ts new file mode 100644 index 0000000000..bed56ef8c5 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/wildmatch.ts @@ -0,0 +1,121 @@ +/** + * Patterns of `.gitattributes` lines, matched as Git's wildmatch matches them: `*` and `?` stay within one path + * segment, `**` between slashes or at either end crosses segments, `[...]` sets take `!` or `^` for negation, ranges, + * and POSIX classes, `\` makes the next character literal, and every other character, including `(`, `{`, and `+`, + * is literal. Matching is case-sensitive, as in Git unless `core.ignoreCase` is set, and compares characters where Git + * compares UTF-8 bytes, so `?` and ranges differ from Git only for characters outside ASCII. + */ + +/** ASCII members of each POSIX class wildmatch accepts, written as regular expression class ranges. */ +const CLASSES: Readonly> = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + blank: ' \\t', + cntrl: '\\x00-\\x1f\\x7f', + digit: '0-9', + graph: '\\x21-\\x7e', + lower: 'a-z', + print: '\\x20-\\x7e', + punct: '\\x21-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7e', + space: '\\t-\\r ', + upper: 'A-Z', + xdigit: '0-9a-fA-F', +} + +/** Write one character literally in a regular expression, inside or outside a class. */ +function literal(char: string): string { + return /[\\^$.*+?()[\]{}|/-]/.test(char) ? `\\${char}` : char +} + +/** + * Translate a bracket expression that starts at `pattern[start]`, which is `[`. + * @returns the regular expression class and the index of the closing `]`, or undefined for an unterminated set or an + * unknown class, which wildmatch treats as matching nothing. + */ +function bracket(pattern: string, start: number): { readonly source: string; readonly end: number } | undefined { + let index = start + 1 + const negated = pattern[index] === '!' || pattern[index] === '^' + if (negated) index += 1 + const members: string[] = [] + // The first character, even `]`, is a member, so the set closes at a later `]`. + for (let first = true; first || pattern[index] !== ']'; first = false, index += 1) { + let char = pattern[index] + if (char === undefined) return undefined + if (char === '[' && pattern[index + 1] === ':') { + // A class runs to the next `]`, which must follow `:`; otherwise the `[` is a member. + const close = pattern.indexOf(']', index + 2) + if (close === -1) return undefined + if (close > index + 2 && pattern[close - 1] === ':') { + const range = CLASSES[pattern.slice(index + 2, close - 1)] + if (range === undefined) return undefined + members.push(range) + index = close + continue + } + } + if (char === '\\') { + index += 1 + char = pattern[index] + if (char === undefined) return undefined + } + const to = pattern[index + 2] + if (pattern[index + 1] === '-' && to !== undefined && to !== ']') { + index += 2 + let end = to + if (end === '\\') { + index += 1 + end = pattern[index] ?? '' + if (end === '') return undefined + } + // A range whose end precedes its start matches only its start. + members.push(char <= end ? `${literal(char)}-${literal(end)}` : literal(char)) + continue + } + members.push(literal(char)) + } + const set = members.join('') + // A set never matches `/`. + return { source: negated ? `[^/${set}]` : `(?!/)[${set}]`, end: index } +} + +/** + * Compile one `.gitattributes` pattern, without the leading `/` that anchors it, into a test of a path. + * @param pattern - the pattern as written, which the caller has checked is not quoted, negated, or a directory. + * @returns a test of the text the pattern applies to, or undefined for a pattern that can match nothing. + */ +export function wildmatch(pattern: string): ((text: string) => boolean) | undefined { + let source = '' + for (let index = 0; index < pattern.length; index += 1) { + const char = pattern.charAt(index) + if (char === '\\') { + const next = pattern[index + 1] + if (next === undefined) return undefined + source += literal(next) + index += 1 + } else if (char === '?') { + source += '[^/]' + } else if (char === '*') { + let last = index + while (pattern[last + 1] === '*') last += 1 + const after = pattern[last + 1] + const crossing = last > index && (index === 0 || pattern[index - 1] === '/') && (after === undefined || after === '/') + if (crossing && after === '/') { + // `**/` also matches no directory at all. + source += '(?:.*/)?' + index = last + 1 + } else { + source += crossing ? '.*' : '[^/]*' + index = last + } + } else if (char === '[') { + const set = bracket(pattern, index) + if (set === undefined) return undefined + source += set.source + index = set.end + } else { + source += literal(char) + } + } + const expression = new RegExp(`^${source}$`, 's') + return text => expression.test(text) +} diff --git a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx index 97caf876a1..a4b277e34c 100644 --- a/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/changes-tab.client.spec.tsx @@ -557,24 +557,34 @@ describe('ChangesTab local reads', () => { expect(m.faces.localDiff).toHaveBeenCalledTimes(3) }) - it('reads again on refresh, on the page refresh command, and when the branch summary moves', async () => { + it('reads changes and commits again on refresh, on the page refresh command, and when the branch summary moves', async () => { const m = mount() await settle() expect(m.faces.localDiff).toHaveBeenCalledTimes(1) + expect(m.faces.localCommits).toHaveBeenCalledTimes(1) fireEvent.click(m.view.getByRole('button', { name: en['diff.refresh'] })) await settle() expect(m.faces.localDiff).toHaveBeenCalledTimes(2) + expect(m.faces.localCommits).toHaveBeenCalledTimes(2) const commands = m.tabActions.bindCommands.mock.calls[0]?.[0] act(() => { commands?.refresh?.() }) await settle() expect(m.faces.localDiff).toHaveBeenCalledTimes(3) + expect(m.faces.localCommits).toHaveBeenCalledTimes(3) act(() => { m.panel.set({ state: { ...LOCAL_STATE, readiness: null }, disconnected: false }) }) await settle() expect(m.faces.localDiff).toHaveBeenCalledTimes(3) + expect(m.faces.localCommits).toHaveBeenCalledTimes(3) act(() => { m.panel.set({ state: { ...LOCAL_STATE, local: { base: BASE, files: [] } }, disconnected: false }) }) await settle() expect(m.faces.localDiff).toHaveBeenCalledTimes(4) + expect(m.faces.localCommits).toHaveBeenCalledTimes(4) + // A commit of the staged changes moves HEAD without changing the summary against the fork point. + act(() => { m.panel.set({ state: ready({ local: { base: BASE, files: [] } }, { commit: 'f'.repeat(40) }), disconnected: false }) }) + await settle() + expect(m.faces.localDiff).toHaveBeenCalledTimes(4) + expect(m.faces.localCommits).toHaveBeenCalledTimes(5) m.view.unmount() expect(m.unbind).toHaveBeenCalledOnce() @@ -1590,10 +1600,13 @@ describe('ChangesTab commits', () => { expect((m.view.getByRole('button', { name: en['review.submit'] }) as HTMLButtonElement).disabled).toBe(true) }) - it('lists the commits of the branch scope only, and offers every commit when chosen ones are gone', async () => { + it('lists the commits of the branch scope only, and offers every commit when chosen ones are gone or not one run', async () => { const m = mount({ setup: (faces) => { - faces.localDiff.mockImplementation(async scope => scope.kind === 'branch' && scope.commits !== null - ? { ok: false, error: new RemoteError('forgePanel/commits-missing', 'gone', {}) } : ok(LOCAL)) + faces.localDiff.mockImplementation(async (scope) => { + if (scope.kind !== 'branch' || scope.commits === null) return ok(LOCAL) + const code = scope.commits.from === one.from ? 'forgePanel/commits-missing' : 'forgePanel/commits-not-linear' + return { ok: false, error: new RemoteError(code, 'refused', {}) } + }) } }) await settle() expect(m.faces.localCommits).toHaveBeenCalledWith(null, expect.any(AbortSignal)) @@ -1605,6 +1618,14 @@ describe('ChangesTab commits', () => { expect(m.view.getByText(en['commits.missing'])).toBeDefined() fireEvent.click(m.view.getByRole('button', { name: en['commits.showAll'] })) expect(m.store.getSnapshot().byTab[TAB]?.commits).toBeNull() + await settle() + fireEvent.click(m.view.getByRole('button', { name: 'Commits shown: All commits' })) + await settle() + fireEvent.click(within(document.body).getByRole('menuitem', { name: /^3333333/ })) + await settle() + expect(m.view.getByText(en['commits.notLinear'])).toBeDefined() + fireEvent.click(m.view.getByRole('button', { name: en['commits.showAll'] })) + expect(m.store.getSnapshot().byTab[TAB]?.commits).toBeNull() fireEvent.click(m.view.getByRole('button', { name: 'Branch' })) fireEvent.click(within(document.body).getByRole('menuitem', { name: en['diff.scope.staged'] })) diff --git a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts index e7d48e4b77..51f6ac0d66 100644 --- a/packages/experimental/client-ui-forge/tests/controller.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/controller.host.spec.ts @@ -549,19 +549,31 @@ describe('forgePanel local changes', () => { const listed = await opened.ctx.forgePanel.localCommits(opened.session, null, signal) expect(listed).toMatchObject({ truncated: true, headSha: await git(repo, 'rev-parse', 'HEAD') }) - expect(listed.commits.map(commit => commit.title)).toEqual(['one', 'two']) + expect(listed.commits.map(commit => commit.title)).toEqual(['two', 'three']) await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/topic', signal)) .resolves.toMatchObject({ truncated: false, commits: [{ title: 'three' }] }) - const [one, two] = listed.commits.map(commit => commit.sha) + const [two, three] = listed.commits.map(commit => commit.sha) const chosen = await opened.ctx.forgePanel.localDiff(opened.session, - { kind: 'branch', base: null, commits: { from: one ?? '', to: two ?? '' } }, signal) - expect(chosen.files.map(file => file.path)).toEqual(['one.txt', 'two.txt']) + { kind: 'branch', base: null, commits: { from: two ?? '', to: three ?? '' } }, signal) + expect(chosen.files.map(file => file.path)).toEqual(['three.txt', 'two.txt']) await expect(opened.ctx.forgePanel.localText(opened.session, - { kind: 'branch', base: null, commits: { from: one ?? '', to: one ?? '' } }, 'one.txt', signal)).resolves.toBe('one\n') + { kind: 'branch', base: null, commits: { from: two ?? '', to: two ?? '' } }, 'two.txt', signal)).resolves.toBe('two\n') await expect(opened.ctx.forgePanel.localDiff(opened.session, - { kind: 'branch', base: 'refs/heads/topic', commits: { from: one ?? '', to: two ?? '' } }, signal)) + { kind: 'branch', base: 'refs/heads/topic', commits: { from: two ?? '', to: three ?? '' } }, signal)) .rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) await expect(opened.ctx.forgePanel.localCommits(opened.session, 'refs/heads/gone', signal)).rejects.toMatchObject({ code: 'forgePanel/base-missing' }) + // A merged side branch lists its commit beside the branch's own, so a run across them is refused. + await git(repo, 'checkout', '--quiet', '-b', 'side', 'origin/main') + await writeFile(join(repo, 'side.txt'), 'side\n') + await git(repo, 'add', 'side.txt') + await git(repo, 'commit', '--quiet', '-m', 'side') + await git(repo, 'checkout', '--quiet', '-') + await git(repo, 'merge', '--quiet', '--no-ff', '--no-edit', 'side') + const order = (await git(repo, 'log', '--topo-order', '--reverse', '--format=%H %P', 'origin/main..HEAD')).split('\n').map(line => line.split(' ')) + const leaving = order.findIndex(([, parent], index) => index > 0 && parent !== order[index - 1]?.[0]) + await expect(opened.ctx.forgePanel.localDiff(opened.session, + { kind: 'branch', base: null, commits: { from: order[leaving - 1]?.[0] ?? '', to: order[leaving]?.[0] ?? '' } }, signal)) + .rejects.toMatchObject({ code: 'forgePanel/commits-not-linear' }) const unrelated = await project() const lonely = await open(unrelated.repo) @@ -737,6 +749,10 @@ describe('forgePanel change request diffs', () => { await expect(read(1, 1)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: 'The first chosen commit has no parent to compare with' }) await expect(read(3, 2)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) await expect(read(4, 3)).rejects.toMatchObject({ code: 'forgePanel/commits-missing' }) + // A commit of another branch listed between two others leaves the run of first parents. + opened.provider.commitLists.set(7, { ...list, commits: [commit(1, null), commit(2, sha(1)), commit(5, sha(1)), commit(3, sha(2))] }) + await expect(read(2, 5)).rejects.toMatchObject({ code: 'forgePanel/commits-not-linear' }) + opened.provider.commitLists.set(7, list) await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-failed', message: `no comparison ${sha(2)}..${sha(3)}` }) opened.provider.comparisons.set(`${sha(2)}..${sha(3)}`, { code: 'too-large', message: 'too many files' }) await expect(read(3, 3)).rejects.toMatchObject({ code: 'forgePanel/diff-too-large' }) diff --git a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts index 598109e93e..3f88cc7edc 100644 --- a/packages/experimental/client-ui-forge/tests/diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/diff.host.spec.ts @@ -94,6 +94,18 @@ describe('parseDiff', () => { expect(parseDiff(PATCH.replace('index bdc955b..8352675', 'index bdc955b..0000001'))[0]?.digest).not.toBe(digests[0]) }) + it('digests a mode change, which adds no hunk, apart from the same text change without it', () => { + const text = ['diff --git a/run.sh b/run.sh', 'index 1111111..2222222 100644', '--- a/run.sh', '+++ b/run.sh', '@@ -1 +1 @@', '-a', '+b', ''].join('\n') + const executable = text.replace('index 1111111..2222222 100644', 'old mode 100644\nnew mode 100755\nindex 1111111..2222222') + const [plain] = parseDiff(text) + const [moved] = parseDiff(executable) + expect(moved?.hunks).toEqual(plain?.hunks) + expect(moved?.digest).not.toBe(plain?.digest) + expect(parseDiff(executable)[0]?.digest).toBe(moved?.digest) + const modeOnly = ['diff --git a/run.sh b/run.sh', 'old mode 100644', 'new mode 100755', ''].join('\n') + expect(parseDiff(modeOnly)[0]?.digest).not.toBe(parseDiff(modeOnly.replace('100755', '100700'))[0]?.digest) + }) + it('digests a binary change without its blob names when a section does not start with a Git header', () => { const binary = 'diff --git a/x.png b/x.png\nindex 1111111..2222222 100644\nBinary files a/x.png and b/x.png differ\n' const withLeader = `--- a/y\n+++ b/y\n@@ -1 +1 @@\n-a\n+b\n${binary}` diff --git a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts index 7c7f74b9c6..79e7653bfc 100644 --- a/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts +++ b/packages/experimental/client-ui-forge/tests/local-diff.host.spec.ts @@ -7,8 +7,8 @@ import { FsError } from '@deepseek-ai/dsh-fs' import { gitIn, inspectCheckout } from '../src/git.ts' import type { Inspection } from '../src/git.ts' import { - aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, DiffTooLarge, forkPoint, localChanges, localCommits, localDiff, - localText, NoForkPoint, + aheadOf, BaseMissing, baseBranches, chosenForkPoint, CommitsMissing, CommitsNotLinear, DiffTooLarge, forkPoint, localChanges, + localCommits, localDiff, localText, NoForkPoint, } from '../src/local-diff.ts' import type { DiffConfig, ForkPoint } from '../src/local-diff.ts' import { FileLayers } from '../src/layers.ts' @@ -351,7 +351,7 @@ describe('commits of the branch scope', () => { return { repo, point: { commit: fork, label: 'origin/main', worktree: false }, shas } } - it('lists the commits between the fork point and HEAD oldest first, bounded by the limit', async () => { + it('lists the commits between the fork point and HEAD oldest first, keeping the newest ones over the limit', async () => { const { repo, point, shas } = await committed() const ctx = await context(repo) const runner = gitIn(ctx, CONFIG, plainSession(repo), repo, signal) @@ -364,7 +364,31 @@ describe('commits of the branch scope', () => { expect(listed.commits.map(commit => commit.sha)).toEqual(shas) expect(listed.commits.map(commit => commit.parent)).toEqual([point.commit, ...shas.slice(0, -1)]) expect(Date.parse(listed.commits[0]?.authoredAt ?? '')).not.toBeNaN() - await expect(localCommits(runner, point, 2)).resolves.toMatchObject({ truncated: true, commits: [{ title: 'committed' }, { title: 'staged' }] }) + await expect(localCommits(runner, point, 2)).resolves.toMatchObject({ truncated: true, commits: [{ title: 'second' }, { title: 'third' }] }) + await expect(localCommits(runner, point, 4)).resolves.toMatchObject({ truncated: false, commits: { length: 4 } }) + }) + + it('lists signed commits while the repository asks Git to show signatures', async () => { + const { repo, point, shas } = await committed() + const head = shas.at(-1) ?? '' + // A signature Git cannot verify still makes `log.showSignature` print verification text before each signed commit. + const tree = await git(repo, 'rev-parse', 'HEAD^{tree}') + const signed = join(repo, '.git', 'signed-commit') + await writeFile(signed, [ + `tree ${tree}`, `parent ${head}`, 'author Forge fixture 1700000000 +0000', + 'committer Forge fixture 1700000000 +0000', + 'gpgsig -----BEGIN SSH SIGNATURE-----', ' AAAA', ' -----END SSH SIGNATURE-----', '', 'signed', '', + ].join('\n')) + const sha = await git(repo, 'hash-object', '-t', 'commit', '-w', signed) + await git(repo, 'reset', '--quiet', '--soft', sha) + await git(repo, 'config', 'log.showSignature', 'true') + await git(repo, 'config', 'gpg.ssh.program', join(repo, 'missing-ssh-keygen')) + const ctx = await context(repo) + + const listed = await localCommits(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), point, 10) + expect(listed.commits.map(commit => [commit.sha, commit.title])).toEqual([ + ...shas.map((commit, index) => [commit, ['committed', 'staged', 'second', 'third'][index]]), [sha, 'signed'], + ]) }) it('reads the committed changes of consecutive commits with the attributes of the last one, without working tree changes', async () => { @@ -402,6 +426,33 @@ describe('commits of the branch scope', () => { expect(diff.files.map(file => [file.path, file.status])).toEqual([['orphan.txt', 'added']]) }) + it('refuses a run of commits whose first parents leave it, and reads one that follows them', async () => { + const { repo, fork } = await forked(await directory()) + await git(repo, 'commit', '--quiet', '-m', 'staged') + await git(repo, 'checkout', '--quiet', '-b', 'side', fork) + for (const name of ['side-one', 'side-two']) { + await writeFile(join(repo, `${name}.txt`), `${name}\n`) + await git(repo, 'add', `${name}.txt`) + await git(repo, 'commit', '--quiet', '-m', name) + } + await git(repo, 'checkout', '--quiet', 'feat') + await git(repo, 'merge', '--quiet', '--no-ff', '--no-edit', 'side') + const point: ForkPoint = { commit: fork, label: 'origin/main', worktree: false } + const ctx = await context(repo) + const listed = (await localCommits(gitIn(ctx, CONFIG, plainSession(repo), repo, signal), point, 10)).commits + const read = (from: string, to: string): Promise<{ readonly files: readonly { readonly path: string }[] }> => + localDiff(ctx, CONFIG, plainSession(repo), repo, point, { kind: 'branch', base: null, commits: { from, to } }, LAYERS, signal) + // Two branches from the fork point list their commits one after the other, so one pair of neighbours is unrelated. + const leaving = listed.findIndex((commit, index) => index > 0 && commit.parent !== listed[index - 1]?.sha) + const before = listed[leaving - 1]?.sha ?? '' + const after = listed[leaving]?.sha ?? '' + + expect(leaving).toBeGreaterThan(0) + await expect(read(before, after)).rejects.toBeInstanceOf(CommitsNotLinear) + const side = listed.filter(commit => commit.title.startsWith('side-')) + expect((await read(side[0]?.sha ?? '', side[1]?.sha ?? '')).files.map(file => file.path)).toEqual(['side-one.txt', 'side-two.txt']) + }) + it('refuses commits that are not full object names, not on the branch, or out of order', async () => { const { repo, point, shas } = await committed() const ctx = await context(repo) diff --git a/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx b/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx index 6f535ed954..c1ffebcbe4 100644 --- a/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx +++ b/packages/experimental/client-ui-forge/tests/review-controls.client.spec.tsx @@ -86,6 +86,14 @@ describe('LensMenu', () => { expect(within(document.body).queryByRole('menu')).toBeNull() }) + it('disables the test lens without its count while test files hide, as the segments do', () => { + const view = render() + fireEvent.click(view.getByRole('button', { name: 'Review layer: All' })) + const tests = within(document.body).getByRole('menuitem', { name: 'Tests' }) + expect(tests.textContent).toBe('Tests') + expect((tests as HTMLButtonElement).disabled).toBe(true) + }) + it('keeps its menu closed while the tab is hidden', () => { const view = render() fireEvent.click(view.getByRole('button', { name: 'Review layer: All' })) @@ -116,7 +124,7 @@ describe('CommitMenu', () => { function mount(props: Partial = {}) { const list = props.list ?? vi.fn(async () => ({ ok: true, value: COMMITS })) const choose = vi.fn() - const all: CommitMenuProps = { chosen: null, visible: true, version: 'v1', t, ...props, list, choose } + const all: CommitMenuProps = { chosen: null, visible: true, kept: 'oldest', version: 'v1', t, ...props, list, choose } const view = render() const rerender = (next: Partial): void => { view.rerender() } const rows = (): string[] => within(document.body).queryAllByRole('menuitem').map(row => row.textContent ?? '') @@ -130,7 +138,7 @@ describe('CommitMenu', () => { expect(commitsLabel({ from: sha(1), to: sha(2) }, t)).toBe('1111111…2222222') }) - it('reads the commits once per version, again on each opening, and chooses one or a Shift run of them', async () => { + it('reads the commits once per version, keeps them across openings, and chooses one or a Shift run of them', async () => { const m = mount() await settle() expect(m.list).toHaveBeenCalledTimes(1) @@ -140,7 +148,7 @@ describe('CommitMenu', () => { const trigger = m.view.getByRole('button', { name: 'Commits shown: All commits' }) fireEvent.click(trigger) await settle() - expect(m.list).toHaveBeenCalledTimes(2) + expect(m.list).toHaveBeenCalledTimes(1) const rows = m.rows() expect(rows[0]).toBe('All commits3 commits') expect(rows.slice(1).map((row, index) => row.startsWith(`${sha(index + 1).slice(0, 7)}commit ${index + 1}`) && row.endsWith(' d ago'))).toEqual([true, true, true]) @@ -173,9 +181,31 @@ describe('CommitMenu', () => { fireEvent.click(within(document.body).getByRole('menuitem', { name: /^All commits/ })) expect(m.choose).toHaveBeenLastCalledWith(null) + expect(m.list).toHaveBeenCalledTimes(1) m.rerender({ chosen: null, version: 'v2' }) await settle() - expect(m.list).toHaveBeenCalledTimes(7) + expect(m.list).toHaveBeenCalledTimes(2) + }) + + it('keeps its menu open and says why for a Shift run that leaves the first-parent line', async () => { + // The third commit sits on another branch from the first one, after the second in the list. + const commits = COMMITS.commits.map(commit => commit.sha === sha(3) ? { ...commit, parent: sha(1) } : commit) + const m = mount({ list: async () => ({ ok: true, value: { ...COMMITS, commits } }) }) + fireEvent.click(m.view.getByRole('button', { name: 'Commits shown: All commits' })) + await settle() + fireEvent.click(m.row(2)) + expect(m.choose).toHaveBeenLastCalledWith({ from: sha(2), to: sha(2) }) + m.rerender({ chosen: { from: sha(2), to: sha(2) } }) + fireEvent.click(m.view.getByRole('button', { name: 'Commits shown: 2222222' })) + await settle() + + fireEvent.click(m.row(3), { shiftKey: true }) + expect(m.choose).toHaveBeenCalledTimes(1) + expect(within(document.body).getByRole('menu')).toBeDefined() + expect(within(document.body).getByRole('status').textContent).toBe(en['commits.notLinear']) + fireEvent.click(m.row(1), { shiftKey: true }) + expect(m.choose).toHaveBeenLastCalledWith({ from: sha(1), to: sha(2) }) + expect(within(document.body).queryByRole('status')).toBeNull() }) it('starts a Shift run at the clicked commit without an earlier choice, and ignores choosing every commit again', async () => { @@ -205,6 +235,8 @@ describe('CommitMenu', () => { expect(m.rows()).toEqual(['All commits0 commits']) expect(within(document.body).queryByText(en['commits.shiftHint'])).toBeNull() expect(within(document.body).getByText('Only the earliest 0 commits are listed')).toBeDefined() + m.rerender({ kept: 'newest' }) + expect(within(document.body).getByText('Only the latest 0 commits are listed')).toBeDefined() fireEvent.keyDown(within(document.body).getByRole('menu'), { key: 'Escape' }) result = { ok: true, value: null } diff --git a/packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts b/packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts index 6a409bc7fe..4ebce40bbb 100644 --- a/packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts +++ b/packages/experimental/client-ui-forge/tests/viewed-files.client.spec.ts @@ -37,6 +37,48 @@ describe('ViewedFiles', () => { expect(listener).toHaveBeenCalledTimes(2) }) + it('keeps the marks another tab of the Session saved, and shows them as that tab saves them', () => { + const first = new ViewedFiles('s1') + const second = new ViewedFiles('s1') + expect(first.mark('pr', FILES, 'a.ts', true)).toBe(true) + expect(second.mark('pr', FILES, 'b.ts', true)).toBe(true) + expect([...new ViewedFiles('s1').marksOf('pr').keys()].sort()).toEqual(['a.ts', 'b.ts']) + + // The first subscriber reads what the other tab saved while nothing listened. + const listener = vi.fn() + const unsubscribe = first.subscribe(listener) + expect([...first.marksOf('pr').keys()].sort()).toEqual(['a.ts', 'b.ts']) + const stored = (key: string | null): void => { window.dispatchEvent(new StorageEvent('storage', { key })) } + second.mark('pr', FILES, 'a.ts', false) + stored('dsh.forge-viewed.v1."s2"') + expect(listener).not.toHaveBeenCalled() + stored('dsh.forge-viewed.v1."s1"') + expect(listener).toHaveBeenCalledTimes(1) + expect([...first.marksOf('pr').keys()]).toEqual(['b.ts']) + stored('dsh.forge-viewed.v1."s1"') + expect(listener).toHaveBeenCalledTimes(1) + localStorage.clear() + stored(null) + expect(first.marksOf('pr').size).toBe(0) + expect(listener).toHaveBeenCalledTimes(2) + + // The listener on storage stays while another subscriber remains. + const other = vi.fn() + const unsubscribeOther = first.subscribe(other) + unsubscribe() + second.mark('pr', FILES, 'a.ts', true) + stored('dsh.forge-viewed.v1."s1"') + expect(other).toHaveBeenCalledTimes(1) + localStorage.setItem('dsh.forge-viewed.v1."s1"', '{') + stored('dsh.forge-viewed.v1."s1"') + expect(first.marksOf('pr').size).toBe(0) + unsubscribeOther() + second.mark('pr', FILES, 'b.ts', true) + stored('dsh.forge-viewed.v1."s1"') + expect(other).toHaveBeenCalledTimes(2) + expect(listener).toHaveBeenCalledTimes(2) + }) + it('drops the marks of paths the diff no longer has and refuses a path it does not have', () => { const viewed = new ViewedFiles('s1') viewed.mark('pr', FILES, 'a.ts', true) diff --git a/packages/experimental/client-ui-forge/tests/wildmatch.host.spec.ts b/packages/experimental/client-ui-forge/tests/wildmatch.host.spec.ts new file mode 100644 index 0000000000..c2c9dce587 --- /dev/null +++ b/packages/experimental/client-ui-forge/tests/wildmatch.host.spec.ts @@ -0,0 +1,59 @@ +/** `.gitattributes` patterns: each pattern applies to the same paths as `git check-attr` applies it to. */ +import { writeFile } from 'node:fs/promises' +import { join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { attributesOf } from '../src/layers.ts' +import { git, scratch } from './harness.ts' + +/** Patterns whose meaning differs between Git's wildmatch and shell or glob libraries, or that Git refuses. */ +const PATTERNS = [ + 'src/(group)/**', 'foo.{js,ts}', '*.ts', '/root.ts', 'src/*.ts', '**/fixtures/*.json', 'a/**/b.txt', 'docs/**', 'a**b.txt', + 'src/**x/*.ts', '***/deep.txt', '?.md', '[abc].txt', '[!abc].txt', '[^abc].txt', '[a-c]x.txt', '[z-a].txt', '[!z-a].txt', + '[]].txt', '[]-a]y.txt', '[a-]x.txt', '[-a]w.txt', '[a-c-e]v.txt', '[\\]]u.txt', '[[:digit:]].txt', '[[:alpha:][:digit:]]z.txt', + '[[:digit:]-z]t.txt', '[[:]x.txt', '[[:foo:]].txt', '[[:digit:]', '[ab', '\\*.txt', '\\[x].txt', 'end\\', 'a+b.txt', 'c$.txt', + 'x|y.txt', '\\!bang.txt', '!neg.txt', 'src/[[:upper:]]*.ts', 'src/[!a]*.ts', '[[:space:]]s.txt', '[[:punct:]]p.txt', + '[a-\\c]r.txt', 'x[[:digit', 'y[\\', 'q[a-\\', +] + +const PATHS = [ + 'src/(group)/a.ts', 'src/group/a.ts', 'foo.{js,ts}', 'foo.js', 'a.ts', 'x/y/a.ts', 'root.ts', 'x/root.ts', 'src/a.ts', 'src/x/a.ts', + 'fixtures/a.json', 'x/fixtures/a.json', 'x/fixtures/y/a.json', 'a/b.txt', 'a/x/y/b.txt', 'docs/a/b.txt', 'docs', 'aXb.txt', 'aX/b.txt', + 'src/abx/a.ts', 'src/a/x/a.ts', 'deep.txt', 'x/y/deep.txt', 'q.md', 'qq.md', 'a.txt', 'd.txt', 'ax.txt', 'dx.txt', ']y.txt', '^y.txt', + 'ay.txt', 'by.txt', ']u.txt', 'ex.txt', '-x.txt', '-w.txt', 'aw.txt', 'av.txt', '-v.txt', 'dv.txt', 'ev.txt', '].txt', '5.txt', + 'z.txt', '5z.txt', 'zz.txt', '5t.txt', '-t.txt', 'zt.txt', '[x.txt', ':x.txt', '[[:digit:]', '[ab', 'ab', '*.txt', 'x.txt', + '[x].txt', 'end', 'a+b.txt', 'aab.txt', 'c$.txt', 'x|y.txt', 'x.txt', '!bang.txt', 'neg.txt', '!neg.txt', 'src/Ab.ts', 'src/ab.ts', + 'src/bb.ts', ' s.txt', 'ss.txt', '.p.txt', 'pp.txt', 'x/.p.txt', 'br.txt', 'cr.txt', 'dr.txt', 'x[[:digit', 'y[', 'q[a-', +] + +describe('attributesOf patterns', () => { + let repo = '' + let remove = async (): Promise => {} + + beforeAll(async () => { + ({ path: repo, remove } = await scratch('dsh-forge-wildmatch-')) + await git(repo, 'init', '--quiet') + }) + + afterAll(async () => { await remove() }) + + /** The paths `git check-attr` reports in the layer a one-line `.gitattributes` names. */ + async function gitMatches(pattern: string): Promise { + await writeFile(join(repo, '.gitattributes'), `${pattern} dsh-review-layer=test\n`) + const output = await git(repo, '-c', `core.attributesFile=${join(repo, 'none')}`, '-c', 'core.ignoreCase=false', + 'check-attr', '-z', 'dsh-review-layer', '--', ...PATHS) + const fields = output.split('\0') + const matched: string[] = [] + for (let index = 0; index + 2 < fields.length; index += 3) { + if (fields[index + 2] === 'test') matched.push(fields[index] ?? '') + } + return matched + } + + it('applies each pattern to the paths git check-attr applies it to', async () => { + for (const pattern of PATTERNS) { + const read = attributesOf(`${pattern} dsh-review-layer=test\n`) + const ours = PATHS.filter(path => read(path).layer === 'test') + expect({ pattern, matched: ours }).toEqual({ pattern, matched: await gitMatches(pattern) }) + } + }) +}) diff --git a/packages/experimental/client-ui-forge/tsconfig.client.json b/packages/experimental/client-ui-forge/tsconfig.client.json index 6b1f10f81f..6bc548094f 100644 --- a/packages/experimental/client-ui-forge/tsconfig.client.json +++ b/packages/experimental/client-ui-forge/tsconfig.client.json @@ -7,6 +7,7 @@ }, "include": [ "src/client", + "src/commit-range.ts", "src/css-modules.d.ts", "src/types.ts" ], diff --git a/packages/experimental/client-ui-forge/tsconfig.host.json b/packages/experimental/client-ui-forge/tsconfig.host.json index 65f55fefac..a6c004f078 100644 --- a/packages/experimental/client-ui-forge/tsconfig.host.json +++ b/packages/experimental/client-ui-forge/tsconfig.host.json @@ -7,6 +7,7 @@ }, "files": [ "src/index.ts", + "src/commit-range.ts", "src/diff.ts", "src/git.ts", "src/local-diff.ts", @@ -16,6 +17,7 @@ "src/patch-cache.ts", "src/states.ts", "src/types.ts", + "src/wildmatch.ts", "src/worktree.ts" ], "references": [ diff --git a/packages/experimental/forge-github/README.i18n.yaml b/packages/experimental/forge-github/README.i18n.yaml index 5fbff3d367..c329bf236f 100644 --- a/packages/experimental/forge-github/README.i18n.yaml +++ b/packages/experimental/forge-github/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-forge-github/use-this-package: - en: 8c1de4f9461d9160 - zh: 08b08d71e32b55a1 + en: 0f8041e0380036c9 + zh: 63cbdc82c9f438d4 /deepseek-ai-dsh-experimental-forge-github/understand-the-implementation: en: f98e77171cba809f zh: 1b330cb342d69efe diff --git a/packages/experimental/forge-github/README.md b/packages/experimental/forge-github/README.md index 35109f62b5..84a261269a 100644 --- a/packages/experimental/forge-github/README.md +++ b/packages/experimental/forge-github/README.md @@ -46,7 +46,7 @@ Unfinished check runs and completed runs with stale, missing, or unrecognized co A pull request is `mergeReady` when it is open, not a draft, GitHub reports its merge state as `CLEAN`, `HAS_HOOKS`, or `UNSTABLE`, and the signed-in user has write, maintain, or admin permission. `mergeMethods` lists the squash, merge-commit, and rebase methods the repository allows, the user's default merge method first. Marking ready runs `gh pr ready --repo //`. Merging calls `PUT repos///pulls//merge` through `gh api` with the method and the expected head SHA, so GitHub refuses once new commits arrived, which is reported as `stale`. Unlike `gh pr merge`, it never enables auto-merge, never joins a merge queue, and never deletes the head branch. A refused action reports GitHub's message, and a diagnostic that mentions authentication becomes `unauthenticated`. -`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head of the first one, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. +`diff` reads `headRefOid` and `baseRefOid` in one GraphQL query and returns `stale` when the head is not the requested commit, which must be a full 40- or 64-digit hexadecimal commit. Otherwise it reads `repos///compare/...` through `gh api --allow-escape-sequences` with the diff media type, the patch from the merge base of both commits, so neither end follows a moving branch. For every open and merged pull request measured, this patch is byte-identical to `gh pr diff`, which takes no commit argument. Unlike the pull request diff, the compare endpoint returns diffs over 300 files, so only output over `maxOutputBytes` or GitHub's own refusal makes such a diff `too-large`. `--allow-escape-sequences` keeps terminal escape sequences that file contents hold, which `gh` 2.97 and newer otherwise refuse to print; an older `gh` rejects the option with `unknown flag` before sending a request and prints such sequences unchanged, so that rejection repeats the read without it. `fileText` reads `repos///contents/?ref=` through `gh api` with the raw media type and accepts only a full 40- or 64-digit hexadecimal commit. `fileUrl` returns `https://///blob//`. Both paths percent-encode each segment. `commits` reads a pull request's commits through GraphQL, 100 per page with the owner, name, number, and cursor as variables, until `maxCommits`; every page must report the head and commit count of the first one and a cursor no earlier page returned, else the listing is `unavailable`. `compare` reads the patch from the merge base of two full commits to the second through the same compare request as `diff`. A refused read becomes `not-found` for HTTP 404, `unauthenticated` for a diagnostic that mentions authentication, `too-large` for GitHub's HTTP 406 refusal or `too_large` error, which a diff or file over its size limit draws, and `unavailable` otherwise, with GitHub's message. A read whose output exceeds `maxOutputBytes` becomes `too-large`, and one that outlives `timeoutMs` becomes `unavailable`. Review submission checks the current pull request head, then posts a single inline comment or one completed review through the REST API with an explicit `commit_id`. Multiline comments carry their side and inclusive start and end lines. Review decisions are Comment, Approve, and Request changes. JSON request bodies travel on stdin. The provider never retries a mutation: a timeout, unexpected response, or server error after dispatch returns an unknown outcome that the caller must reconcile on GitHub. A commit arriving between the check and the write can make the explicitly addressed review outdated; GitHub does not offer an atomic head precondition on these endpoints. diff --git a/packages/experimental/forge-github/README.zh.md b/packages/experimental/forge-github/README.zh.md index f1ef4f6c35..205a8f0439 100644 --- a/packages/experimental/forge-github/README.zh.md +++ b/packages/experimental/forge-github/README.zh.md @@ -46,7 +46,7 @@ kind: "package-reference" pull request 处于打开状态、不是草稿、GitHub 报告其合并状态为 `CLEAN`、`HAS_HOOKS` 或 `UNSTABLE`,且已登录用户具有 write、maintain 或 admin 权限时,`mergeReady` 为真。`mergeMethods` 列出仓库允许的压缩合并、合并提交与变基合并方式,用户默认的合并方式排在最前。标记为可评审运行 `gh pr ready --repo //`。合并经 `gh api` 调用 `PUT repos///pulls//merge`,带上合并方式与预期的 head SHA,因此有新提交到达后 GitHub 会拒绝,报告为 `stale`。与 `gh pr merge` 不同,它从不启用自动合并、从不加入合并队列,也从不删除 head 分支。被拒绝的操作报告 GitHub 的原因,提到身份验证的诊断转为 `unauthenticated`。 -`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 必须与第一页相同,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 +`diff` 在一次 GraphQL 查询中读取 `headRefOid` 与 `baseRefOid`,head 不是请求的提交时返回 `stale`;请求的提交必须是完整的 40 位或 64 位十六进制提交。否则经 `gh api --allow-escape-sequences` 以 diff 媒体类型读取 `repos///compare/...`,即两个提交的合并基准到 head 的补丁,两端都不跟随移动的分支。实测的所有 open 与已合并 pull request 上,该补丁与不接受提交参数的 `gh pr diff` 逐字节一致。与 pull request diff 不同,compare 接口会返回超过 300 个文件的 diff,因此这类 diff 只有在输出超过 `maxOutputBytes` 或 GitHub 自身拒绝时才为 `too-large`。`--allow-escape-sequences` 保留文件内容中的终端转义序列;否则 `gh` 2.97 及以上版本拒绝输出。更早的 `gh` 在发出请求前就以 `unknown flag` 拒绝该选项,且原样输出这类序列,因此遇到这一拒绝时去掉该选项重读一次。`fileText` 经 `gh api` 以 raw 媒体类型读取 `repos///contents/?ref=`,只接受完整的 40 位或 64 位十六进制提交。`fileUrl` 返回 `https://///blob//`。两者的路径都逐段做百分号编码。`commits` 经 GraphQL 读取拉取请求的提交,每页 100 个,owner、name、number 与游标作为变量传入,直到 `maxCommits`;每一页报告的 head 与提交总数必须与第一页相同,游标也不能与之前任何一页重复,否则返回 `unavailable`。`compare` 用与 `diff` 相同的 compare 请求读取两个完整提交的合并基准到第二个提交的补丁。被拒绝的读取在 HTTP 404 时为 `not-found`,诊断提到身份验证时为 `unauthenticated`,GitHub 以 HTTP 406 拒绝或报告 `too_large` 错误时(diff 或文件超过其大小上限即会如此)为 `too-large`,其余为 `unavailable`,并带有 GitHub 的原因。输出超过 `maxOutputBytes` 的读取为 `too-large`,超过 `timeoutMs` 的为 `unavailable`。 提交评审时先检查 PR 当前的 head,再通过 REST API 发布单条行内评论或一次完整评审,并显式指定 `commit_id`。多行评论携带所属侧及包含端点的起止行号。评审结论为“评论”“批准”或“请求更改”。JSON 请求正文通过标准输入传递。provider 不会重试写操作;发送后的超时、异常响应或服务端错误会返回结果不明,由调用方到 GitHub 核对。检查与写入之间到来的新提交可能让已明确定位到旧提交的评审过时;GitHub 的这些接口不提供原子的 head 前置条件。 diff --git a/packages/experimental/forge-github/src/commits.ts b/packages/experimental/forge-github/src/commits.ts index 24a0d830b0..e00c101571 100644 --- a/packages/experimental/forge-github/src/commits.ts +++ b/packages/experimental/forge-github/src/commits.ts @@ -50,7 +50,8 @@ export type GraphqlReader = (args: readonly string[], signal: AbortSignal) => Pr /** * List a pull request's commits oldest first, at most `limit`, reading pages until the limit or the last commit. - * Every page must report the head of the first page, so the list never mixes two pushes. + * Every page must report the head and commit count of the first page, so the list never mixes two pushes, and a cursor + * no earlier page returned, so the listing ends. * @param read - runs one GraphQL request. * @param ref - validated pull request address. * @param limit - most commits listed. @@ -65,7 +66,8 @@ export async function listCommits( ): Promise { const { host, owner, name } = checkedRepository(ref) const commits: ForgeCommit[] = [] - let head: string | undefined + const cursors = new Set() + let first: { readonly head: string; readonly total: number } | undefined let cursor: string | null = null for (;;) { const body = await read([ @@ -78,10 +80,11 @@ export async function listCommits( if (!parsed.success) return { code: 'unavailable', message: 'unexpected GitHub response to the commit listing' } const pull = parsed.data.data.repository?.pullRequest if (pull == null) return { code: 'not-found', message: `pull request ${ref.number} was not found` } - if (head !== undefined && pull.headRefOid !== head) { + const { headRefOid: head, commits: { totalCount: total, pageInfo: { hasNextPage, endCursor } } } = pull + first ??= { head, total } + if (head !== first.head || total !== first.total) { return { code: 'unavailable', message: 'The pull request head changed while its commits were read' } } - head = pull.headRefOid for (const { commit } of pull.commits.nodes) { commits.push({ sha: commit.oid, @@ -91,10 +94,9 @@ export async function listCommits( authoredAt: commit.authoredDate, }) } - const { hasNextPage, endCursor } = pull.commits.pageInfo - if (!hasNextPage || endCursor === null || commits.length >= limit) { - return { headSha: head, commits, truncated: pull.commits.totalCount > commits.length } - } + if (!hasNextPage || commits.length >= limit) return { headSha: head, commits, truncated: total > commits.length } + if (endCursor === null || cursors.has(endCursor)) return { code: 'unavailable', message: 'GitHub commit pagination did not advance' } + cursors.add(endCursor) cursor = endCursor } } diff --git a/packages/experimental/forge-github/src/provider.ts b/packages/experimental/forge-github/src/provider.ts index 8a7939a7d4..67e963e3d9 100644 --- a/packages/experimental/forge-github/src/provider.ts +++ b/packages/experimental/forge-github/src/provider.ts @@ -193,7 +193,8 @@ export class GitHubProvider implements ForgeProvider { /** List the pull request's commits through GraphQL, at most `maxCommits`, all read at one head. */ async commits(ref: ChangeRequestRef, signal: AbortSignal): Promise { - const failure = this.hostFailure(ref.repository.host) + const { host } = checkedRepository(ref) + const failure = this.hostFailure(host) if (failure !== undefined) return failure return await listCommits(this.graphql, ref, this.limits.maxCommits, signal) } diff --git a/packages/experimental/forge-github/tests/provider.spec.ts b/packages/experimental/forge-github/tests/provider.spec.ts index d1c2326291..1993c8cee6 100644 --- a/packages/experimental/forge-github/tests/provider.spec.ts +++ b/packages/experimental/forge-github/tests/provider.spec.ts @@ -583,10 +583,26 @@ describe('GitHub provider commits', () => { expect(bounded.calls[0]).toEqual(expect.arrayContaining(['first=2'])) }) - it('refuses a listing whose head moves between pages, a missing pull request, and an unexpected response', async () => { + it('refuses a listing whose head or count moves between pages, or whose pages do not advance', async () => { const moved = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(4)) : page([node(1)], 'page-1')) await expect(provider(moved.run).commits(pull(7), signal)) .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + const recounted = fakeGh(args => args.includes('cursor=page-1') ? page([node(3)], null, sha(3), 4) : page([node(1)], 'page-1')) + await expect(provider(recounted.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'The pull request head changed while its commits were read' }) + // A page that repeats the cursor it was read after would be requested again forever. + const stuck = fakeGh(args => page(args.includes('cursor=page-1') ? [] : [node(1)], 'page-1')) + await expect(provider(stuck.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'GitHub commit pagination did not advance' }) + expect(stuck.calls).toHaveLength(2) + const endless = fakeGh(() => output({ data: { repository: { pullRequest: { + headRefOid: sha(3), commits: { totalCount: 3, pageInfo: { hasNextPage: true, endCursor: null }, nodes: [node(1)] }, + } } } })) + await expect(provider(endless.run).commits(pull(7), signal)) + .resolves.toEqual({ code: 'unavailable', message: 'GitHub commit pagination did not advance' }) + }) + + it('refuses a missing pull request and an unexpected response', async () => { await expect(provider(fakeGh(() => output({ data: { repository: { pullRequest: null } } })).run).commits(pull(7), signal)) .resolves.toEqual({ code: 'not-found', message: 'pull request 7 was not found' }) await expect(provider(fakeGh(() => output({ data: { repository: null } })).run).commits(pull(7), signal)) @@ -632,5 +648,12 @@ it('rejects readiness, actions, and content reads for an unconfigured host witho await expect(subject.fileText(target, 'a'.repeat(40), 'file.txt', signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.commits(target, signal)).resolves.toEqual({ code: 'unavailable', message }) await expect(subject.compare(target, 'a'.repeat(40), 'b'.repeat(40), signal)).resolves.toEqual({ code: 'unavailable', message }) + // A repository that cannot name a request is refused before its host, as every read refuses it. + const unsafe = pull(7, { ...demo, host: 'unconfigured.example', owner: 'oc/to' }) + const invalid = 'forge-github: invalid repository "oc/to/demo"' + await expect(subject.diff(unsafe, 'a'.repeat(40), signal)).rejects.toThrow(invalid) + await expect(subject.fileText(unsafe, 'a'.repeat(40), 'file.txt', signal)).rejects.toThrow(invalid) + await expect(subject.commits(unsafe, signal)).rejects.toThrow(invalid) + await expect(subject.compare(unsafe, 'a'.repeat(40), 'b'.repeat(40), signal)).rejects.toThrow(invalid) expect(gh.calls).toEqual([]) }) diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 919c486d18..de37043f87 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1389,13 +1389,13 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read the changes one scope covers in the checkout of the Session\'s current directory, with Git using the Session\'s sandbox policy.', parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'scope', description: 'which changes to read.' }, { name: 'signal', description: 'request cancellation.' }], returns: 'the files, the base of the `branch` scope, and the untracked files left out.', - throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'], + throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch chosen for the `branch` scope does not exist; `forgePanel/no-fork-point` for the `branch` scope without a fork point; `forgePanel/commits-missing` when chosen commits are not between the fork point and HEAD in order; `forgePanel/commits-not-linear` when a chosen commit\'s first parent is not the commit listed before it; `forgePanel/filter-config-failed` when filter configuration cannot be read completely, before any comparison; `forgePanel/diff-too-large` over `maxDiffBytes`; the Git error when Git fails.'], }, { signature: '@Remote async localCommits(session: Session, base: string | null, signal: AbortSignal): Promise', description: 'List the commits of the `branch` scope of the Session\'s current checkout, which the changes view can show one or several of instead of the whole scope.', parameters: [{ name: 'session', description: 'Session whose checkout is read.' }, { name: 'base', description: 'the base ref of the `branch` scope, or null for its automatic fork point.' }, { name: 'signal', description: 'request cancellation.' }], - returns: 'at most `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD\'s commit.', + returns: 'the newest `maxCommits` commits between the fork point and HEAD, oldest first, and HEAD\'s commit.', throws: ['`forgePanel/not-a-checkout` outside a checkout; `forgePanel/base-missing` when the base branch does not exist; `forgePanel/no-fork-point` without a fork point; the Git error when Git fails or the listing exceeds `maxDiffBytes`.'], }, { @@ -1424,7 +1424,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Read the changes of a change request of a Session as its code host computes them, with each file\'s layer following the root `.gitattributes` of the commit the diff ends at. Without `commits` the diff covers the change request at the head commit of its latest status; a patch already read at the same head commit and base branch is reused from memory with its attributes, for any Session, until `maxCachedDiffBytes` evicts it. With `commits`, it covers those commits, from the first one\'s first parent to the last, and is read every time.', parameters: [{ name: 'session', description: 'Session the change request is bound to.' }, { name: 'url', description: 'binding URL of the change request.' }, { name: 'commits', description: 'consecutive commits of the change request, or null for all of it.' }, { name: 'signal', description: 'request cancellation.' }], returns: 'the files, the commit they end at, each file\'s web page, and the commits the checkout has beyond the head.', - throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/commits-missing` when chosen commits are not among the change request\'s commits in order; `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again; `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host does not provide the commits, the diff, or an existing `.gitattributes` otherwise.'], + throws: ['`forgePanel/not-bound` unless the URL is a visible binding of the Session that a provider serves; `forgePanel/commits-missing` when chosen commits are not among the change request\'s commits in order; `forgePanel/commits-not-linear` when a chosen commit\'s first parent is not the commit listed before it; `forgePanel/stale-head` without `commits` when the head moved past the latest status, which is then polled again; `forgePanel/diff-too-large` when the host or its provider refuses the diff over a size limit; `forgePanel/diff-failed` before its status was read, for a first chosen commit without a parent, and when the host does not provide the commits, the diff, or an existing `.gitattributes` otherwise.'], }, { signature: '@Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise', @@ -6703,7 +6703,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'ForgeLocalCommits', - declaration: 'export type ForgeLocalCommits = ForgeCommitList;', + declaration: 'export interface ForgeLocalCommits {\n readonly headSha: string;\n readonly commits: readonly ForgeCommit[];\n readonly truncated: boolean;\n}', }, { name: 'ForgeLocalDiff', From 6d6fc8968600f86f327568195097f73bd9bd5f5e Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 13:05:01 +0800 Subject: [PATCH 085/103] test: cover macOS CUA channel policy forwarding on every platform --- .../cua-macos/tests/provider-channel.spec.ts | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 packages/experimental/cua-macos/tests/provider-channel.spec.ts diff --git a/packages/experimental/cua-macos/tests/provider-channel.spec.ts b/packages/experimental/cua-macos/tests/provider-channel.spec.ts new file mode 100644 index 0000000000..02d9fc0fe6 --- /dev/null +++ b/packages/experimental/cua-macos/tests/provider-channel.spec.ts @@ -0,0 +1,36 @@ +/** Provider configuration reaches the native transport without opening a macOS connection. */ +import { resolve } from 'node:path' +import { PassThrough } from 'node:stream' +import { Context } from '@deepseek-ai/cordis' +import { installCua } from '@deepseek-ai/dsh-cua' +import type { NativeChannel } from '@deepseek-ai/dsh-cua/native-client' +import { expect, it, onTestFinished, vi } from 'vitest' +import { apply, Config } from '../src/index.ts' +import { createSharedNativeChannel } from '../src/shared-native.ts' + +vi.mock('@deepseek-ai/dsh-cua', async importOriginal => ({ + ...await importOriginal(), + installCua: vi.fn(), +})) +vi.mock('../src/shared-native.ts', () => ({ createSharedNativeChannel: vi.fn() })) + +it.each([false, true])('forwards systemPointerHover=%s and native limits to each channel', async (systemPointerHover) => { + const ctx = new Context() + onTestFinished(() => ctx.fiber.dispose()) + const config = Config({ helperPath: resolve('fixture-helper'), systemPointerHover }) + const channel: NativeChannel = { + stdin: new PassThrough(), stdout: new PassThrough(), done: Promise.resolve(), + close() {}, waitForClose: async () => {}, + } + onTestFinished(() => { channel.stdin.destroy(); channel.stdout.destroy() }) + vi.mocked(installCua).mockClear() + vi.mocked(createSharedNativeChannel).mockReset().mockReturnValue(channel) + + await apply(ctx, config) + expect(installCua).toHaveBeenCalledTimes(1) + const backend = vi.mocked(installCua).mock.calls[0]![2] + const owner = { subprocess: { spawn: vi.fn() } } + const native = { ...config, helperPath: resolve('fixture-helper'), cwd: process.cwd() } + expect(backend.createChannel(owner, native)).toBe(channel) + expect(createSharedNativeChannel).toHaveBeenCalledExactlyOnceWith(owner, native, systemPointerHover) +}) From 5a0c6c10f8163c57d0935ac791bbe5894ad59b41 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 13:08:42 +0800 Subject: [PATCH 086/103] fix(cua-macos): validate physical key chords before dispatch --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 8 ++-- ...026-11-05-cua-scoped-surfaces-and-input.md | 4 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 4 +- .../cua-native-platform/guide.i18n.yaml | 4 +- .../v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../cua-native-platform/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 8 ++-- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- .../Sources/CuaNative/KeyboardInput.swift | 31 ++++++++----- .../Sources/CuaNative/RequestAdmission.swift | 10 ++-- .../cua-macos/native/protocol.schema.json | 3 +- .../native/tests/capabilities_e2e.py | 13 +++--- .../tests/swift/KeyboardChordTests.swift | 46 ++++++++++++++++--- .../native/tests/swift/ProtocolTests.swift | 12 +++++ .../experimental/cua-macos/src/guidance.ts | 1 + .../cua-macos/tests/guidance.spec.ts | 8 +++- packages/experimental/cua/README.i18n.yaml | 2 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/src/guidance.ts | 2 +- packages/experimental/cua/src/protocol.ts | 5 +- packages/experimental/cua/src/types.ts | 2 +- .../experimental/cua/tests/protocol.spec.ts | 7 +++ .../cua-native/system-prompt.expected.md | 2 +- .../cua-native/tool-schemas.expected.json | 3 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 30 files changed, 137 insertions(+), 68 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index f3a0d8f1d3..adad612610 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -9,11 +9,11 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: ec115e11f96ffe60 - zh: c1fe9eb2866196d0 + en: 74f97ec371e61b82 + zh: a8a5cefc1e06bb20 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: - en: 32c970ae153e0f6c - zh: 8431be0a10ffed15 + en: 2113f17a49e16670 + zh: 1df04d9736a3ad4f /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: en: 5c6ec60b77f1bff0 zh: e1ae568ef3501b7b diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 609e5bf901..655172fb19 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -14,7 +14,7 @@ Application and window objects share accessibility operations, but only an expli Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. -Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. +Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses one key or, on macOS, several physical keys in order and releases them in reverse while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. @@ -24,7 +24,7 @@ Within one API instance, the object facade keeps one current accessibility snaps **An application-specific branch in the shared base** would let window objects inherit decisions and capability checks that apply only to applications. Scope factories that inject their own requirements keep the shared operations independent of which scope uses them. -**A packed chord string** requires parsing key names, separators, and plus escaping together, and it pushes platform alias normalization into the shared layer. Keystroke and direction are separate semantics: `pressKey` describes one complete keystroke, while `sendKeyEvent` describes one explicit direction. Separate key and modifier values keep those semantics without a parser. +**A packed chord string** requires parsing key names, separators, and plus escaping together, and it pushes platform alias normalization into the shared layer. Keystroke and direction are separate semantics: `pressKey` describes a complete press and release, while `sendKeyEvent` describes one explicit direction. Separate key and modifier values keep those semantics without a parser. **Platform keyboard key enumerations in the shared schema** would couple the portable operation schema to one provider's key names and require a schema change for each platform. Provider-defined strings let the provider interpret its own names while the shared schema stays neutral. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 081f02986e..495ba2d399 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -14,7 +14,7 @@ Status: implemented Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 -键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 +键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放指定的键。macOS 也接受多个物理键,依次按下并逆序释放。修饰键名称由提供方定义,以字符串数组传入。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 @@ -24,7 +24,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 **在共享基类中加入应用专属分支**会让窗口对象继承只适用于应用的决定和能力检查。由各作用域工厂注入自己的要求,可以让共享操作不依赖使用它的作用域。 -**打包的组合键字符串**需要一起解析按键名、分隔符和加号转义,并把平台别名归一化推入共享层。击键与方向是两种语义:`pressKey` 描述一次完整击键,`sendKeyEvent` 描述一个显式方向。分开的按键和修饰键值让这些语义无需解析器。 +**打包的组合键字符串**需要一起解析按键名、分隔符和加号转义,并把平台别名归一化推入共享层。击键与方向是两种语义:`pressKey` 在一次调用中完成按下和释放,`sendKeyEvent` 描述一个显式方向。分开的按键和修饰键值让这些语义无需解析器。 **在共享 schema 中枚举平台键盘按键**会把可移植的操作 schema 绑定到某个 provider 的按键名,并让每个平台都修改 schema。由 provider 定义字符串,平台可以解释自己的名称,共享 schema 保持中立。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index a76d4de320..c3d5791588 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: b09e3dde32391786 - zh: f702e1e25b260b29 + en: 4cf8b18af0d2bb79 + zh: 7f490fd9785deffe diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 3179dae0d9..363e627e66 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -18,6 +18,6 @@ Providers supply startup capabilities alongside their platform guidance. The nat 1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. 2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. -4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. 5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. 6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index f0a4a905e0..272e4a96d4 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -18,6 +18,6 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 -4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index bcc12b8ecc..6a38002c4f 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: e3643640ef764471 - zh: 5d25e833cb78bf9b + en: 24ea893846cf0914 + zh: dca284e8e589274d /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 63e1c495d2..60d57c749d 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -79,7 +79,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. `getApp` returns the `appHandle` used by every app-targeted operation, and `app.getWindow(windowId)` returns the object that owns screenshots and pointer input. -`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct keys. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass modifier names separately, for example `pressKey('Tab', ['shift'])` or `pressKey('+')`; an omitted modifier array means none. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. On macOS, use `pressKey` on the App object. The shared `sendKeyEvent` operation returns `NOT_IMPLEMENTED` on this provider. +`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct physical keys. Aliases such as `Enter` and `Return` identify the same key. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass held modifiers separately, as in `pressKey('Tab', ['shift'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. In a multi-key chord, use `=` and pass Shift explicitly to apply it to the whole chord. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. On macOS, use `pressKey` on the App object. The shared `sendKeyEvent` operation returns `NOT_IMPLEMENTED` on this provider. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -221,7 +221,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 276f725cb3..cadefe0dd6 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -79,7 +79,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。`getApp` 返回每个面向应用的操作所需的 `appHandle`,`app.getWindow(windowId)` 返回负责截图和指针输入的对象。 -`pressKey(key, modifiers?)` 接受单个键名或由不同键名组成的非空数组。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。修饰键名称单独传入,例如 `pressKey('Tab', ['shift'])` 或 `pressKey('+')`;省略修饰键数组表示不按修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。在 macOS 上,通过 App 对象调用 `pressKey`。调用共享接口 `sendKeyEvent` 会收到 `NOT_IMPLEMENTED`。 +`pressKey(key, modifiers?)` 接受单个键名或由不同物理键组成的非空数组。`Enter` 和 `Return` 等别名指向同一个物理键。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。需要全程按住的修饰键单独传入,例如 `pressKey('Tab', ['shift'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。单独传入 `+` 或 `plus` 会发送 Shift 和等号。在多键组合中请使用 `=`,需要全程按住 Shift 时将其列入修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。在 macOS 上,通过 App 对象调用 `pressKey`。调用共享接口 `sendKeyEvent` 会收到 `NOT_IMPLEMENTED`。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -221,7 +221,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 6e9294f0ce..7382f3006b 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,11 +21,11 @@ en: 88a59904ca4ebedc zh: 14f2b666d7382145 /dsh-cua-native-helper/observation-and-input: - en: d19180b1a6db2e48 - zh: c6279db9957218eb + en: 51a70780a0672272 + zh: e7ca17dd40b887aa /dsh-cua-native-helper/verification: - en: 49f4cce2a4cc3114 - zh: e9d65c92ef35fe24 + en: ade5a2ccd3aeb1b4 + zh: 74c2b0bcb23fc4bc /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b94d053746..2437c220a4 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -103,7 +103,7 @@ Clicks send mouse-down and mouse-up events at the element center or the supplied Capture and pointer delivery read CG bounds before and after an exact-window AX frame query. Movement during the query returns WINDOW_CHANGED. Valid AX/CG frames must have equal outward-rounded integral point rectangles; a known mismatch returns WINDOW_CHANGED before mouse movement, priming or button delivery. The helper preserves both coordinate sources rather than substituting AX geometry for CG geometry. Missing or unusable AX geometry remains unknown, while AX communication, permission and invalid-element errors propagate. Capture without Accessibility permission retains its CG/SCK checks. Advertised AX actions bypass this pointer preflight; an AX action error does not trigger pointer input. These reads do not lock the window against later movement, and no geometry check activates or raises it. -`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses its modifiers followed by the requested keys in order, then releases all pressed keys in reverse order, including on cancellation; these events do not use the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. +`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses its modifiers followed by the requested keys in order, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. @@ -157,7 +157,7 @@ For text pacing comparisons, use `native/tests/text_input_benchmark.py` with `-- For an independently isolated Electron/Chromium check, run `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`. Omitting `--electron` uses an already installed desktop workspace runtime. The check never downloads Electron. Its renderer runs with Node integration disabled, context isolation and Chromium sandboxing enabled, private userData/sessionData/log directories, and a local fixture page. Renderer click/input events write independent observations through the main process; all test actions still use the native helper. AX polling waits for actual controls after Chromium accessibility activation. Native and Electron subprocess groups are owned and stopped before temporary files are removed. Optional artifacts include a fixture-only screenshot and private request transcript. -Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures and keypad identities through an isolated AppKit receiver. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results. +Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures, overlapping W and D key events, and keypad identities through an isolated AppKit receiver. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results. Run `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence` to verify that an owned AppKit app accepts a background Paste action without reading its data, reports `PASTE_NOT_CONSUMED`, then consumes the same paste in the foreground. The test requires an unlocked Mac and Accessibility permission, activates only its own two applications, and records received actions and text independently of helper replies. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 7ddde7d4f4..1224e0e6db 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -103,7 +103,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 截图和鼠标输入在精确窗口的 AX 边界查询前后读取 CG 边界,查询期间移动会返回 WINDOW_CHANGED。有效的 AX/CG 边界向外取整后必须一致;已知不一致会在移动、预备事件或按键发送前返回 WINDOW_CHANGED。helper 保留两个坐标来源,不用 AX 几何替换 CG 几何。缺失或无效的 AX 几何仍表示未知,AX 通信、权限和无效元素错误继续传递。无辅助功能权限的截图保留 CG/SCK 检查。声明的 AX 动作不经过鼠标预检,AX 动作失败也不改用鼠标输入。这些读取不会锁住窗口以阻止后续移动,几何检查不激活或抬起窗口。 -`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和指定按键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 +`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和指定按键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 @@ -157,7 +157,7 @@ Blender 键盘检查使用 `python3 packages/experimental/cua-macos/native/tests 隔离的 Electron/Chromium 检查使用 `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`。省略 `--electron` 时使用桌面工作区已安装的运行时,检查不下载 Electron。渲染器禁用 Node 集成,启用上下文隔离和 Chromium 沙箱,使用独立 userData/sessionData/log 目录及本地 fixture 页面。渲染器的点击/输入事件通过主进程写出独立观察,测试动作仍通过原生 helper 执行。AX 轮询等待 Chromium 辅助功能启用后的真实控件。原生和 Electron 子进程组由测试持有,在删除临时文件前停止。可选产物包含仅有 fixture 的截图和私有请求记录。 -运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、中键/修饰键手势及数字键盘身份。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。 添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。 +运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。 添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。 运行 `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence`,验证自有 AppKit 应用在后台接收 Paste 动作但不读取数据时返回 `PASTE_NOT_CONSUMED`,以及前台读取同一次粘贴后成功。测试要求 Mac 已解锁并已授予辅助功能权限,只激活自有的两个应用,并独立记录收到的动作和文本以核对 helper 回复。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index 2dbf648ecf..3511256457 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -22,23 +22,32 @@ final class KeyboardInput { /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. func pressKey(_ keys: [String], modifiers: [String], to pid: Int32) throws { try checkCancellation() - var modifierNames = modifiers - let mainKeys = try keys.map { name -> Key in + var chord = try modifiers.map(Self.modifier) + var namesByCode: [CGKeyCode: String] = [:] + for name in keys { + let key: Key if name == "+" || name.lowercased() == "plus" { - modifierNames.append("shift") - return Key(keyCode: try Self.keyCode("="), flag: []) + guard keys.count == 1 else { + throw RequestParameters.invalid("For a multi-key chord, use = with an explicit shift modifier instead of \(name)") + } + chord.append(try Self.modifier("shift")) + key = Key(keyCode: try Self.keyCode("="), flag: []) + } else if let modifier = Self.namedModifier(name) { + key = modifier + } else { + key = Key(keyCode: try Self.keyCode(name), flag: []) } - if let modifier = Self.namedModifier(name) { return modifier } - return Key(keyCode: try Self.keyCode(name), flag: []) - } - guard Set(mainKeys.map(\.keyCode)).count == mainKeys.count else { - throw RequestParameters.invalid("A chord must contain distinct physical keys") + if let previous = namesByCode.updateValue(name, forKey: key.keyCode) { + throw RequestParameters.invalid("Keys '\(previous)' and '\(name)' name the same physical key") + } + chord.append(key) } var selected = Set() var flags: CGEventFlags = [] var events: [(down: CGEvent, up: CGEvent)] = [] let source = try Self.source() - for key in try modifierNames.map(Self.modifier) + mainKeys where selected.insert(key.keyCode).inserted { + for key in chord { + guard selected.insert(key.keyCode).inserted else { continue } let releasedFlags = flags flags.formUnion(key.flag) events.append(( @@ -243,7 +252,7 @@ final class KeyboardInput { case "m": return 46 case ".": return 47 case "`": return 50 - default: throw NativeFailure(code: "NATIVE_ERROR", message: "Unknown key name: \(key)") + default: throw RequestParameters.invalid("Unknown key name: \(key)") } } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index ef2b6dc101..0041e88b2a 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -37,13 +37,11 @@ struct RequestParameters: Sendable { } } func pressKeys() throws -> [String] { - if let name = values["key"]?.string { - guard !name.isEmpty else { throw Self.invalid("key must not be empty") } - return [name] + switch values["key"] { + case .string(let name) where !name.isEmpty: return [name] + case .array(let items) where !items.isEmpty: return try strings("key") + default: throw Self.invalid("key must be a nonempty string or a nonempty array of key names") } - let names = try strings("key") - guard !names.isEmpty else { throw Self.invalid("key must name at least one key") } - return names } func optionalString(_ key: String) throws -> String? { contains(key) ? try string(key) : nil } func optionalBoolean(_ key: String) throws -> Bool? { diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index aa6d201dcb..ce960cea7e 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -1006,7 +1006,8 @@ "minLength": 1 } } - ] + ], + "description": "One key name or distinct physical keys to press in order and release in reverse." }, "modifiers": { "type": "array", diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 95a94c97b6..f9c280a193 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -188,15 +188,14 @@ def main(): if not args.click_only: call("click", {**window, **point, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 26 and event.get("button") == 2 and event["shift"] for event in value["events"])) + count = len(state["events"]) + call("pressKey", {**owner, "key": ["w", "d"]}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) + chord = [(event["type"], event.get("keyCode")) for event in state["events"][count:]] + assert chord == [(10, 13), (10, 2), (11, 2), (11, 13)], chord call("drag", {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80, "toY": point["y"] + 20, "durationMs": 200, "steps": 10, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 27 and event.get("button") == 2 and event["shift"] for event in value["events"])) - call("pressKey", {**owner, "key": ["w", "d"]}) - expected_chord = [(10, 13), (10, 2), (11, 2), (11, 13)] - state = wait_for_state(state_file, lambda value: any( - event["type"] == 11 and event.get("keyCode") == 13 for event in value["events"])) - assert [(event["type"], event["keyCode"]) for event in state["events"] - if event.get("keyCode") in (13, 2)] == expected_chord, state["events"] call("pressKey", {**owner, "key": "KP_0"}) call("pressKey", {**owner, "key": "KP_Enter"}) state = wait_for_state(state_file, lambda value: {82, 76}.issubset({event.get("keyCode") for event in value["events"]})) @@ -207,7 +206,7 @@ def main(): (args.artifacts / "capabilities.png").write_bytes(base64.b64decode(shot["data"])) (args.artifacts / "state.json").write_text(json.dumps(state, ensure_ascii=False, indent=2)) print("PASS: click holds and cancellation/timeout/disconnect release" if args.click_only else - "PASS: stopped-app launch, Unicode selection, plain/HTML paste, middle/modifier drag, keypad identity and click holds") + "PASS: stopped-app launch, Unicode selection, plain/HTML paste, middle/modifier drag, overlapping W+D events, keypad identity and click holds") finally: if pid is None and state_file.exists(): pid = json.loads(state_file.read_text())["pid"] diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index ae98c891d6..6ca44cd59a 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -3,14 +3,19 @@ import CoreGraphics import Testing @testable import CuaNative -@Test func chordKeepsModifiersThroughBothLetterReleases() throws { +@Test(arguments: [ + (["w", "d"], ["shift"], [56, 13, 2, 2, 13, 56]), + (["shift", "w", "d"], [], [56, 13, 2, 2, 13, 56]), + (["a", "="], ["shift"], [56, 0, 24, 24, 0, 56]), +]) +func chordKeepsShiftThroughBothKeyReleases(_ keys: [String], _ modifiers: [String], _ codes: [Int64]) throws { var events: [CGEvent] = [] let input = KeyboardInput(post: { event, pid in #expect(pid == 42) events.append(event) }, textEventInterval: 0) - try input.pressKey(["w", "d"], modifiers: ["shift"], to: 42) - #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 13, 56]) + try input.pressKey(keys, modifiers: modifiers, to: 42) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == codes) #expect(events.map(\.type) == [.flagsChanged, .keyDown, .keyDown, .keyUp, .keyUp, .flagsChanged]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, true, false]) } @@ -29,8 +34,37 @@ func cancelledChordReleasesOnlyPressedKeys(_ cancelAfter: Int) { #expect(events.map(\.type) == Array(repeating: .keyDown, count: cancelAfter) + Array(repeating: .keyUp, count: cancelAfter)) } -@Test(arguments: [["w", "unknown"], ["w", "W"], ["Enter", "Return"]]) -func invalidChordPostsNoInput(_ keys: [String]) { +@Test(arguments: [ + (["w", "unknown"], "Unknown key name: unknown"), + (["w", "W"], "Keys 'w' and 'W' name the same physical key"), + (["Enter", "Return"], "Keys 'Enter' and 'Return' name the same physical key"), + (["a", "+"], "For a multi-key chord, use = with an explicit shift modifier instead of +"), + (["Plus", "w"], "For a multi-key chord, use = with an explicit shift modifier instead of Plus"), +]) +func invalidChordPostsNoInput(_ keys: [String], _ message: String) throws { let input = KeyboardInput(post: { _, _ in Issue.record("Invalid chord posted input") }, textEventInterval: 0) - #expect(throws: NativeFailure.self) { try input.pressKey(keys, modifiers: ["shift"], to: 42) } + do { + try input.pressKey(keys, modifiers: ["shift"], to: 42) + Issue.record("Invalid chord was accepted") + } catch let error as NativeFailure { + #expect(error.code == "INVALID_ARGUMENT") + #expect(error.message == message) + } +} + +@Test(arguments: ["+", "plus"]) +func plusAlonePressesShiftEquals(_ alias: String) throws { + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0) + try input.pressKey([alias], modifiers: [], to: 42) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 24, 24, 56]) + #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, false]) +} + +@Test func standaloneShiftSetsItsFlagOnlyWhileHeld() throws { + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0) + try input.pressKey(["shift"], modifiers: [], to: 42) + #expect(events.map(\.type) == [.flagsChanged, .flagsChanged]) + #expect(events.map { $0.flags.contains(.maskShift) } == [true, false]) } diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index 84a9fec849..85fa37aaf0 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -138,3 +138,15 @@ func rejectsMalformedApplicationIconPaths(_ value: String) throws { let request = try NativeRequest(data: Data("{\"id\":\"icons\",\"method\":\"applicationIcons\",\"params\":{\"paths\":\(value)}}".utf8)) #expect(throws: NativeFailure.self) { try RequestParameters(request).strings("paths") } } + +@Test func invalidPressKeyTypeNamesBothAcceptedForms() throws { + let request = try NativeRequest(data: Data(#"{"id":"call","method":"pressKey","params":{"key":7}}"#.utf8)) + let params = try RequestParameters(request) + do { + _ = try params.pressKeys() + Issue.record("Numeric key was admitted") + } catch let error as NativeFailure { + #expect(error.code == "INVALID_ARGUMENT") + #expect(error.message == "key must be a nonempty string or a nonempty array of key names") + } +} diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index f8779651a9..c7726f385b 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,6 +13,7 @@ const methodDetails = new Map([ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { + if (method === 'pressKey') return "- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed." const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index f3e530b7de..16fb39122a 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -27,6 +27,10 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('accessibility tree operations are available at app or window level') expect(PLATFORM_GUIDANCE).toContain('Simulated keyboard input is available at app level') expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') + const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) + expect(pressKey).toContain('key: string | string[]') + expect(pressKey).toContain("pressKey(['w', 'd']) presses W then D and releases D then W") + expect(pressKey).toContain("Packed strings such as 'w+d'") const hover = GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE', 'systemPointerHover']) expect(hover).toContain(term) const click = GUIDANCE.split('\n').find(line => line.startsWith('- click(')) @@ -89,7 +93,7 @@ it('preserves image formats and pointer modifier enums without restricting keybo for (const name of ['click', 'drag']) { expect(lines.find(line => line.startsWith(`- ${name}(`))).toContain("modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[]") } - expect(COMMON_GUIDANCE).toContain('pressKey(key: string | string[], modifiers?: string[])') + expect(COMMON_GUIDANCE).toContain('pressKey(key: string, modifiers?: string[])') expect(COMMON_GUIDANCE).toContain('Key and modifier names are platform-defined strings') }) @@ -130,7 +134,7 @@ it('documents facade initialization, emitted observations, and separate key argu expect(COMMON_GUIDANCE).toContain('host-provided bridge initialization once') expect(COMMON_GUIDANCE).toContain('not a preinstalled global') expect(COMMON_GUIDANCE).toContain('void await') - expect(COMMON_GUIDANCE).toContain("pressKey(['w', 'd']) presses W then D and releases D then W") + expect(COMMON_GUIDANCE).toContain('do not pack them into a chord string') expect(COMMON_GUIDANCE).toContain('perform a left-button double-click') }) diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 0d16bc4b02..8587d8c7d5 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,7 +21,7 @@ en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: e38d57709aa6d001 + en: 181158347d09c629 zh: 231b2dcaf826d386 /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index e6c0f0778f..9fb8f64eb7 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and de Provider startup capabilities are fixed at installation: platform, methods, app-level accessibility, keyboard scopes, browser support, and coordinate space. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges both layers for the model-visible result. The raw RPC remains a common operation representation rather than a capability inventory, so provider guidance states the actions its platform supports. -Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` holds the listed modifiers while pressing the requested keys in order and releasing them in reverse. For example, `pressKey(['w', 'd'])` holds W through the D keystroke; `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. +Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` holds the listed modifiers while pressing the requested keys in order and releasing them in reverse. For example, `pressKey(['w', 'd'])` holds W through the D keystroke. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. Platform providers import `CuaConfigFields` from `@deepseek-ai/dsh-cua/config` to extend the shared configuration. The root Host entry exports `installCua`, `CuaConfig`, and the Typert-discovered `CuaAccess` service; its `apply()` only marks the optional Client contribution. `/client` loads the permission UI through the existing module loader. Separate Host and Client compiler projects keep React, CSS, and browser registrations out of headless imports. `/api` owns the app/window API and its types; `/bridge`, `/native-client`, and `/protocol` retain runtime and platform consumers. `/types` exports only the named types required by generated Remote declarations. The Client uses package-local types. `/typert` supplies Host reflection and `/remote` supplies generated browser descriptors and codecs; permission authority remains on the Host. diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 0677be5433..745ccfe9be 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -43,6 +43,6 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.` diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 8488f32af3..42b545e66a 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -62,7 +62,10 @@ export const Request = z.discriminatedUnion('method', [ selectionType: z.enum(['text', 'cursor_before', 'cursor_after']).optional() }), operation('typeText', { ...app, windowId: id.optional(), text: z.string() }), operation('paste', { ...app, windowId: id.optional(), text: z.string(), format: z.enum(['text', 'html']).optional() }), - operation('pressKey', { ...app, windowId: id.optional(), key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]), modifiers: z.array(z.string()).optional() }), + operation('pressKey', { ...app, windowId: id.optional(), + key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]) + .describe('One key name or distinct physical keys to press in order and release in reverse.'), + modifiers: z.array(z.string()).optional() }), operation('sendKeyEvent', { ...app, windowId: id.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('scroll'), params: z.union([ z.object({ ...absoluteCoordinate, diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index 875418d805..da1c1eaf56 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -162,7 +162,7 @@ export interface CuaSurface { /** * Press the keys in order at the current focus, then release them in reverse order. * Rejects when the provider does not support keyboard input at this scope. - * @param key - One provider-defined key name or a nonempty array of distinct keys to hold together. + * @param key - One provider-defined key name or a nonempty array of distinct physical keys to hold together. * @param modifiers - Platform- or provider-defined modifier names held for this keystroke; omitted means none. * @returns Whether the provider successfully executed the requested operation. */ diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index 50fb329c07..c3d69e309c 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -12,6 +12,8 @@ const rejectedRequests: Array<{ reason: string; request: JsonValue }> = [ { reason: 'numeric element id', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: 0 } } }, { reason: 'coordinate click without a window', request: { method: 'click', params: { appHandle: 'app', x: 1, y: 2 } } }, { reason: 'mixed element and coordinate click', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: 23, x: 1, y: 2 } } }, + { reason: 'empty pressKey chord', request: { method: 'pressKey', params: { appHandle: 'app', key: [] } } }, + { reason: 'non-string pressKey chord member', request: { method: 'pressKey', params: { appHandle: 'app', key: ['w', 7] } } }, { reason: 'non-string pressKey modifier', request: { method: 'pressKey', params: { appHandle: 'app', key: 'a', modifiers: ['command', 7] } } }, { reason: 'sendKeyEvent modifiers', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a', direction: 'down', modifiers: [] } } }, { reason: 'sendKeyEvent without direction', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a' } } }, @@ -23,6 +25,11 @@ it.each(rejectedRequests)('rejects $reason at operation admission', ({ request } expect(Request.safeParse(request).success).toBe(false) }) +it('admits an ordered chord in a raw pressKey request', () => { + const request = { method: 'pressKey', params: { appHandle: 'app', key: ['w', 'd'] } } + expect(Request.parse(request)).toEqual(request) +}) + it('admits arbitrary provider-defined pressKey modifier names', () => { const request = { method: 'pressKey', params: { appHandle: 'app', key: 'PlatformKey', modifiers: ['platform-modifier', 'shift'] } } expect(Request.parse(request)).toEqual(request) diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index a39b9145d4..73107a5ee3 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -78,7 +78,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 8f608ec54e..3a94712d06 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -1045,7 +1045,8 @@ "minLength": 1 } } - ] + ], + "description": "One key name or distinct physical keys to press in order and release in reverse." }, "modifiers": { "type": "array", diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 017e5b103b..14f13a5a00 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -80,7 +80,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index ef58a12bd2..6e0914ac15 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -80,7 +80,7 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — press one key or hold distinct keys together. pressKey(['w', 'd']) presses W then D and releases D then W. Pass modifiers separately, as in pressKey('Tab', ['shift']). Key and modifier names are platform-defined strings. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From 89d374d5788c4822d86deed427d1db87c8483866 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 13:33:24 +0800 Subject: [PATCH 087/103] feat(cua-macos): hold physical keys for one run_code execution --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 4 +- ...026-11-05-cua-scoped-surfaces-and-input.md | 2 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 2 +- .../cua-native-platform/guide.i18n.yaml | 4 +- .../v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../cua-native-platform/guide.zh.md | 2 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 7 +- packages/experimental/cua-macos/README.zh.md | 7 +- .../cua-macos/native/README.i18n.yaml | 8 +- .../experimental/cua-macos/native/README.md | 4 +- .../cua-macos/native/README.zh.md | 4 +- .../native/Sources/CuaNative/AXWorker.swift | 25 ++++-- .../native/Sources/CuaNative/HeldKeys.swift | 84 +++++++++++++++++++ .../Sources/CuaNative/KeyboardInput.swift | 42 ++++++++-- .../CuaNative/NativeProtocol.generated.swift | 3 +- .../Sources/CuaNative/RequestAdmission.swift | 2 +- .../CuaNative/RequestCoordinator.swift | 4 +- .../Sources/CuaNative/RequestScheduler.swift | 1 + .../cua-macos/native/generate-protocol.ts | 1 + .../cua-macos/native/protocol.schema.json | 38 ++++++++- .../native/tests/capabilities_e2e.py | 16 ++++ .../tests/swift/KeyboardChordTests.swift | 22 +++++ .../experimental/cua-macos/src/guidance.ts | 3 +- .../experimental/cua-macos/src/held-keys.ts | 42 ++++++++++ packages/experimental/cua-macos/src/index.ts | 5 +- .../cua-macos/tests/guidance.spec.ts | 5 +- .../tests/provider-lifecycle.spec.ts | 84 +++++++++++++++++-- packages/experimental/cua/src/index.ts | 4 + .../experimental/cua/src/native-client.ts | 23 ++++- packages/experimental/cua/src/protocol.ts | 2 +- packages/experimental/cua/src/types.ts | 2 +- .../cua/tests/native-client.spec.ts | 12 +++ snapshots/session/cua-native/session.v4.jsonl | 2 +- .../cua-native/system-prompt.expected.md | 3 +- .../session/cua-ptc/system-prompt.expected.md | 3 +- .../system-prompt.expected.md | 3 +- 37 files changed, 428 insertions(+), 53 deletions(-) create mode 100644 packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift create mode 100644 packages/experimental/cua-macos/src/held-keys.ts diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index adad612610..716f07d599 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -15,5 +15,5 @@ en: 2113f17a49e16670 zh: 1df04d9736a3ad4f /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: - en: 5c6ec60b77f1bff0 - zh: e1ae568ef3501b7b + en: c4b12ca80865e670 + zh: 396426fad0105eaa diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 655172fb19..6b4fe604d5 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -34,6 +34,6 @@ Within one API instance, the object facade keeps one current accessibility snaps Element IDs belong to the application's current accessibility snapshot. Reading one window replaces the facade’s current snapshot for that application, so callers observe again and confirm the IDs they use. The new read does not guarantee that an old string is rejected or that an ID changes; callers must not assume an older ID still identifies the same control. Pointer input and screenshots require an explicit window object; callers enumerate windows first. -Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, because the API never sends the opposite event. Keyboard modifier names are provider-defined, so the same string may have different support across providers. +Keyboard behavior follows the provider's supported scopes. A caller that uses `sendKeyEvent` owns the down/up pairing, during execution. macOS releases that run’s remaining keys when the program ends or the user pauses it. Keyboard modifier names are provider-defined, so the same string may have different support across providers. Provider guidance owns the list of supported actions. Adding a method to the shared schema does not claim that every provider implements it, and the merged `getCapabilities` result remains the runtime source for permissions and session lock. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index 495ba2d399..d03c3b4723 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -34,6 +34,6 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 元素 ID 属于应用当前的辅助功能快照。读取一个窗口会替换门面对该应用的当前快照,因此调用方需要重新观察并确认要使用的 ID。新的读取不保证拒绝旧字符串,也不保证 ID 会改变;调用方不得假定旧 ID 仍指向同一控件。指针输入和截图都要求显式的窗口对象;调用方先枚举窗口。 -键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,因为 API 从不发送相反事件。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 +键盘行为遵循 provider 支持的作用域。使用 `sendKeyEvent` 的调用方负责按下与抬起的配对,在 macOS 上,程序结束或用户暂停时会释放本次执行仍按着的键。键盘修饰键名称由 provider 定义,同一字符串在不同 provider 上可能支持不同。 Provider 指导文本负责支持动作的清单。把方法加入共享 schema 并不表示每个 provider 都已实现它;合并后的 `getCapabilities` 结果仍是权限和会话锁定状态的运行时来源。 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index c3d5791588..09553adc47 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: 4cf8b18af0d2bb79 - zh: 7f490fd9785deffe + en: a0640d4cd1f2e84e + zh: be8d5b5f9d14caf8 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 363e627e66..8f5b092012 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -18,6 +18,6 @@ Providers supply startup capabilities alongside their platform guidance. The nat 1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. 2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. -4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`: macOS supports complete keystrokes and rejects directional events with `NOT_IMPLEMENTED`. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. 5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. 6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index 272e4a96d4..7580de0836 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -18,6 +18,6 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 -4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。macOS 支持完整按键,单独发送按下或松开事件会返回 `NOT_IMPLEMENTED`。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 6a38002c4f..1abb4f6399 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 24ea893846cf0914 - zh: dca284e8e589274d + en: f4206e2cb725c917 + zh: 37f0b04e9e74c193 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 60d57c749d..042cc4fa94 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -79,7 +79,9 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. `getApp` returns the `appHandle` used by every app-targeted operation, and `app.getWindow(windowId)` returns the object that owns screenshots and pointer input. -`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct physical keys. Aliases such as `Enter` and `Return` identify the same key. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass held modifiers separately, as in `pressKey('Tab', ['shift'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. In a multi-key chord, use `=` and pass Shift explicitly to apply it to the whole chord. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. On macOS, use `pressKey` on the App object. The shared `sendKeyEvent` operation returns `NOT_IMPLEMENTED` on this provider. +`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct physical keys. Aliases such as `Enter` and `Return` identify the same key. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass held modifiers separately, as in `pressKey('Tab', ['shift'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. In a multi-key chord, use `=` and pass Shift explicitly to apply it to the whole chord. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. + +For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. Each successful down remains active across subsequent tool calls in that execution. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -221,7 +223,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index cadefe0dd6..0f6f4dad51 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -79,7 +79,9 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。`getApp` 返回每个面向应用的操作所需的 `appHandle`,`app.getWindow(windowId)` 返回负责截图和指针输入的对象。 -`pressKey(key, modifiers?)` 接受单个键名或由不同物理键组成的非空数组。`Enter` 和 `Return` 等别名指向同一个物理键。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。需要全程按住的修饰键单独传入,例如 `pressKey('Tab', ['shift'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。单独传入 `+` 或 `plus` 会发送 Shift 和等号。在多键组合中请使用 `=`,需要全程按住 Shift 时将其列入修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。在 macOS 上,通过 App 对象调用 `pressKey`。调用共享接口 `sendKeyEvent` 会收到 `NOT_IMPLEMENTED`。 +`pressKey(key, modifiers?)` 接受单个键名或由不同物理键组成的非空数组。`Enter` 和 `Return` 等别名指向同一个物理键。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。需要全程按住的修饰键单独传入,例如 `pressKey('Tab', ['shift'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。单独传入 `+` 或 `plus` 会发送 Shift 和等号。在多键组合中请使用 `=`,需要全程按住 Shift 时将其列入修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 + +长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。按下成功后,在同一次执行中调用其他工具时该键仍保持按下。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 向每个键原先的接收进程松开该次执行仍按着的键。后续执行不能释放前一次执行的键。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -221,7 +223,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 7382f3006b..2b78969668 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -18,11 +18,11 @@ en: 1435672513328c05 zh: 11e7a1e672410c10 /dsh-cua-native-helper/request-protocol: - en: 88a59904ca4ebedc - zh: 14f2b666d7382145 + en: 2a69d89b7fc95998 + zh: 084575bb31fb40dd /dsh-cua-native-helper/observation-and-input: - en: 51a70780a0672272 - zh: e7ca17dd40b887aa + en: 851614a21ebfeb65 + zh: ff868b14dc77adb8 /dsh-cua-native-helper/verification: en: ade5a2ccd3aeb1b4 zh: 74c2b0bcb23fc4bc diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 2437c220a4..b3074d6ce9 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -78,7 +78,7 @@ Successful `activate` returns `dispatched` and `foregroundChanged`. A known chan | `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`. `windowId` is null for an app-wide observation. Elements include the opaque string `elementId`, role, title, value, description, identifier, bounds, actions, and enabled state. Element bounds are null or [x, y, width, height] in screen points; window input uses local points. These structured element diagnostics are retained by native checks and omitted by the model tool projection. Unavailable optional descriptive properties are null, and an unavailable action list is empty; permission, communication and window-discovery failures still reject the observation. | | `listActions` | Provider-defined action names for one element as a string array; an element may advertise none. | | `show` | `{dispatched: boolean, windowId, foregroundChanged}` records restoration dispatch. `windowId` is null when no window was selected; `foregroundChanged` is null when the sampled observation was unavailable. | -| `invoke`, `performAction`, `mouseMove`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: boolean}` records native dispatch; `invoke` reports false when no applicable default action exists. `mouseMove` also reports `hoverRoute` and `systemPointerMoved`. Read fresh state to verify the intended application change. | +| `invoke`, `performAction`, `mouseMove`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `sendKeyEvent`, `scroll`, `drag` | `{dispatched: boolean}` records native dispatch; `invoke` reports false when no applicable default action exists. `mouseMove` also reports `hoverRoute` and `systemPointerMoved`. Read fresh state to verify the intended application change. | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`. PNG pixel dimensions can differ from window point dimensions on Retina displays. | Every app-targeted operation requires `appHandle` from `getApp` in the same helper. The helper pins the PID and kernel process start time, and invalidates the handle and all of its snapshots after process exit or PID reuse. Calling `getApp` can acquire the replacement process without reactivating old handles. A random per-helper namespace prevents handles from a terminated helper matching those of its replacement. Repeated acquisition of the same live process shares its handle. A post-launch inspection failure invalidates the pending handle and preserves the original error. It does not terminate a process already started; launchApp cannot reuse the failed handle. @@ -105,6 +105,8 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses its modifiers followed by the requested keys in order, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. +The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. Explicit up and cleanup verify the original process identity. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. + The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. Host-only permission controls are `permissionStatus {}`, `requestPermission` and `openPermissionSettings {permission}`, where permission is `accessibility` or `screenRecording`. Requests carry localized `instruction`, `backLabel`, `finderLabel`, `unavailableMessage`, `settingsMessage`, and an integer `pollIntervalMs` of 100–2147483647. The native guide substitutes its application name for `{application}`. Status reports permission observations, process diagnostics, and `launchApplication` metadata. These operations remain absent from the model tool and `getCapabilities.methods`. The helper dynamically resolves `responsibility_get_pid_responsible_for_pid` with the signature used by [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm), capturing the responsible bundle before readiness and falling back to its own bundle when unavailable. Parent paths do not determine authorization ownership. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 1224e0e6db..6035ffaee2 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -78,7 +78,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 | `getState` | `{appHandle, windowId, focusedWindowId, snapshotId, tree, elements, windows, truncated}`。应用级观察的 `windowId` 为 null。元素包含不透明字符串 `elementId`、role、title、value、description、identifier、bounds、actions 和 enabled 状态。元素边界为 null 或屏幕 point 单位的 [x, y, width, height],窗口输入使用局部 point。这些结构化元素诊断供原生检查保留,模型工具投影会移除它们。不可用的可选描述属性为 null,无法取得的动作列表为空;权限、通信和窗口发现失败仍会拒绝观察。 | | `listActions` | 一个元素由 provider 定义的动作名数组;元素可以不声明任何动作。 | | `show` | `{dispatched: boolean, windowId, foregroundChanged}` 记录恢复分派。未选中窗口时 `windowId` 为 null;无法取得采样观察时 `foregroundChanged` 为 null。 | -| `invoke`, `performAction`, `mouseMove`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `scroll`, `drag` | `{dispatched: boolean}` 记录原生分派;`invoke` 在没有可用的默认动作时返回 false。`mouseMove` 还报告 `hoverRoute` 和 `systemPointerMoved`。需要读取新状态以核实预期的应用变化。 | +| `invoke`, `performAction`, `mouseMove`, `click`, `setValue`, `selectText`, `typeText`, `paste`, `pressKey`, `sendKeyEvent`, `scroll`, `drag` | `{dispatched: boolean}` 记录原生分派;`invoke` 在没有可用的默认动作时返回 false。`mouseMove` 还报告 `hoverRoute` 和 `systemPointerMoved`。需要读取新状态以核实预期的应用变化。 | | `screenshot` | `{mimeType: "image/png", data, pixelWidth, pixelHeight, bounds, coordinateSpace: "window-points", windowId}`。Retina 显示器上 PNG 像素尺寸可能不同于窗口 point 尺寸。 | 每个面向应用的操作都要求使用同一 helper 的 `getApp` 返回的 `appHandle`。helper 固定 PID 和内核进程启动时间,进程退出或 PID 被复用后使句柄及其全部快照失效。再次调用 `getApp` 可取得替代进程,不会重新激活旧句柄。随机的 helper 命名空间防止已终止 helper 的句柄与替代实例重合。重复获取同一存活进程会共享句柄。启动后检查失败会使待启动句柄失效,并保留原错误;已经启动的进程不会被终止,launchApp 也不能复用失败的句柄。 @@ -105,6 +105,8 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和指定按键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 +宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。显式松键或执行结束时会核对原进程身份。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 + 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 仅供 Host 使用的权限操作为 `permissionStatus {}`、`requestPermission` 和 `openPermissionSettings {permission}`,其中 permission 为 `accessibility` 或 `screenRecording`。请求携带本地化的 `instruction`、`backLabel`、`finderLabel`、`unavailableMessage`、`settingsMessage`,以及 100–2147483647 的整数 `pollIntervalMs`。原生引导将 `{application}` 替换为自身应用名。状态返回权限观测、进程诊断和 `launchApplication` 信息。这些操作不出现在模型工具及 `getCapabilities.methods` 中。helper 动态解析 `responsibility_get_pid_responsible_for_pid`,函数签名与 [Chromium](https://chromium.googlesource.com/chromium/src/+/refs/tags/134.0.6998.28/base/process/process_info_mac.mm) 一致,在报告就绪前记录责任 bundle,无法获取时使用自身 bundle。父进程路径不决定授权归属。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index da1afe5a3d..80d820d0f1 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -81,13 +81,15 @@ actor AXWorker { private let systemPointerHover: Bool? private let sessionState: @Sendable () -> Bool? private var access: AXAccess? + private let heldKeys: HeldKeys private var keyboard: KeyboardInput? private var pointer: WindowPointerInput? private var hovers: [String: AXHover] = [:] private var closed = false - init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, systemPointerHover: Bool? = nil, + init(cancellation: CancellationLatch, axTimeout: Float, textEventInterval: Double, maxClickHoldMs: Int, systemPointerHover: Bool? = nil, heldKeys: HeldKeys = HeldKeys(), sessionState: @escaping @Sendable () -> Bool? = NativePlatform.sessionLocked) { + self.heldKeys = heldKeys self.cancellation = cancellation self.axTimeout = axTimeout self.textEventInterval = textEventInterval @@ -118,7 +120,7 @@ actor AXWorker { if let keyboard, let pointer { return (keyboard, pointer) } let poster = PIDEventPoster() let latch = cancellation - let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, checkCancellation: { try latch.check() }) + let key = KeyboardInput(post: poster.post, textEventInterval: textEventInterval, held: heldKeys, checkCancellation: { try latch.check() }) let mouse = WindowPointerInput(poster: poster, checkCancellation: { try latch.check() }) keyboard = key; pointer = mouse return (key, mouse) @@ -208,8 +210,13 @@ actor AXWorker { trace: ScreenshotTrace? = nil) async throws -> DriverOutcome { try cancellation.check() guard !closed else { throw NativeFailure(code: "NATIVE_CLOSED", message: "Helper is closing") } - if method == "sendKeyEvent" { - throw NativeFailure(code: "NOT_IMPLEMENTED", message: "sendKeyEvent is not implemented on current platform.") + if method == "releaseHeldKeys" { + try keyboard?.releaseHeldKeys(run: params.string("runId")) + return .result(Self.actionResult) + } + if method == "sendKeyEvent", try params.string("direction") == "up" { + let dispatched = try inputs().0.keyUp(params.string("key"), app: params.string("appHandle"), run: params.string("runId")) + return .result(.object(["dispatched": .bool(dispatched)])) } let locked = observeSession() if method == "getCapabilities" { @@ -331,6 +338,9 @@ actor AXWorker { maxBytes: try params.integer("maxClipboardBytes", in: 1024...Int.max), readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)), maxElements: try params.integer("maxElements", in: 1...10000), maxDepth: try params.integer("maxDepth", in: 1...100))) + case "sendKeyEvent": + let recipient = try ax().keyboardRecipient(identity, catalog: catalog) + try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId"), recipient: recipient) case "typeText", "pressKey": let recipient = try ax().keyboardRecipient(identity, catalog: catalog) try NativePlatform.verify(recipient) @@ -496,5 +506,10 @@ actor AXWorker { static func mouseMoveResult(route: String, pointerMoved: Bool) -> JSONValue { .object(["dispatched": .bool(true), "hoverRoute": .string(route), "systemPointerMoved": .bool(pointerMoved)]) } - func shutdown() { closed = true; snapshots.removeAll(); observedWindowBounds.removeAll(); targets.removeAll(); hovers.removeAll(); access = nil; keyboard = nil; pointer = nil } + func shutdown() { + do { try keyboard?.releaseHeldKeys() } + catch { fputs("Could not release held keys on disconnect: \(error)\n", stderr) } + closed = true; snapshots.removeAll(); observedWindowBounds.removeAll(); targets.removeAll(); hovers.removeAll() + access = nil; keyboard = nil; pointer = nil + } } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift new file mode 100644 index 0000000000..47c34fbe2a --- /dev/null +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift @@ -0,0 +1,84 @@ +// All connections to the shared helper deliver to the same desktop processes. +import CoreGraphics +import Foundation + +/// The lock covers both the held-key records and their corresponding PID-targeted event posts. +/// Shutdown may release a connection's keys outside the ordinary request scheduler. +final class HeldKeys: @unchecked Sendable { + struct Owner: Equatable { + let connection: UUID + let run: String + let app: String + } + + private struct Press { + let owner: Owner + let recipient: ProcessIdentity + let code: CGKeyCode + let flag: CGEventFlags + let up: CGEvent + } + + private let lock = NSLock() + private var pressed: [Press] = [] + + func snapshot(pid: Int32) -> [CGKeyCode: CGEventFlags] { + lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.recipient.pid == pid }.map { ($0.code, $0.flag) }) } + } + + func down(owner: Owner, recipient: ProcessIdentity, code: CGKeyCode, flag: CGEventFlags, + down: CGEvent, up: CGEvent, post: (CGEvent, Int32) -> Void) throws { + try lock.withLock { + guard !pressed.contains(where: { $0.code == code && ($0.owner == owner || $0.recipient.pid == recipient.pid) }) else { + throw RequestParameters.invalid("Key is already held for this target") + } + pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up)) + down.flags = flags(for: recipient) + post(down, recipient.pid) + } + } + + private func flags(for recipient: ProcessIdentity) -> CGEventFlags { + pressed.reduce(into: CGEventFlags()) { if $1.recipient == recipient { $0.formUnion($1.flag) } } + } + + /// An up always targets the process selected at down. Never post to a recycled PID. + private func release(at index: Int, post: (CGEvent, Int32) -> Void) throws -> Bool { + let key = pressed[index] + do { try NativePlatform.verify(key.recipient) } + catch let error as NativeFailure where error.code == "STALE_APP" || error.code == "APP_UNAVAILABLE" { + pressed.remove(at: index) + return false + } + pressed.remove(at: index) + key.up.flags = flags(for: key.recipient) + post(key.up, key.recipient.pid) + return true + } + + func up(owner: Owner, code: CGKeyCode, post: (CGEvent, Int32) -> Void) throws -> Bool { + try lock.withLock { + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { + throw RequestParameters.invalid("This run has not pressed that key for this application") + } + return try release(at: index, post: post) + } + } + + func release(connection: UUID, run: String?, post: (CGEvent, Int32) -> Void) throws { + try lock.withLock { + defer { + // A closed connection cannot retry an unverifiable recipient. + if run == nil { pressed.removeAll { $0.owner.connection == connection } } + } + var firstError: Error? + for index in pressed.indices.reversed() { + let owner = pressed[index].owner + guard owner.connection == connection, run == nil || owner.run == run else { continue } + do { _ = try release(at: index, post: post) } + catch { firstError = firstError ?? error } + } + if let firstError { throw firstError } + } + } +} diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index 3511256457..91572fbd5f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -9,16 +9,39 @@ final class KeyboardInput { let flag: CGEventFlags } + private let connection = UUID() + private let held: HeldKeys private let post: (CGEvent, Int32) -> Void private let textEventInterval: Double private let checkCancellation: @Sendable () throws -> Void - init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, checkCancellation: @escaping @Sendable () throws -> Void = {}) { + init(post: @escaping (CGEvent, Int32) -> Void, textEventInterval: Double, held: HeldKeys = HeldKeys(), checkCancellation: @escaping @Sendable () throws -> Void = {}) { + self.held = held self.post = post self.textEventInterval = textEventInterval self.checkCancellation = checkCancellation } + func keyDown(_ name: String, app: String, run: String, recipient: ProcessIdentity) throws { + let modifier = Self.namedModifier(name) + let code = try Self.keyCode(name) + let source = try Self.source() + let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) + let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) + try checkCancellation() + try NativePlatform.verify(recipient) + try held.down(owner: .init(connection: connection, run: run, app: app), recipient: recipient, + code: code, flag: modifier?.flag ?? [], down: down, up: up, post: post) + } + + func keyUp(_ name: String, app: String, run: String) throws -> Bool { + try held.up(owner: .init(connection: connection, run: run, app: app), code: Self.keyCode(name), post: post) + } + + func releaseHeldKeys(run: String? = nil) throws { + try held.release(connection: connection, run: run, post: post) + } + /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. func pressKey(_ keys: [String], modifiers: [String], to pid: Int32) throws { try checkCancellation() @@ -42,8 +65,12 @@ final class KeyboardInput { } chord.append(key) } - var selected = Set() - var flags: CGEventFlags = [] + let alreadyHeld = held.snapshot(pid: pid) + guard namesByCode.keys.allSatisfy({ alreadyHeld[$0] == nil }) else { + throw RequestParameters.invalid("Release the held key before using it in pressKey") + } + var selected = Set(alreadyHeld.keys) + var flags = alreadyHeld.values.reduce(CGEventFlags()) { $0.union($1) } var events: [(down: CGEvent, up: CGEvent)] = [] let source = try Self.source() for key in chord { @@ -77,6 +104,8 @@ final class KeyboardInput { func typeText(_ text: String, to pid: Int32) throws { try checkCancellation() let source = try Self.source() + let alreadyHeld = held.snapshot(pid: pid) + let flags = alreadyHeld.values.reduce(CGEventFlags()) { $0.union($1) } for scalar in text.replacingOccurrences(of: "\r\n", with: "\n").unicodeScalars { try checkCancellation() let code: CGKeyCode @@ -85,8 +114,11 @@ final class KeyboardInput { case 9: code = try Self.keyCode("Tab") default: code = 0 } - let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) - let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) + guard alreadyHeld[code] == nil else { + throw RequestParameters.invalid("Release the held physical key before typing text with its key code") + } + let down = try Self.keyEvent(source: source, code: code, down: true, flags: flags) + let up = try Self.keyEvent(source: source, code: code, down: false, flags: flags) if code == 0 { let units = Array(String(scalar).utf16) units.withUnsafeBufferPointer { buffer in diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift index 0da4e5cb96..57f20c732f 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/NativeProtocol.generated.swift @@ -20,11 +20,12 @@ enum NativeProtocol { "performAction": ["action", "appHandle", "argument", "elementId", "snapshotId", "windowId"], "permissionStatus": [], "pressKey": ["appHandle", "key", "modifiers", "windowId"], + "releaseHeldKeys": ["runId"], "requestPermission": ["backLabel", "finderLabel", "instruction", "permission", "pollIntervalMs", "settingsMessage", "unavailableMessage"], "screenshot": ["appHandle", "windowId"], "scroll": ["appHandle", "deltaLinesX", "deltaLinesY", "snapshotId", "windowId", "x", "y"], "selectText": ["appHandle", "elementId", "prefix", "selectionType", "snapshotId", "suffix", "text", "windowId"], - "sendKeyEvent": ["appHandle", "direction", "key", "windowId"], + "sendKeyEvent": ["appHandle", "direction", "key", "runId", "windowId"], "setValue": ["appHandle", "elementId", "snapshotId", "value", "windowId"], "show": ["appHandle", "windowId"], "typeText": ["appHandle", "text", "windowId"], diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 0041e88b2a..6b69122d99 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -7,7 +7,7 @@ struct RequestParameters: Sendable { init(_ request: NativeRequest) throws { guard let values = request.params.object else { throw Self.invalid("params must be an object") } guard let allowed = Self.fields[request.method] else { throw NativeFailure(code: "UNSUPPORTED", message: "Unsupported native operation: \(request.method)") } - if ["typeText", "pressKey", "paste"].contains(request.method), values["windowId"] != nil { + if ["typeText", "pressKey", "sendKeyEvent", "paste"].contains(request.method), values["windowId"] != nil { throw Self.invalid("macOS keyboard input follows application focus; use the App object") } guard Set(values.keys).isSubset(of: allowed) else { throw Self.invalid("Unknown operation parameter") } diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift index 000a69e848..737d560720 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestCoordinator.swift @@ -43,7 +43,7 @@ import Darwin self.onFatal = onFatal worker = AXWorker(cancellation: cancellation, axTimeout: configuration.axTimeoutSeconds, textEventInterval: configuration.textEventIntervalSeconds, maxClickHoldMs: configuration.maxClickHoldMs, - systemPointerHover: configuration.systemPointerHover) + systemPointerHover: configuration.systemPointerHover, heldKeys: scheduler.heldKeys) input = JSONLInput(limit: configuration.maxRequestBytes, cancellation: cancellation, channel: channel) self.writer = writer } @@ -166,7 +166,7 @@ import Darwin let params = try RequestParameters(request) try cancellation.check() if request.method == "screenshot" { try capture.requireAvailable() } - let requiresCatalog = ["getApp", "listApps", "findApps", "typeText", "pressKey", "click"].contains(request.method) + let requiresCatalog = ["getApp", "listApps", "findApps", "typeText", "pressKey", "sendKeyEvent", "click"].contains(request.method) let catalog = requiresCatalog ? ApplicationCatalog.snapshot() : ApplicationCatalogSnapshot(applications: [], frontPID: nil) let result: JSONValue if request.method == "permissionStatus" { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift index 54671b12d4..83807c8468 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestScheduler.swift @@ -7,6 +7,7 @@ import Dispatch let id: UUID let continuation: CheckedContinuation } + let heldKeys = HeldKeys() private var owner: UUID? private var waiting: [Waiting] = [] diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 398999cc2c..29ccc58344 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -10,6 +10,7 @@ import { PermissionGuideParameters, PermissionSettingsParameters } from '../src/ */ export function renderNativeProtocol(): { json: string; swift: string } { const { fields, enums, json } = nativeProtocol({ + sendKeyEvent: z.object({ runId: z.string().min(1) }), mouseMove: z.object({ allowSystemPointer: z.boolean().optional() }), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, }) diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index ce960cea7e..f8a9824752 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -1062,12 +1062,17 @@ "down", "up" ] + }, + "runId": { + "type": "string", + "minLength": 1 } }, "required": [ "appHandle", "key", - "direction" + "direction", + "runId" ], "additionalProperties": false } @@ -1304,6 +1309,37 @@ ], "additionalProperties": false }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "releaseHeldKeys" + }, + "params": { + "type": "object", + "properties": { + "runId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "runId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false + }, { "type": "object", "properties": { diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index f9c280a193..432f70e81f 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -193,6 +193,22 @@ def main(): state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) chord = [(event["type"], event.get("keyCode")) for event in state["events"][count:]] assert chord == [(10, 13), (10, 2), (11, 2), (11, 13)], chord + count = len(state["events"]) + def key(name, direction): + call("sendKeyEvent", {**owner, "runId": "held-input", "key": name, "direction": direction}) + key("w", "down") + key("d", "down") + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 2) + call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) + time.sleep(2) + key("d", "up") + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 3) + held = state["events"][count:] + assert [(event["type"], event["keyCode"]) for event in held] == [(10, 13), (10, 2), (11, 2)], held + assert held[2]["timestamp"] - held[1]["timestamp"] >= 2, held + call("releaseHeldKeys", {"runId": "held-input"}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) + assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] call("drag", {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80, "toY": point["y"] + 20, "durationMs": 200, "steps": 10, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 27 and event.get("button") == 2 and event["shift"] for event in value["events"])) diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index 6ca44cd59a..52cae6911e 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -1,5 +1,6 @@ // Observe the actual CoreGraphics events without sending keyboard input to the desktop. import CoreGraphics +import Darwin import Testing @testable import CuaNative @@ -68,3 +69,24 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { #expect(events.map(\.type) == [.flagsChanged, .flagsChanged]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, false]) } + +@Test func directionalReleaseUsesOriginalRecipientAndPreservesOtherRuns() throws { + let target = try NativePlatform.identity(getpid()) + let held = HeldKeys() + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, pid in + #expect(pid == target.pid) + events.append(event) + }, textEventInterval: 0, held: held) + try input.keyDown("shift", app: "editor", run: "one", recipient: target) + try input.keyDown("w", app: "editor", run: "two", recipient: target) + #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: target) } + #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two") } + #expect(throws: NativeFailure.self) { try input.pressKey(["w"], modifiers: [], to: target.pid) } + try input.pressKey(["d"], modifiers: ["shift"], to: target.pid) + try input.releaseHeldKeys(run: "one") + #expect(try input.keyUp("w", app: "editor", run: "two")) + try input.releaseHeldKeys(run: "two") + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 56, 13]) + #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, false, false]) +} diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index c7726f385b..e750c4068b 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,7 +13,8 @@ const methodDetails = new Map([ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { - if (method === 'pressKey') return "- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed." + if (method === 'pressKey') return `- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/packages/experimental/cua-macos/src/held-keys.ts b/packages/experimental/cua-macos/src/held-keys.ts new file mode 100644 index 0000000000..30c1311da8 --- /dev/null +++ b/packages/experimental/cua-macos/src/held-keys.ts @@ -0,0 +1,42 @@ +/** Directional input belongs to the enclosing run_code, including while its worker calls other tools. */ +import { randomUUID } from 'node:crypto' +import type { Context } from '@deepseek-ai/cordis' +import type { CuaBackend } from '@deepseek-ai/dsh-cua' +import { NativeError, type NativeClient } from '@deepseek-ai/dsh-cua/native-client' +import { RUN_CODE_NAME, type ToolExecutionToken } from '@deepseek-ai/dsh-tools' + +/** + * Keep native key ownership alive until its program returns, throws, or is interrupted. + * @param ctx - Provider scope owning the tool execution listener. + * @returns Handler for authorized directional keyboard requests. + */ +export function installHeldKeys(ctx: Context): NonNullable { + const runs = new Map() + ctx.on('tools/execute', async (execution, next) => { + if (execution.name !== RUN_CODE_NAME) return next() + const run: { id: string; client?: NativeClient } = { id: randomUUID() } + runs.set(execution.token, run) + let cleanup: Promise | undefined + const release = () => { + runs.delete(execution.token) + if (run.client) cleanup ??= run.client.requestCleanup('releaseHeldKeys', { runId: run.id }) + return cleanup + } + // Pause may arrive while an unrelated subtool is still settling. + const onAbort = () => { void release()?.catch(() => undefined) } + execution.signal.addEventListener('abort', onAbort, { once: true }) + try { + return await next() + } finally { + execution.signal.removeEventListener('abort', onAbort) + await release() + } + }) + return (client, params, execution) => { + const run = execution.parent && runs.get(execution.parent) + if (!run) throw new NativeError('INVALID_ARGUMENT', 'Use sendKeyEvent inside an active run_code execution') + if (run.client && run.client !== client) throw new NativeError('NATIVE_CLOSED', 'The keyboard connection changed; start a new run_code') + run.client = client + return client.request('sendKeyEvent', { ...params, runId: run.id }, execution.signal, execution.callId) + } +} diff --git a/packages/experimental/cua-macos/src/index.ts b/packages/experimental/cua-macos/src/index.ts index 4b07e9c8b7..8c089c9f8e 100644 --- a/packages/experimental/cua-macos/src/index.ts +++ b/packages/experimental/cua-macos/src/index.ts @@ -9,6 +9,7 @@ import { CuaConfigFields } from '@deepseek-ai/dsh-cua/config' import { createPermissionParameters } from './permission-guide.ts' import { nativeHostArchitecture, prepareNativeExecutable, type SourceSigning } from './native-build.ts' import { createSharedNativeChannel } from './shared-native.ts' +import { installHeldKeys } from './held-keys.ts' import { GUIDANCE } from './guidance.ts' export { GUIDANCE } from './guidance.ts' @@ -17,7 +18,7 @@ const CAPABILITIES: CuaStartupCapabilities = { methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', - 'selectText', 'setValue', 'show', 'typeText', + 'selectText', 'sendKeyEvent', 'setValue', 'show', 'typeText', ], appLevelAccessibility: true, keyboard: ['app'], @@ -65,7 +66,7 @@ export const Config = Schema.object({ */ export async function apply(ctx: Context, config: Config): Promise { const createChannel: NativeChannelFactory = (owner, native) => createSharedNativeChannel(owner, native, config.systemPointerHover) - const backend = { createChannel, guidance: GUIDANCE, capabilities: CAPABILITIES, + const backend = { createChannel, sendKeyEvent: installHeldKeys(ctx), guidance: GUIDANCE, capabilities: CAPABILITIES, permissionParameters: createPermissionParameters(config.permissionPollIntervalMs) } if (config.helperPath !== undefined) { if (!isAbsolute(config.helperPath)) throw new Error('dsh-cua helperPath must be absolute') diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 16fb39122a..54322e2316 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -28,6 +28,9 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(PLATFORM_GUIDANCE).toContain('Simulated keyboard input is available at app level') expect(PLATFORM_GUIDANCE).toContain('Simulated mouse input is available at window level') const pressKey = GUIDANCE.split('\n').find(line => line.startsWith('- pressKey(')) + expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") + expect(GUIDANCE).toContain('returns, throws, or the user pauses') + expect(COMMON_GUIDANCE).not.toContain('sendKeyEvent(') expect(pressKey).toContain('key: string | string[]') expect(pressKey).toContain("pressKey(['w', 'd']) presses W then D and releases D then W") expect(pressKey).toContain("Packed strings such as 'w+d'") @@ -139,5 +142,5 @@ it('documents facade initialization, emitted observations, and separate key argu }) it('omits stale names and unavailable platform operations', () => { - for (const stale of ['getAXState', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'sendKeyEvent', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) + for (const stale of ['getAXState', 'disableDiffing', 'performSecondaryAction', 'hover(', 'keyChord', 'window.typeText', 'window.pressKey', 'elementIndex', 'verified: false', 'browser tabs', 'not implemented']) expect(GUIDANCE).not.toContain(stale) }) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 48b9eb99e3..194f7244fd 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -1,5 +1,5 @@ /** Native helper replacement is synchronized with Agent and provider disposal. */ -import { executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' +import { executeModelToolFixture, executeToolFixture } from '@deepseek-ai/dsh-tool-testkit' import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, resolve } from 'node:path' @@ -28,6 +28,7 @@ import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' import { LlmAdapter, ToolCallId, type LlmResolvedModelInfo, type StreamChunk } from '@deepseek-ai/dsh-llm' import { SessionId } from '@deepseek-ai/dsh-session' import Subprocess from '@deepseek-ai/dsh-subprocess' +import SubprocessLocal from '@deepseek-ai/dsh-subprocess-local' import { expect, it, onTestFinished, vi } from 'vitest' import sharp from 'sharp' import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' @@ -38,6 +39,7 @@ import type { NativeBuildSpec } from '../src/native-build.ts' const native = vi.hoisted(() => ({ prepare: vi.fn<(spec: NativeBuildSpec) => Promise>(), architecture: vi.fn(() => 'arm64' as const), + cleanup: vi.fn(), request: vi.fn(), dispose: vi.fn(), instances: [] as Array<{ disposed: boolean }>, reportDiagnostic: undefined as ((message: string) => void) | undefined, })) @@ -54,6 +56,7 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ native.reportDiagnostic = args[3] native.instances.push(this) } + requestCleanup = native.cleanup request = native.request invalidate() { this.disposed = true } async dispose() { this.disposed = true; await native.dispose() } @@ -110,19 +113,25 @@ class ImageAdapter extends LlmAdapter { const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } -async function setup(model?: { provider: string; model: string }) { +async function setup(model?: { provider: string; model: string }, ptc = false) { + native.cleanup.mockReset().mockResolvedValue({ dispatched: true }) native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() native.instances.length = 0 native.reportDiagnostic = undefined const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) - await mountAgentLoopTestDependencies(ctx) + await mountAgentLoopTestDependencies(ctx, ptc ? { workingDirectory: true, tools: { mode: 'ptc' } } : {}) await ctx.plugin(ComputerUseRegistry) - await ctx.plugin(Subprocess, []) + if (ptc) { + await ctx.plugin(SubprocessLocal) + await ctx.plugin(Sandbox) + await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access' }) + await ctx.plugin(NodeRuntime) + } else await ctx.plugin(Subprocess, []) const provider = await ctx.plugin(NativeProvider, config) await mountAgentLoopTestHarness(ctx) - const handle = await ctx.agents.create({ sessionId: SessionId('native-lifecycle'), ...model ? { agentOptions: model } : {} }) + const handle = await ctx.agents.create({ sessionId: SessionId('native-lifecycle'), meta: { cwd: process.cwd() }, ...model ? { agentOptions: model } : {} }) let index = 0 const execute = (method = 'listApps', params: Record = {}, signal = new AbortController().signal) => executeToolFixture(ctx, { agent: handle.agent, signal, callId: ToolCallId(`lifecycle-${++index}`), name: 'cua', arguments: { method, params }, @@ -138,6 +147,69 @@ async function selectApplication(f: Awaited>) { expect((await f.execute('getApp', { selector: 'Fixture' })).isError).toBe(false) } +it('requires an enclosing run_code before sending a directional key', async () => { + const f = await setup() + await selectApplication(f) + native.request.mockClear() + const result = await f.execute('sendKeyEvent', { appHandle: 'app-one', key: 'w', direction: 'down' }) + expect(result.isError).toBe(true) + expect(JSON.stringify(result.content)).toContain('active run_code') + expect(native.request).not.toHaveBeenCalled() +}) + +it.each(['return', 'throw', 'pause'])('cleans up only the held W when run_code ends by %s', async (ending) => { + const f = await setup(undefined, true) + await selectApplication(f) + const held = new Set() + const events: string[] = [] + const controller = new AbortController() + const runIds = new Set() + native.request.mockImplementation(async (method, params) => { + expect(method).toBe('sendKeyEvent') + runIds.add(params.runId) + const key = String(params.key) + if (params.direction === 'down') held.add(key) + else held.delete(key) + events.push(`${key}:${params.direction}`) + return { dispatched: true } + }) + native.cleanup.mockImplementation(async (method, params) => { + expect(method).toBe('releaseHeldKeys') + expect(runIds).toEqual(new Set([params.runId])) + for (const key of held) events.push(`${key}:up`) + held.clear() + return { dispatched: true } + }) + f.ctx.tools.register({ + name: 'check_held_keys', description: 'Observe the keys held by the test receiver.', + parameters: { type: 'object', properties: {} }, + output: { schema: {}, render: () => [] }, + async execute() { + const keys = [...held] + if (ending === 'pause' && keys.length === 1) { + controller.abort() + await setImmediate() + expect(held.size).toBe(0) + } + return keys + }, + }) + const code = [ + "const key = (key, direction) => tools.cua({ method: 'sendKeyEvent', params: { appHandle: 'app-one', key, direction } });", + "await key('w', 'down'); await key('d', 'down');", + "if ((await tools.check_held_keys({})).join(',') !== 'w,d') throw Error('lost held keys');", + "await key('d', 'up');", + "if ((await tools.check_held_keys({})).join(',') !== 'w') throw Error('lost W');", + ending === 'throw' ? "throw Error('program failed');" : "return 'done';", + ].join('\n') + const result = await executeModelToolFixture(f.ctx, { agent: f.handle.agent, callId: ToolCallId('keyboard-run'), + name: 'run_code', arguments: { code, description: 'Exercise held keys' }, signal: controller.signal }) + expect(events, JSON.stringify(result.content)).toEqual(['w:down', 'd:down', 'd:up', 'w:up']) + expect(native.cleanup).toHaveBeenCalledTimes(1) + expect(result.isError).toBe(ending !== 'return') + if (ending === 'throw') expect(JSON.stringify(result.content)).toContain('program failed') +}) + it('rejects a relative helper path before publishing computer-use operations', async () => { const ctx = new Context() onTestFinished(() => ctx.fiber.dispose()) @@ -200,7 +272,7 @@ it('merges startup capabilities into runtime native fields', async () => { coordinateSpace: 'screenshot-pixels', methods: [ 'activate', 'click', 'drag', 'findApps', 'getApp', 'getCapabilities', 'getState', 'invoke', 'listActions', 'listApps', 'listWindows', 'mouseMove', 'paste', 'performAction', 'pressKey', 'screenshot', 'scroll', - 'selectText', 'setValue', 'show', 'typeText', + 'selectText', 'sendKeyEvent', 'setValue', 'show', 'typeText', ] }) expect(native.request).toHaveBeenCalledExactlyOnceWith('getCapabilities', {}, expect.any(AbortSignal), ToolCallId('lifecycle-1')) }) diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index d6c75f46bc..e06b6989ea 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -126,6 +126,9 @@ export interface CuaBackend { createChannel: NativeChannelFactory guidance: string capabilities: CuaStartupCapabilities + /** Dispatch a directional key through the provider's execution-scoped input owner, after application authorization. */ + sendKeyEvent?: (client: NativeClient, params: Extract['params'], + execution: Readonly) => Promise /** * Build native permission parameters for the selected action and Client language. * @param method Native permission action. @@ -211,6 +214,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient + if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, parsedParams, execution) const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' diff --git a/packages/experimental/cua/src/native-client.ts b/packages/experimental/cua/src/native-client.ts index 25c93e15ce..d2e70813ec 100644 --- a/packages/experimental/cua/src/native-client.ts +++ b/packages/experimental/cua/src/native-client.ts @@ -81,7 +81,12 @@ export class NativeClient { private diagnostics: string[] = [] private diagnosticBytes = 0 private discardedDiagnostics = false - private active: { id: string; resolve: (value: JsonValue) => void; reject: (error: NativeError) => void } | undefined + private active: { + id: string + outcome: Promise + resolve: (value: JsonValue) => void + reject: (error: NativeError) => void + } | undefined /** * @param owner - Managed subprocess provider. @@ -133,7 +138,10 @@ export class NativeClient { throw new NativeError('NATIVE_REQUEST_LIMIT', 'Request exceeded the configured byte limit before dispatch') } const outcome = Promise.withResolvers() - this.active = { id, resolve: outcome.resolve, reject: (error) => { nativeFailure = error; outcome.reject(error) } } + this.active = { + id, outcome: outcome.promise, resolve: outcome.resolve, + reject: (error) => { nativeFailure = error; outcome.reject(error) }, + } if (capture) this.diagnostic(screenshotPrefix + JSON.stringify({ requestId: id, stage: 'host.dispatch', elapsedMs: 0 })) const interrupt = (error: NativeError): void => { if (interruption || this.active?.id !== id) return @@ -193,6 +201,17 @@ export class NativeClient { } } + /** + * Dispatch cleanup after any active request acknowledges completion or cancellation. + * @param method - Host-only helper cleanup operation. + * @param params - Resources owned by the enclosing execution. + * @returns The native cleanup acknowledgement, bounded by the connection's request deadline. + */ + async requestCleanup(method: string, params: Record): Promise { + while (this.active) await this.active.outcome.catch(() => undefined) + return this.request(method, params, new AbortController().signal) + } + private screenshotDiagnostics(): string { const records = [...this.diagnostics] if (this.discardedDiagnostics) records.unshift('[Earlier screenshot diagnostic records were discarded from the bounded diagnostic buffer.]') diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index 42b545e66a..e4de9f4734 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -93,7 +93,7 @@ export const NativeResourceParameters = { } /** Host-only launch continuation and user-facing system permission controls; absent from model arguments. */ export const NativeOnlyOperations = [ - operation('launchApp', app), operation('permissionStatus', {}), + operation('launchApp', app), operation('releaseHeldKeys', { runId: z.string().min(1) }), operation('permissionStatus', {}), operation('applicationIcons', { paths: z.array(z.string().min(1)) }), operation('requestPermission', { permission: z.enum(['accessibility', 'screenRecording']) }), operation('openPermissionSettings', { permission: z.enum(['accessibility', 'screenRecording']) }), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index da1c1eaf56..ca34f16e2c 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -169,7 +169,7 @@ export interface CuaSurface { pressKey(key: string | string[], modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * Does not send the opposite event. + * On macOS, down persists within one run_code until explicit up, program completion (including errors), or user pause. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. * @param direction - Explicit event direction; the opposite event is never sent implicitly. diff --git a/packages/experimental/cua/tests/native-client.spec.ts b/packages/experimental/cua/tests/native-client.spec.ts index f7a9007f42..19475f83fe 100644 --- a/packages/experimental/cua/tests/native-client.spec.ts +++ b/packages/experimental/cua/tests/native-client.spec.ts @@ -63,6 +63,18 @@ function fixture(options: { } describe('native helper transport', () => { + it('sends run cleanup after an interrupted native request has acknowledged its outcome', async () => { + const f = fixture() + const active = f.client.request('getState', {}, new AbortController().signal) + const release = f.client.requestCleanup('releaseHeldKeys', { runId: 'program' }) + expect(f.requests).toHaveLength(1) + f.reply({ id: f.id(), error: { code: 'NATIVE_CANCELLED', message: 'paused' } }) + await expect(active).rejects.toThrow('paused') + expect(f.requests.map(frame => frame.method)).toEqual(['getState', 'releaseHeldKeys']) + f.reply({ id: f.id(), result: { dispatched: true } }) + await expect(release).resolves.toEqual({ dispatched: true }) + }) + it('passes transport limits and connection deadlines to the shared channel', () => { const f = fixture({ maxRequestBytes: 4096, maxResponseBytes: 8192, timeoutMs: 1234 }) expect(f.connect).toHaveBeenCalledExactlyOnceWith(f.owner, f.config) diff --git a/snapshots/session/cua-native/session.v4.jsonl b/snapshots/session/cua-native/session.v4.jsonl index 10a71dc794..728ff1c9c2 100644 --- a/snapshots/session/cua-native/session.v4.jsonl +++ b/snapshots/session/cua-native/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Inspect CUA capabilities, select the","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949731596,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949731597,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}}},{"type":"chunk","time":1793949731597,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949731597,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"cua-native-1","name":"cua","arguments":"{\"method\":\"getCapabilities\",\"params\":{}}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"cua-native-1"},"toolCallId":"cua-native-1","content":[{"type":"text","text":"{\"sessionLocked\":false,\"permissions\":{\"accessibility\":true,\"screenRecording\":true},\"platform\":\"macos\",\"methods\":[\"activate\",\"click\",\"drag\",\"findApps\",\"getApp\",\"getCapabilities\",\"getState\",\"invoke\",\"listActions\",\"listApps\",\"listWindows\",\"mouseMove\",\"paste\",\"performAction\",\"pressKey\",\"screenshot\",\"scroll\",\"selectText\",\"sendKeyEvent\",\"setValue\",\"show\",\"typeText\"],\"appLevelAccessibility\":true,\"keyboard\":[\"app\"],\"browser\":false,\"coordinateSpace\":\"screenshot-pixels\"}"}],"isError":false,"id":"{{message:5}}"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash-vision-exp"},"id":"{{message:6}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1793949732188,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1793949732188,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"cua-unauthorized-getState","name":"cua","arguments":"{\"method\":\"getState\",\"params\":{\"appHandle\":\"fixture-app\"}}"}}},{"type":"chunk","time":1793949732188,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1793949732188,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 73107a5ee3..3ed01c96c7 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -78,7 +78,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 14f13a5a00..e8c8afed86 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -80,7 +80,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 6e0914ac15..990f35fcd0 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -80,7 +80,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From 7f8a6ad4d4943787be86ae9ce1d2d461ec732a8b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 13:36:26 +0800 Subject: [PATCH 088/103] test(cua-macos): isolate desktop key holds and cover failed pause cleanup --- docs/config-catalog.md | 2 +- docs/config-catalog.zh.md | 2 +- docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/tests/CapabilitiesFixture.swift | 5 +- .../native/tests/capabilities_e2e.py | 59 +++++++++++-------- .../experimental/cua-macos/src/held-keys.ts | 1 - .../tests/provider-lifecycle.spec.ts | 13 ++-- packages/experimental/cua/src/index.ts | 4 +- 12 files changed, 59 insertions(+), 39 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index dede6981f9..67006d1d03 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1144,7 +1144,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 9c142b9b43..d476f746da 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -1146,7 +1146,7 @@ export interface Config { - `inject`: `computerUse` · `tools` · `systemPrompt` · `subprocess` · `agents` - `refs`: [`CuaConfig`](../packages/experimental/cua/src/index.ts) -- `source`: [`packages/experimental/cua-macos/src/index.ts:33`](../packages/experimental/cua-macos/src/index.ts) +- `source`: [`packages/experimental/cua-macos/src/index.ts:34`](../packages/experimental/cua-macos/src/index.ts) ```ts config-catalog /** Native preparation, source-build signing, operation bounds, and profile-local application grants. */ diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index b4cffaf1aa..18901156ff 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -84,7 +84,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index b1b58ef08a..9ebcc28905 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -86,7 +86,7 @@ | `system-prompt/assemble` | `waterfall` | [`packages/core/system-prompt/src/index.ts:31`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`waterfall`) | `browser-use-runtime`, [`working-directory`](../packages/session/working-directory) | | `system-prompt/change` | `emit` | [`packages/core/system-prompt/src/index.ts:37`](../packages/core/system-prompt/src/index.ts) | [`system-prompt`](../packages/core/system-prompt) (`emit`) | - | | `tools/change` | `emit` | [`packages/core/tools/src/events.ts:56`](../packages/core/tools/src/events.ts) | [`agent-preset-registry`](../packages/preset/agent-preset-registry) (`emit`), [`tools`](../packages/core/tools) (`emit`) | `browser-use-runtime` | -| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | +| `tools/execute` | `waterfall` | [`packages/core/tools/src/events.ts:29`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `browser-use-runtime`, `browser-use-stagehand-native`, `claude-code-mods`, `computer-use-cua-driver-native`, `cua-macos`, [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), `timeout-policy` | | `tools/post-execute` | `waterfall` | [`packages/core/tools/src/events.ts:41`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `claude-code-mods`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), [`repeat-tool-reminder`](../packages/guard/repeat-tool-reminder), [`spill-policy`](../packages/spill/spill-policy), [`tool-fs-search`](../packages/fs/tool-fs-search) | | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 2b78969668..5e6adac2ce 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -24,8 +24,8 @@ en: 851614a21ebfeb65 zh: ff868b14dc77adb8 /dsh-cua-native-helper/verification: - en: ade5a2ccd3aeb1b4 - zh: 74c2b0bcb23fc4bc + en: c87945aeec587bf5 + zh: e5d69e4927e2fed3 /dsh-cua-native-helper/further-exploration: en: 265e1927952ce6d7 zh: 7c35d9fd98b6e6c8 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index b3074d6ce9..cc1c046ca9 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -159,7 +159,7 @@ For text pacing comparisons, use `native/tests/text_input_benchmark.py` with `-- For an independently isolated Electron/Chromium check, run `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`. Omitting `--electron` uses an already installed desktop workspace runtime. The check never downloads Electron. Its renderer runs with Node integration disabled, context isolation and Chromium sandboxing enabled, private userData/sessionData/log directories, and a local fixture page. Renderer click/input events write independent observations through the main process; all test actions still use the native helper. AX polling waits for actual controls after Chromium accessibility activation. Native and Electron subprocess groups are owned and stopped before temporary files are removed. Optional artifacts include a fixture-only screenshot and private request transcript. -Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures, overlapping W and D key events, and keypad identities through an isolated AppKit receiver. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results. +Run `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence` to verify a stopped application's discovery and launch, Unicode selection, multiline plain/HTML paste, middle/modifier gestures, overlapping W and D key events, and keypad identities through an isolated AppKit receiver. Add `--keyboard-only` for a background receiver that checks a two-second W+D hold, independent D release, and W cleanup. Add `--click-only` to check click holds, AX routing and cancellation/timeout release in a background fixture without keyboard or clipboard input. It requires existing Accessibility/Screen Recording grants and records the receiver's actual state separately from dispatch results. Run `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence` to verify that an owned AppKit app accepts a background Paste action without reading its data, reports `PASTE_NOT_CONSUMED`, then consumes the same paste in the foreground. The test requires an unlocked Mac and Accessibility permission, activates only its own two applications, and records received actions and text independently of helper replies. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 6035ffaee2..73b7754b3a 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -159,7 +159,7 @@ Blender 键盘检查使用 `python3 packages/experimental/cua-macos/native/tests 隔离的 Electron/Chromium 检查使用 `python3 packages/experimental/cua-macos/native/tests/electron_e2e.py --electron /absolute/path/to/Electron.app/Contents/MacOS/Electron`。省略 `--electron` 时使用桌面工作区已安装的运行时,检查不下载 Electron。渲染器禁用 Node 集成,启用上下文隔离和 Chromium 沙箱,使用独立 userData/sessionData/log 目录及本地 fixture 页面。渲染器的点击/输入事件通过主进程写出独立观察,测试动作仍通过原生 helper 执行。AX 轮询等待 Chromium 辅助功能启用后的真实控件。原生和 Electron 子进程组由测试持有,在删除临时文件前停止。可选产物包含仅有 fixture 的截图和私有请求记录。 -运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。 添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。 +运行 `python3 packages/experimental/cua-macos/native/tests/capabilities_e2e.py --helper /absolute/helper --artifacts /private/evidence`,通过隔离的 AppKit 接收方验证未运行应用的发现和启动、Unicode 选区、多行纯文本/HTML 粘贴、带修饰键的中键手势、W 和 D 同时按住时的事件顺序及数字键盘键码。需要已有辅助功能/屏幕录制权限,接收方实际状态与分派结果分开记录。添加 `--keyboard-only` 可用后台窗口验证 W、D 同时按住两秒、单独释放 D 和收尾时释放 W。添加 `--click-only` 可在后台测试窗口中验证按住时长、AX 路由和取消、超时后的松开事件,不发送键盘或剪贴板输入。 运行 `python3 packages/experimental/cua-macos/native/tests/paste_e2e.py --artifacts /private/evidence`,验证自有 AppKit 应用在后台接收 Paste 动作但不读取数据时返回 `PASTE_NOT_CONSUMED`,以及前台读取同一次粘贴后成功。测试要求 Mac 已解锁并已授予辅助功能权限,只激活自有的两个应用,并独立记录收到的动作和文本以核对 helper 回复。 diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 5382155260..1151468790 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -92,7 +92,10 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega } window.contentView!.addSubview(pad) if Bundle.main.object(forInfoDictionaryKey: "DSHFixtureBackground") as? Bool == true || CommandLine.arguments.contains("--background") { - window.orderFront(nil) + if Bundle.main.object(forInfoDictionaryKey: "DSHFixtureKeyboard") as? Bool == true { + window.makeFirstResponder(pad) + window.orderBack(nil) + } else { window.orderFront(nil) } } else { window.makeKeyAndOrderFront(nil) window.makeFirstResponder(text) diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 432f70e81f..6649b82dd9 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -123,11 +123,39 @@ def check_clicks(helper, window, point, state_file): return state +def check_keyboard(call, owner, state_file, state): + count = len(state["events"]) + call("pressKey", {**owner, "key": ["w", "d"]}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) + chord = [(event["type"], event.get("keyCode")) for event in state["events"][count:]] + assert chord == [(10, 13), (10, 2), (11, 2), (11, 13)], chord + count = len(state["events"]) + + def key(name, direction): + call("sendKeyEvent", {**owner, "runId": "held-input", "key": name, "direction": direction}) + + key("w", "down") + key("d", "down") + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 2) + call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) + time.sleep(2) + key("d", "up") + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 3) + held = state["events"][count:] + assert [(event["type"], event["keyCode"]) for event in held] == [(10, 13), (10, 2), (11, 2)], held + assert held[2]["timestamp"] - held[1]["timestamp"] >= 2, held + call("releaseHeldKeys", {"runId": "held-input"}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) + assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] + + def main(): parser = argparse.ArgumentParser() parser.add_argument("--helper", type=Path, required=True) parser.add_argument("--artifacts", type=Path) - parser.add_argument("--click-only", action="store_true") + only = parser.add_mutually_exclusive_group() + only.add_argument("--click-only", action="store_true") + only.add_argument("--keyboard-only", action="store_true") args = parser.parse_args() transcript = [] helper = None @@ -141,7 +169,8 @@ def main(): info = {"CFBundleName": "Capabilities Fixture", "CFBundleDisplayName": "Capabilities Fixture", "CFBundleIdentifier": "test.dsh.cua." + uuid.uuid4().hex, "CFBundleExecutable": "CapabilitiesFixture", "CFBundlePackageType": "APPL", - "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only} + "DSHFixtureStatePath": str(state_file), "DSHFixtureBackground": args.click_only or args.keyboard_only, + "DSHFixtureKeyboard": args.keyboard_only} (application / "Contents/Info.plist").write_bytes(plistlib.dumps(info)) subprocess.run(["swiftc", str(ROOT / "tests/CapabilitiesFixture.swift"), "-o", str(executable)], check=True) try: @@ -158,6 +187,10 @@ def main(): app = call("launchApp", owner) assert app["running"] is True, app pid = wait_for_state(state_file, lambda value: value["windowId"] > 0)["pid"] + if args.keyboard_only: + check_keyboard(call, owner, state_file, json.loads(state_file.read_text())) + print("PASS: W+D short press, two-second hold, independent D up and remaining W cleanup") + return if not args.click_only: call("activate", owner) state = wait_for_state(state_file, lambda value: value["pid"] == pid and value["active"] and value["keyWindow"]) @@ -188,27 +221,7 @@ def main(): if not args.click_only: call("click", {**window, **point, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 26 and event.get("button") == 2 and event["shift"] for event in value["events"])) - count = len(state["events"]) - call("pressKey", {**owner, "key": ["w", "d"]}) - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) - chord = [(event["type"], event.get("keyCode")) for event in state["events"][count:]] - assert chord == [(10, 13), (10, 2), (11, 2), (11, 13)], chord - count = len(state["events"]) - def key(name, direction): - call("sendKeyEvent", {**owner, "runId": "held-input", "key": name, "direction": direction}) - key("w", "down") - key("d", "down") - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 2) - call("getState", {**owner, "maxElements": 2000, "maxDepth": 25}) - time.sleep(2) - key("d", "up") - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 3) - held = state["events"][count:] - assert [(event["type"], event["keyCode"]) for event in held] == [(10, 13), (10, 2), (11, 2)], held - assert held[2]["timestamp"] - held[1]["timestamp"] >= 2, held - call("releaseHeldKeys", {"runId": "held-input"}) - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) - assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] + check_keyboard(call, owner, state_file, state) call("drag", {**window, "fromX": point["x"], "fromY": point["y"], "toX": point["x"] + 80, "toY": point["y"] + 20, "durationMs": 200, "steps": 10, "mouseButton": "middle", "modifiers": ["shift"]}) state = wait_for_state(state_file, lambda value: any(event["type"] == 27 and event.get("button") == 2 and event["shift"] for event in value["events"])) diff --git a/packages/experimental/cua-macos/src/held-keys.ts b/packages/experimental/cua-macos/src/held-keys.ts index 30c1311da8..0cfb58c6fa 100644 --- a/packages/experimental/cua-macos/src/held-keys.ts +++ b/packages/experimental/cua-macos/src/held-keys.ts @@ -35,7 +35,6 @@ export function installHeldKeys(ctx: Context): NonNullable { const run = execution.parent && runs.get(execution.parent) if (!run) throw new NativeError('INVALID_ARGUMENT', 'Use sendKeyEvent inside an active run_code execution') - if (run.client && run.client !== client) throw new NativeError('NATIVE_CLOSED', 'The keyboard connection changed; start a new run_code') run.client = client return client.request('sendKeyEvent', { ...params, runId: run.id }, execution.signal, execution.callId) } diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index 194f7244fd..a6efc825a9 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -37,12 +37,14 @@ import type { NativeClient } from '@deepseek-ai/dsh-cua/native-client' import type { NativeBuildSpec } from '../src/native-build.ts' const native = vi.hoisted(() => ({ + connect: vi.fn(), prepare: vi.fn<(spec: NativeBuildSpec) => Promise>(), architecture: vi.fn(() => 'arm64' as const), cleanup: vi.fn(), request: vi.fn(), dispose: vi.fn(), instances: [] as Array<{ disposed: boolean }>, reportDiagnostic: undefined as ((message: string) => void) | undefined, })) +vi.mock('../src/shared-native.ts', () => ({ createSharedNativeChannel: native.connect })) vi.mock('../src/native-build.ts', async importOriginal => ({ ...await importOriginal(), nativeHostArchitecture: native.architecture, @@ -53,6 +55,7 @@ vi.mock('@deepseek-ai/dsh-cua/native-client', async importOriginal => ({ NativeClient: class { disposed = false constructor(...args: ConstructorParameters) { + args[2](args[0], args[1]) native.reportDiagnostic = args[3] native.instances.push(this) } @@ -114,6 +117,7 @@ const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoA const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } async function setup(model?: { provider: string; model: string }, ptc = false) { + native.connect.mockClear() native.cleanup.mockReset().mockResolvedValue({ dispatched: true }) native.request.mockReset().mockResolvedValue([]) native.dispose.mockReset() @@ -157,7 +161,7 @@ it('requires an enclosing run_code before sending a directional key', async () = expect(native.request).not.toHaveBeenCalled() }) -it.each(['return', 'throw', 'pause'])('cleans up only the held W when run_code ends by %s', async (ending) => { +it.each(['return', 'throw', 'pause', 'pause with cleanup error'])('cleans up only the held W when run_code ends by %s', async (ending) => { const f = await setup(undefined, true) await selectApplication(f) const held = new Set() @@ -176,6 +180,7 @@ it.each(['return', 'throw', 'pause'])('cleans up only the held W when run_code e native.cleanup.mockImplementation(async (method, params) => { expect(method).toBe('releaseHeldKeys') expect(runIds).toEqual(new Set([params.runId])) + if (ending === 'pause with cleanup error') throw new Error('release acknowledgement failed') for (const key of held) events.push(`${key}:up`) held.clear() return { dispatched: true } @@ -186,10 +191,10 @@ it.each(['return', 'throw', 'pause'])('cleans up only the held W when run_code e output: { schema: {}, render: () => [] }, async execute() { const keys = [...held] - if (ending === 'pause' && keys.length === 1) { + if (ending.startsWith('pause') && keys.length === 1) { controller.abort() await setImmediate() - expect(held.size).toBe(0) + expect(held.size).toBe(ending === 'pause' ? 0 : 1) } return keys }, @@ -204,7 +209,7 @@ it.each(['return', 'throw', 'pause'])('cleans up only the held W when run_code e ].join('\n') const result = await executeModelToolFixture(f.ctx, { agent: f.handle.agent, callId: ToolCallId('keyboard-run'), name: 'run_code', arguments: { code, description: 'Exercise held keys' }, signal: controller.signal }) - expect(events, JSON.stringify(result.content)).toEqual(['w:down', 'd:down', 'd:up', 'w:up']) + expect(events, JSON.stringify(result.content)).toEqual(['w:down', 'd:down', 'd:up', ...ending === 'pause with cleanup error' ? [] : ['w:up']]) expect(native.cleanup).toHaveBeenCalledTimes(1) expect(result.isError).toBe(ending !== 'return') if (ending === 'throw') expect(JSON.stringify(result.content)).toContain('program failed') diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index e06b6989ea..d88a958711 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -127,7 +127,7 @@ export interface CuaBackend { guidance: string capabilities: CuaStartupCapabilities /** Dispatch a directional key through the provider's execution-scoped input owner, after application authorization. */ - sendKeyEvent?: (client: NativeClient, params: Extract['params'], + sendKeyEvent?: (client: NativeClient, params: Record, execution: Readonly) => Promise /** * Build native permission parameters for the selected action and Client language. @@ -214,7 +214,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) const signal = execution.signal signal.throwIfAborted() const client = execution.nativeClient - if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, parsedParams, execution) + if (method === 'sendKeyEvent' && backend.sendKeyEvent) return backend.sendKeyEvent(client, params, execution) const nativeParams = method === 'findApps' ? { ...params, maxAppMatches: config.maxAppMatches } : method === 'paste' From de0515a771cd93ab0f4f92d6712900188046f1c6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 13:41:15 +0800 Subject: [PATCH 089/103] fix(cua-macos): retain the run signal and validate test receiver events --- packages/experimental/cua-macos/README.i18n.yaml | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua-macos/src/held-keys.ts | 5 +++-- .../cua-macos/tests/provider-lifecycle.spec.ts | 7 ++++--- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 1abb4f6399..bb17939f06 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -16,7 +16,7 @@ zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: en: f4206e2cb725c917 - zh: 37f0b04e9e74c193 + zh: d10792bd8e7e242b /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 0f6f4dad51..51826288e4 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -81,7 +81,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 接受单个键名或由不同物理键组成的非空数组。`Enter` 和 `Return` 等别名指向同一个物理键。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。需要全程按住的修饰键单独传入,例如 `pressKey('Tab', ['shift'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。单独传入 `+` 或 `plus` 会发送 Shift 和等号。在多键组合中请使用 `=`,需要全程按住 Shift 时将其列入修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。按下成功后,在同一次执行中调用其他工具时该键仍保持按下。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 向每个键原先的接收进程松开该次执行仍按着的键。后续执行不能释放前一次执行的键。 +长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。按下成功后,在同一次执行中调用其他工具时该键仍保持按下。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 diff --git a/packages/experimental/cua-macos/src/held-keys.ts b/packages/experimental/cua-macos/src/held-keys.ts index 0cfb58c6fa..fee0519c53 100644 --- a/packages/experimental/cua-macos/src/held-keys.ts +++ b/packages/experimental/cua-macos/src/held-keys.ts @@ -24,11 +24,12 @@ export function installHeldKeys(ctx: Context): NonNullable { void release()?.catch(() => undefined) } - execution.signal.addEventListener('abort', onAbort, { once: true }) + const signal = execution.signal + signal.addEventListener('abort', onAbort, { once: true }) try { return await next() } finally { - execution.signal.removeEventListener('abort', onAbort) + signal.removeEventListener('abort', onAbort) await release() } }) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index a6efc825a9..f65e1a6a61 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -171,10 +171,11 @@ it.each(['return', 'throw', 'pause', 'pause with cleanup error'])('cleans up onl native.request.mockImplementation(async (method, params) => { expect(method).toBe('sendKeyEvent') runIds.add(params.runId) - const key = String(params.key) - if (params.direction === 'down') held.add(key) + const { key, direction } = params + if (typeof key !== 'string' || (direction !== 'down' && direction !== 'up')) throw new Error('Invalid directional event') + if (direction === 'down') held.add(key) else held.delete(key) - events.push(`${key}:${params.direction}`) + events.push(`${key}:${direction}`) return { dispatched: true } }) native.cleanup.mockImplementation(async (method, params) => { From 5195b73915779c4d9c54253149b8c6eb68e21f12 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 13:46:49 +0800 Subject: [PATCH 090/103] fix(ui-subagent): distinguish unread catalogs and isolate browser checks --- .../unread-catalog.expected.md | 12 ------- apps/web/tests/forge-panel.e2e.ts | 15 +++++---- apps/web/tests/subagent-conversation.e2e.ts | 32 ++++++++++++++++--- packages/client/ui-subagent/README.i18n.yaml | 8 ++--- packages/client/ui-subagent/README.md | 4 ++- packages/client/ui-subagent/README.zh.md | 4 ++- .../client/SubagentHeaderLineage.module.css | 4 --- .../src/client/SubagentHeaderLineage.tsx | 7 ++-- .../client/ui-subagent/src/client/locales.ts | 8 +++++ .../tests/conversation-ui.client.spec.tsx | 25 +++++++++++++-- 10 files changed, 81 insertions(+), 38 deletions(-) delete mode 100644 apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md diff --git a/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md b/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md deleted file mode 100644 index b1ccd511e5..0000000000 --- a/apps/web/tests/expected/subagent-conversation/unread-catalog.expected.md +++ /dev/null @@ -1,12 +0,0 @@ -- tree "Subagent sessions": - - treeitem "event-sourcing researcher agent-1 · continuable · completed 7.9K tok · {{duration}}" [expanded] [level=1]: - - button "Collapse event-sourcing researcher descendants" - - text: event-sourcing researcher agent-1 7.9K tok {{duration}} - - button "Open event-sourcing researcher in sidebar" - - group: - - treeitem "example editor recorded-grandchild · continuable · completed 0 tok · {{duration}}" [level=2]: - - text: example editor recorded-grandchild 0 tok {{duration}} - - button "Open example editor in sidebar" - - treeitem "event-sourcing reviewer recorded-one-shot · one-shot · completed 0 tok · {{duration}}" [level=1]: - - text: event-sourcing reviewer recorded-one-shot 0 tok ~6mo 12d - - button "Open event-sourcing reviewer in sidebar" diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 0392e51260..4cb03a2c86 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -462,13 +462,14 @@ it.skipIf(MODE === 'record')('automatically shows a numbered PR when gh JSON omi await change.getByText('等待评审 · 1 条未解决讨论', { exact: true }).waitFor() await compareOrRefreshGolden(join(EXPECTED, 'reference.expected.md'), await captureStableAria(page, `[data-forge-change="${PULL}"]`, scaffold.workspaceCwd), MODE) - // Reference lookup can finish after the turn; the visible card confirms its binding was appended. - await scaffold.ctx.sessionPersistence.flush() - const boundEvents = await readPersistedEvents(scaffold, sessionId) - expect(boundEvents.flatMap((event) => { - const record = pluginRecordOf(event) - return record?.type === 'plugin:forge-session/binding' ? [record.data] : [] - })).toEqual([{ action: 'reference', url: PULL }]) + await expect.poll(async () => { + await scaffold.ctx.sessionPersistence.flush() + const boundEvents = await readPersistedEvents(scaffold, sessionId) + return boundEvents.flatMap((event) => { + const record = pluginRecordOf(event) + return record?.type === 'plugin:forge-session/binding' ? [record.data] : [] + }) + }).toEqual([{ action: 'reference', url: PULL }]) const calls = (await readFile(join(project, '.fixture-bin', 'calls.jsonl'), 'utf8')).trim().split('\n').map(line => JSON.parse(line) as string[]) expect(calls).toContainEqual(['pr', 'view', '7', '--repo', 'octo/demo', '--json', 'url']) expect(tripwire.pageErrors).toEqual([]) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index 018f5e3f18..a3345c93bf 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -405,14 +405,12 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await grandchild.waitFor() expect(await grandchild.getAttribute('aria-expanded')).toBeNull() await compareOrRefreshGolden( - fileURLToPath(new URL('./expected/subagent-conversation/unread-catalog.expected.md', import.meta.url)), + TREE_EXPECTED, await captureStableAria(page, '[role="tree"][aria-label="Subagent sessions"]', scaffold.workspaceCwd), MODE, ) expect(page.url()).toBe(parentUrl) expect(scaffold.ctx.agents.get(childId)).toBeUndefined() expect(scaffold.ctx.agents.get(grandchildId)).toBeUndefined() - await mkdir('.playwright-mcp/catalog-expand', { recursive: true }) - await page.screenshot({ path: '.playwright-mcp/catalog-expand/discovery.png' }) await page.keyboard.press('Escape') await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' }) } finally { @@ -481,7 +479,7 @@ describe('web e2e: persisted subagent conversation and human continuation', () = } expect(await row.getAttribute('aria-label')).toContain(`${LABEL} ${CHILD_NAME} `) expect(await row.getByRole('button', { name: /description/u }).count()).toBe(0) - expect(await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).count()).toBe(1) + await row.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }).waitFor() expect(await row.getByRole('button', { name: `Open ${LABEL} in sidebar`, exact: true }).count()).toBe(1) expect(page.url()).toBe(originalUrl) expect(await page.getByRole('tooltip').count()).toBe(0) @@ -497,8 +495,32 @@ describe('web e2e: persisted subagent conversation and human continuation', () = it('expands locally available cold catalogs without requesting or activating either level', async () => { onTestFailed(() => saveFailureShot(page, 'screenshots/non-migrating-session-reads/web-e2e-subagent-tree')) + const warningStart = tripwire.warnings.length + await page.reload({ waitUntil: 'load' }) + const trigger = page.getByRole('button', { name: '2 subagents', exact: true }) + await trigger.waitFor() + acknowledgeReloadConnectionLoss(tripwire, warningStart) + const siblingsRead = page.waitForResponse((response) => { + if (!response.url().endsWith('/api/session/projections')) return false + const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } } + return body.payload.args.request.sessionId === oneShotId + }) + await trigger.click() + await (await siblingsRead).finished() + const expand = page.getByRole('button', { name: `Expand ${LABEL} descendants`, exact: true }) + await expand.waitFor() + const descendantsRead = page.waitForResponse((response) => { + if (!response.url().endsWith('/api/session/projections')) return false + const body = response.request().postDataJSON() as { payload: { args: { request: { sessionId: SessionId } } } } + return body.payload.args.request.sessionId === grandchildId + }) + await expand.click() + await (await descendantsRead).finished() + await page.keyboard.press('Escape') + await page.locator('[data-subagent-panel]').waitFor({ state: 'detached' }) const catalogReads = apiCalls.filter(path => path === '/api/session/projections').length - await page.getByRole('button', { name: '2 subagents' }).hover() + await page.locator('[data-composer-input]').first().hover() + await trigger.hover() const catalogTree = page.getByRole('tree', { name: 'Subagent sessions' }) expect(await catalogTree.evaluate((element) => { const rect = element.getBoundingClientRect() diff --git a/packages/client/ui-subagent/README.i18n.yaml b/packages/client/ui-subagent/README.i18n.yaml index e4ce63e820..7381b1f9d5 100644 --- a/packages/client/ui-subagent/README.i18n.yaml +++ b/packages/client/ui-subagent/README.i18n.yaml @@ -30,8 +30,8 @@ en: c158f12dcaed87b7 zh: e5d315e7b1fb4fa9 /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/catalog-derivation: - en: 08735d4cc7569cfa - zh: 517309ca6a540adf + en: 3c06acc93d7d4d59 + zh: b967155aec39df0c /deepseek-ai-dsh-client-ui-subagent/understand-the-implementation/duration-completion-and-tokens: en: dcbc58d4cad47fa8 zh: e962a8cbdfd4a914 @@ -57,8 +57,8 @@ en: de2762a99572475f zh: 9b41107ad14ebf8a /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work: - en: ee310ff3cd487639 - zh: 23793aa1c28a23af + en: ea983111988e4b9b + zh: c0ed7a583d2cad52 /deepseek-ai-dsh-client-ui-subagent/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-subagent/README.md b/packages/client/ui-subagent/README.md index 357453d99e..555c6fd2d9 100644 --- a/packages/client/ui-subagent/README.md +++ b/packages/client/ui-subagent/README.md @@ -61,7 +61,7 @@ The [subagent runtime](../../subagent/subagent/README.md) owns continuation and ### Catalog derivation -The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. +The header lineage renderer reads `subagentCatalog` only from `projectionsBySession` through the standard `useSessions` hook. The Session object layer merges list-cache hints, explicit reads, and the Host-wide control stream into these shared values; live frames update loaded levels without per-menu subscriptions. Activity prefers the unified UI status and falls back to Session summaries; summaries also supply titles and usage. Rendering and hovering use only local projections and never request missing catalogs. An unread empty menu says “Subagents not loaded”; the loading notice appears only during a request. Missing and explicitly empty catalogs have no expansion arrow; a later shared projection with children makes the arrow available. Failures require explicit retry. Migration-required rows keep their history-opening actions without a format notice or descendant expansion; opening the Session supplies its catalog through history and control projections. External rows are always leaves and do not load child Sessions. Each header entry declares a footer slot below its tree. Optional UI contributes there within the same scroll container; the catalog owns opening and dismissal. CSS anchors keep the panel attached to its trigger within layout-viewport size limits. Browser zoom and panning move it with the page, so it may extend beyond the visual viewport. Internal scrolling, hover behavior, pinned opening, and focus restoration remain independent. @@ -123,6 +123,8 @@ Append-only. This package never edits earlier request tokens. These limits define what the catalog can show and what `@` references mean; they are current package constraints. - **Non-completed inactive outcomes remain grouped** — the catalog distinguishes a latest normal completion from other inactive states, but does not distinguish failure, cancellation, refusal, token exhaustion, or a child with no closed turn; the UI exposes no Activation identity, and stopping is limited to the composer's current-turn Stop for a running continuable child. +- **Ancestor menus require keyboard activation for uncached branches** — hovering does not read, and clicking the ancestor title navigates. Focus the title and press ArrowDown to prepare that level without leaving the current Session. +- **Level discovery stops on interruption** — an unexpected read rejection stops later siblings and is logged to the console. A reconnect can interrupt discovery before direct children are read; explicitly reopen the menu to prepare the level again. - **`@` references remain display-title text** — duplicate or renamed labels are ambiguous, so they intentionally do not acquire continuation semantics. diff --git a/packages/client/ui-subagent/README.zh.md b/packages/client/ui-subagent/README.zh.md index 5498652e1b..056fad6cde 100644 --- a/packages/client/ui-subagent/README.zh.md +++ b/packages/client/ui-subagent/README.zh.md @@ -61,7 +61,7 @@ kind: "package-reference" ### 目录派生 -页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 +页头谱系 renderer 通过标准 `useSessions` 钩子,仅从 `projectionsBySession` 读取 `subagentCatalog`。Session 对象层将列表缓存提示、显式读取和 Host 全局 control 流合并到这些共享值;实时帧更新已加载层级,无需每个菜单单独订阅。活动状态优先使用统一 UI status,缺少时使用 Session 摘要;摘要还提供标题与用量。渲染与悬停仅使用本地投影,不会请求缺失目录。尚未读取的空菜单显示“尚未加载子智能体”;仅请求进行中显示加载提示。缺失或显式为空的目录没有展开箭头;后续共享投影包含下级时才显示箭头。读取失败后需要显式重试。需要迁移的行保留打开历史的操作,不显示格式提示,也不展开下级;打开 Session 后,历史与 control 投影提供其目录。外部行始终为叶子,不加载子 Session。 每个页头入口在树下方声明 footer 插槽。可选 UI 通过该插槽加入同一滚动容器;目录负责打开和关闭。CSS 锚点让面板跟随触发器,并按布局视口限制尺寸。浏览器缩放和平移时面板随页面移动,因此可以超出视觉视口。内部滚动、悬停行为、点击固定展开和焦点恢复保持独立。 @@ -123,6 +123,8 @@ one-shot 和模式未知的 child 选用只读编辑器。可继续 child 经由 这些限制定义目录能显示什么、`@` 引用意味着什么;它们是当前包约束。 - **非完成的 inactive 结果仍合并显示**:目录能区分最近一次正常完成与其他 inactive 状态,但不区分失败、取消、拒绝、token 耗尽或尚无已结束轮次的 child;UI 不公开 Activation 身份,停止能力仅限编辑器上针对运行中可继续 child 的当前轮次 Stop。 +- **祖先菜单的未缓存分支需要键盘激活**:悬停不读取,点击祖先标题会导航。聚焦标题后按 ArrowDown,可在不离开当前 Session 的情况下准备这一层。 +- **单层发现会在中断后停止**:意外的读取拒绝会停止后续兄弟节点,并记录到控制台。重连可能在直接子节点读取前中断发现;需再次显式打开菜单来准备这一层。 - **`@` 引用仍是显示标题文本**:重复或改名后的 label 会有歧义,因此它们刻意不获得继续执行语义。 diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css index 570c6cd7ef..c450098395 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.module.css @@ -450,10 +450,6 @@ height: 23px; } -.children[aria-busy='true']::before { - content: none; -} - .children > .node::before { top: 0; bottom: 0; diff --git a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx index cffac90f99..8cbb5be217 100644 --- a/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx +++ b/packages/client/ui-subagent/src/client/SubagentHeaderLineage.tsx @@ -255,10 +255,13 @@ function CatalogRows({ const timer = setInterval(() => { setNow(Date.now()) }, 1_000) return () => { clearInterval(timer) } }, [running]) - const emptyLoading = (catalog.state === 'loading' || catalog.state === 'idle') && catalog.entries.length === 0 + const emptyLoading = catalog.state === 'loading' && catalog.entries.length === 0 const reserveDisclosure = catalog.entries.some(entry => canExpandCatalog(entry, catalogs, summaries)) return ( <> + {catalog.state === 'idle' && catalog.entries.length === 0 && ( +
    {t('load.idle')}
    + )} {emptyLoading && ( )} @@ -552,7 +555,7 @@ function CatalogDropdown(props: CatalogDropdownProps) { const totalCountKey = directCount === 1 ? 'count.total.one' : 'count.total.other' const runningCountKey = runningCount === 1 ? 'count.running.one' : 'count.running.other' const presentedCatalog: SubagentCatalogSnapshot | undefined = catalog ?? (variant === 'switcher' || props.hasBoardContent - ? { entries: [], state: 'loading', error: null } + ? { entries: [], state: 'idle', error: null } : undefined) const cancelHoverClose = (): void => { diff --git a/packages/client/ui-subagent/src/client/locales.ts b/packages/client/ui-subagent/src/client/locales.ts index e7edefbb2c..83754edd6c 100644 --- a/packages/client/ui-subagent/src/client/locales.ts +++ b/packages/client/ui-subagent/src/client/locales.ts @@ -26,6 +26,7 @@ export const zh = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': '正在加载子智能体…', + 'load.idle': '尚未加载子智能体', 'load.error': '无法加载子智能体', 'retry': '重试', 'mode.external': '外部任务', @@ -76,6 +77,7 @@ export const en: Record = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': 'Loading subagents…', + 'load.idle': 'Subagents not loaded', 'load.error': 'Unable to load subagents', 'retry': 'Retry', 'mode.external': 'External task', @@ -129,6 +131,7 @@ export const ja = { 'tokens.million': '{value}M', 'tokens.total': '{value} tok', 'loading.label': 'サブエージェントを読み込み中…', + 'load.idle': 'サブエージェントは未読み込みです', 'load.error': 'サブエージェントを読み込めません', 'retry': '再試行', 'mode.external': '外部タスク', @@ -179,6 +182,7 @@ export const es = { 'tokens.million': '{value}M', 'tokens.total': 'Tok {value}', 'loading.label': 'Cargando subagentes…', + 'load.idle': 'Subagentes sin cargar', 'load.error': 'No se pueden cargar subagentes', 'retry': 'Reintentar', 'mode.external': 'tarea externa', @@ -229,6 +233,7 @@ export const fr = { 'tokens.million': '{value}M', 'tokens.total': 'Jeton {value}', 'loading.label': 'Chargement des sous-agents…', + 'load.idle': 'Sous-agents non chargés', 'load.error': 'Impossible de charger les sous-agents', 'retry': 'Réessayer', 'mode.external': 'Tâche externe', @@ -279,6 +284,7 @@ export const de = { 'tokens.million': '{value}M', 'tokens.total': '{value}-Token', 'loading.label': 'Subagenten werden geladen…', + 'load.idle': 'Subagenten nicht geladen', 'load.error': 'Subagenten können nicht geladen werden', 'retry': 'Erneut versuchen', 'mode.external': 'Externe Aufgabe', @@ -329,6 +335,7 @@ export const ru = { 'tokens.million': '{value}M', 'tokens.total': '{value} ток', 'loading.label': 'Загрузка субагентов…', + 'load.idle': 'Субагенты не загружены', 'load.error': 'Невозможно загрузить субагенты', 'retry': 'Повторить', 'mode.external': 'Внешняя задача', @@ -379,6 +386,7 @@ export const pt = { 'tokens.million': '{value}M', 'tokens.total': '{value} valor', 'loading.label': 'Carregando subagentes…', + 'load.idle': 'Subagentes não carregados', 'load.error': 'Não foi possível carregar subagentes', 'retry': 'Tentar novamente', 'mode.external': 'Tarefa externa', diff --git a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx index e3234cfef1..a70f41295e 100644 --- a/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx +++ b/packages/client/ui-subagent/tests/conversation-ui.client.spec.tsx @@ -1781,7 +1781,9 @@ describe('SubagentHeaderLineage', () => { const switcher = screen.getByRole('button', { name: '切换子智能体:worker' }) hoverCatalog(switcher) - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(input.prepareCatalog).not.toHaveBeenCalled() + expect(screen.getByText('尚未加载子智能体')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryAllByRole('treeitem')).toEqual([]) expect(input.refreshProjection).not.toHaveBeenCalled() }) @@ -1887,11 +1889,30 @@ describe('SubagentHeaderLineage', () => { const switcher = screen.getByRole('button', { name: '切换子智能体:正在扫描项目文件' }) expect(input.refreshProjection).not.toHaveBeenCalled() hoverCatalog(switcher) - expect(screen.getByText('正在加载子智能体…')).toBeTruthy() + expect(input.prepareCatalog).not.toHaveBeenCalled() + expect(screen.getByText('尚未加载子智能体')).toBeTruthy() + expect(screen.queryByText('正在加载子智能体…')).toBeNull() expect(screen.queryAllByRole('treeitem')).toEqual([]) expect(input.refreshProjection).not.toHaveBeenCalled() }) + it.each(['idle', 'loading'] as const)('shows the actual %s state of an empty title menu', (state) => { + const input = { + ...props(undefined, {}, {}, { parentSessionId: PARENT, childSessionId: CHILD, mode: 'continuable' }), + lineageSessionId: CHILD, + displayTitle: 'worker', + } + const initial = input.useSessions(value => value) + render( select({ + ...initial, + projectionsBySession: { [PARENT]: { state, error: null, values: {} } }, + })} />) + hoverCatalog(screen.getByRole('button', { name: '切换子智能体:worker' })) + expect(screen.getByText(state === 'idle' ? zh['load.idle'] : zh['loading.label'])).toBeTruthy() + expect(screen.queryByText(state === 'idle' ? zh['loading.label'] : zh['load.idle'])).toBeNull() + expect(input.prepareCatalog).not.toHaveBeenCalled() + }) + it('keeps a nested title switcher scoped to its direct-parent catalog', () => { const input = { ...props(catalog(), { From a9e0950206c575c09c84312ac410a860a230048a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 14:10:32 +0800 Subject: [PATCH 091/103] docs(cua-macos): explain physical key repeat in sendKeyEvent guidance --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua-macos/src/guidance.ts | 2 +- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- snapshots/session/ptc-script-retained/system-prompt.expected.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 042cc4fa94..02b260705a 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 51826288e4..f67195c67b 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index e750c4068b..2fe07ef025 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -14,7 +14,7 @@ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { if (method === 'pressKey') return `- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 3ed01c96c7..82210fa306 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -79,7 +79,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index e8c8afed86..3acaa30b88 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 990f35fcd0..dc18435318 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — hold a physical key across tool calls within one run_code. Choose the keys, how long to hold them, and which tools to call while they are down. Send 'up' for each key when needed. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From ab9700e6ac3d8165aa3bc410198396c1e898011e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 14:19:08 +0800 Subject: [PATCH 092/103] refactor(cua-macos): reserve overlapping ordinary keys for sendKeyEvent --- ...05-cua-scoped-surfaces-and-input.i18n.yaml | 8 +- ...026-11-05-cua-scoped-surfaces-and-input.md | 4 +- ...-11-05-cua-scoped-surfaces-and-input.zh.md | 4 +- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 6 +- packages/experimental/cua-macos/README.zh.md | 6 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 2 +- .../Sources/CuaNative/KeyboardInput.swift | 27 ++----- .../Sources/CuaNative/RequestAdmission.swift | 7 -- .../cua-macos/native/generate-protocol.ts | 4 +- .../cua-macos/native/protocol.schema.json | 79 ++++++++----------- .../native/tests/capabilities_e2e.py | 12 +-- .../tests/swift/KeyboardChordTests.swift | 48 +++++------ .../native/tests/swift/ProtocolTests.swift | 12 --- .../experimental/cua-macos/src/guidance.ts | 4 +- .../cua-macos/tests/guidance.spec.ts | 5 +- .../tests/protocol-generation.spec.ts | 8 ++ packages/experimental/cua/README.i18n.yaml | 4 +- packages/experimental/cua/README.md | 2 +- packages/experimental/cua/README.zh.md | 2 +- .../experimental/cua/src/native-schema.ts | 8 +- packages/experimental/cua/src/protocol.ts | 7 +- packages/experimental/cua/src/types.ts | 8 +- packages/experimental/cua/tests/api.spec.ts | 5 +- .../experimental/cua/tests/protocol.spec.ts | 7 -- .../cua-native/system-prompt.expected.md | 4 +- .../cua-native/tool-schemas.expected.json | 17 +--- .../session/cua-ptc/system-prompt.expected.md | 4 +- .../system-prompt.expected.md | 4 +- 32 files changed, 128 insertions(+), 192 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml index 716f07d599..3e32b6eb92 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.i18n.yaml @@ -9,11 +9,11 @@ en: f72db0b79aa02fb5 zh: b91c1f177dc93ab4 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/decision: - en: 74f97ec371e61b82 - zh: a8a5cefc1e06bb20 + en: ec115e11f96ffe60 + zh: c1fe9eb2866196d0 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/alternatives-considered: - en: 2113f17a49e16670 - zh: 1df04d9736a3ad4f + en: 32c970ae153e0f6c + zh: 8431be0a10ffed15 /agent-note-cua-scoped-surfaces-and-separated-input-capabilities/consequences: en: c4b12ca80865e670 zh: 396426fad0105eaa diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md index 6b4fe604d5..cce266e52b 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.md @@ -14,7 +14,7 @@ Application and window objects share accessibility operations, but only an expli Provider startup capabilities are static. Platform, supported methods, application-level accessibility, keyboard scopes, browser support, and coordinate space are fixed when the provider is installed. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges the two layers for the model-visible result. The neutral RPC is a common operation representation, not a capability inventory; provider guidance names the actions its platform supports. -Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses one key or, on macOS, several physical keys in order and releases them in reverse while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. +Keyboard input keeps keys and modifiers separate: `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers, and its keyboard modifier list is a plain string array defined by the provider. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up without an implicit counterpart. A caller can therefore hold a modifier or split a gesture; neither method packs a chord string, and the shared schema does not enumerate platform key names. Within one API instance, the object facade keeps one current accessibility snapshot per application handle, shared by every application and window object for that handle, including repeated selections of the same application. `getWindow` reads its initial tree silently; `getApp` does the same when the provider reports application-level accessibility. A later `getAccessibilityTree` read invalidates the previous snapshot before dispatch. The facade automatically attaches the latest snapshot ID to element operations; callers use element IDs from the latest tree and do not assume an older ID still identifies the same control. Element IDs are opaque provider strings. Only an explicit `CuaWindow` captures screenshots or sends pointer input. The native helper retains its own application and optional-window snapshots behind that facade; the native layer and the facade snapshot remain separate. The external runtime continues to own variable persistence and completion serialization; the facade adds no evaluator. The [native object decision](2026-09-17-experimental-cua-object-api.md) owns evaluator independence, and the [shared helper decision](2026-10-09-cua-shared-native-helper.md) owns connection lifetime. @@ -24,7 +24,7 @@ Within one API instance, the object facade keeps one current accessibility snaps **An application-specific branch in the shared base** would let window objects inherit decisions and capability checks that apply only to applications. Scope factories that inject their own requirements keep the shared operations independent of which scope uses them. -**A packed chord string** requires parsing key names, separators, and plus escaping together, and it pushes platform alias normalization into the shared layer. Keystroke and direction are separate semantics: `pressKey` describes a complete press and release, while `sendKeyEvent` describes one explicit direction. Separate key and modifier values keep those semantics without a parser. +**A packed chord string** requires parsing key names, separators, and plus escaping together, and it pushes platform alias normalization into the shared layer. Keystroke and direction are separate semantics: `pressKey` describes one complete keystroke, while `sendKeyEvent` describes one explicit direction. Separate key and modifier values keep those semantics without a parser. **Platform keyboard key enumerations in the shared schema** would couple the portable operation schema to one provider's key names and require a schema change for each platform. Provider-defined strings let the provider interpret its own names while the shared schema stays neutral. diff --git a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md index d03c3b4723..5135dc9be8 100644 --- a/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-05-cua-scoped-surfaces-and-input.zh.md @@ -14,7 +14,7 @@ Status: implemented Provider 的启动能力是静态的。平台、支持的方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间在安装 provider 时固定。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。中立的 RPC 是通用操作表示,不是能力清单;provider 指导文本说明其平台支持的动作。 -键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放指定的键。macOS 也接受多个物理键,依次按下并逆序释放。修饰键名称由提供方定义,以字符串数组传入。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 +键盘输入把按键与修饰键分开:`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键,其键盘修饰键列表是 provider 定义的普通字符串数组。`sendKeyEvent(key, direction)` 只发送一次按下或抬起,不隐式发送相反事件。因此调用方可以保持修饰键或拆分手势;两个方法都不接受组合键字符串,共享 schema 也不枚举平台按键名。 在单个 API 实例内,对象门面按应用句柄保存一份当前辅助功能快照,该句柄的所有应用对象和窗口对象共享这份快照,包括对同一应用的重复选择。`getWindow` 静默执行首次树读取;当 provider 报告应用级辅助功能时,`getApp` 也静默读取。之后的 `getAccessibilityTree` 读取会在分派前使上一份快照失效。门面会为元素操作自动附加最新快照 ID;调用方应使用最新树中的元素 ID,不应假定旧 ID 仍指向同一控件。元素 ID 是 provider 定义的不透明字符串。只有显式 `CuaWindow` 可以截图或发送指针输入。原生 helper 在该门面之后保留自己的应用快照和可选窗口快照;原生层与门面快照相互独立。外部运行时继续负责变量持久化和最终表达式序列化;门面不加入 evaluator。[原生对象决定](2026-09-17-experimental-cua-object-api.zh.md)负责 evaluator 独立性,[共享 helper 决定](2026-10-09-cua-shared-native-helper.zh.md)负责连接生命期。 @@ -24,7 +24,7 @@ Provider 的启动能力是静态的。平台、支持的方法、应用级辅 **在共享基类中加入应用专属分支**会让窗口对象继承只适用于应用的决定和能力检查。由各作用域工厂注入自己的要求,可以让共享操作不依赖使用它的作用域。 -**打包的组合键字符串**需要一起解析按键名、分隔符和加号转义,并把平台别名归一化推入共享层。击键与方向是两种语义:`pressKey` 在一次调用中完成按下和释放,`sendKeyEvent` 描述一个显式方向。分开的按键和修饰键值让这些语义无需解析器。 +**打包的组合键字符串**需要一起解析按键名、分隔符和加号转义,并把平台别名归一化推入共享层。击键与方向是两种语义:`pressKey` 描述一次完整击键,`sendKeyEvent` 描述一个显式方向。分开的按键和修饰键值让这些语义无需解析器。 **在共享 schema 中枚举平台键盘按键**会把可移植的操作 schema 绑定到某个 provider 的按键名,并让每个平台都修改 schema。由 provider 定义字符串,平台可以解释自己的名称,共享 schema 保持中立。 diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index bb17939f06..00c45988de 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: f4206e2cb725c917 - zh: d10792bd8e7e242b + en: db5e8ad4d2ea832a + zh: 647cf55f4851760e /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 02b260705a..971acf4818 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -79,7 +79,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-experimental-cua-macos) lists all fields. Native tool calls use `{method, params}`; the complete method-specific schema is exposed to the model. `getApp` returns the `appHandle` used by every app-targeted operation, and `app.getWindow(windowId)` returns the object that owns screenshots and pointer input. -`pressKey(key, modifiers?)` accepts one key or a nonempty array of distinct physical keys. Aliases such as `Enter` and `Return` identify the same key. `pressKey(['w', 'd'])` presses W then D and releases D then W. Pass held modifiers separately, as in `pressKey('Tab', ['shift'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. In a multi-key chord, use `=` and pass Shift explicitly to apply it to the whole chord. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. +`pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. Each successful down remains active across subsequent tool calls in that execution. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. @@ -223,8 +223,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index f67195c67b..57c2f3f371 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -79,7 +79,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. [配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-experimental-cua-macos)列出全部字段。原生工具调用使用 `{method, params}`,模型可以看到每个方法的完整参数定义。`getApp` 返回每个面向应用的操作所需的 `appHandle`,`app.getWindow(windowId)` 返回负责截图和指针输入的对象。 -`pressKey(key, modifiers?)` 接受单个键名或由不同物理键组成的非空数组。`Enter` 和 `Return` 等别名指向同一个物理键。例如,`pressKey(['w', 'd'])` 依次按下 W、D,再依次松开 D、W。需要全程按住的修饰键单独传入,例如 `pressKey('Tab', ['shift'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。单独传入 `+` 或 `plus` 会发送 Shift 和等号。在多键组合中请使用 `=`,需要全程按住 Shift 时将其列入修饰键。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 +`pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。按下成功后,在同一次执行中调用其他工具时该键仍保持按下。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 @@ -223,8 +223,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 5e6adac2ce..58af404d5d 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2a69d89b7fc95998 zh: 084575bb31fb40dd /dsh-cua-native-helper/observation-and-input: - en: 851614a21ebfeb65 - zh: ff868b14dc77adb8 + en: 0bbc620165d868fa + zh: abe73bd9c7b8cc5d /dsh-cua-native-helper/verification: en: c87945aeec587bf5 zh: e5d69e4927e2fed3 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index cc1c046ca9..cc3a0de35f 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -103,7 +103,7 @@ Clicks send mouse-down and mouse-up events at the element center or the supplied Capture and pointer delivery read CG bounds before and after an exact-window AX frame query. Movement during the query returns WINDOW_CHANGED. Valid AX/CG frames must have equal outward-rounded integral point rectangles; a known mismatch returns WINDOW_CHANGED before mouse movement, priming or button delivery. The helper preserves both coordinate sources rather than substituting AX geometry for CG geometry. Missing or unusable AX geometry remains unknown, while AX communication, permission and invalid-element errors propagate. Capture without Accessibility permission retains its CG/SCK checks. Advertised AX actions bypass this pointer preflight; an AX action error does not trigger pointer input. These reads do not lock the window against later movement, and no geometry check activates or raises it. -`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses its modifiers followed by the requested keys in order, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. +`typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. Explicit up and cleanup verify the original process identity. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 73b7754b3a..1b0c3f406f 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -103,7 +103,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 截图和鼠标输入在精确窗口的 AX 边界查询前后读取 CG 边界,查询期间移动会返回 WINDOW_CHANGED。有效的 AX/CG 边界向外取整后必须一致;已知不一致会在移动、预备事件或按键发送前返回 WINDOW_CHANGED。helper 保留两个坐标来源,不用 AX 几何替换 CG 几何。缺失或无效的 AX 几何仍表示未知,AX 通信、权限和无效元素错误继续传递。无辅助功能权限的截图保留 CG/SCK 检查。声明的 AX 动作不经过鼠标预检,AX 动作失败也不改用鼠标输入。这些读取不会锁住窗口以阻止后续移动,几何检查不激活或抬起窗口。 -`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和指定按键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 +`typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。显式松键或执行结束时会核对原进程身份。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 80d820d0f1..1ebde9ee41 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -345,7 +345,7 @@ actor AXWorker { let recipient = try ax().keyboardRecipient(identity, catalog: catalog) try NativePlatform.verify(recipient) if method == "typeText" { try inputs().0.typeText(params.string("text"), to: recipient.pid) } - else { try inputs().0.pressKey(params.pressKeys(), modifiers: params.modifiers(), to: recipient.pid) } + else { try inputs().0.pressKey(params.string("key"), modifiers: params.modifiers(), to: recipient.pid) } case "setValue": try ax().setAttribute(element(handle, params), "AXValue", params.values["value"]) case "performAction": try ax().performAction(element(handle, params), action: params.string("action"), argument: params.values["argument"]) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index 91572fbd5f..1a7ca086ba 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -43,30 +43,15 @@ final class KeyboardInput { } /// Prepare every event before dispatch. On cancellation, release only the keys this call pressed. - func pressKey(_ keys: [String], modifiers: [String], to pid: Int32) throws { + func pressKey(_ name: String, modifiers: [String], to pid: Int32) throws { try checkCancellation() var chord = try modifiers.map(Self.modifier) - var namesByCode: [CGKeyCode: String] = [:] - for name in keys { - let key: Key - if name == "+" || name.lowercased() == "plus" { - guard keys.count == 1 else { - throw RequestParameters.invalid("For a multi-key chord, use = with an explicit shift modifier instead of \(name)") - } - chord.append(try Self.modifier("shift")) - key = Key(keyCode: try Self.keyCode("="), flag: []) - } else if let modifier = Self.namedModifier(name) { - key = modifier - } else { - key = Key(keyCode: try Self.keyCode(name), flag: []) - } - if let previous = namesByCode.updateValue(name, forKey: key.keyCode) { - throw RequestParameters.invalid("Keys '\(previous)' and '\(name)' name the same physical key") - } - chord.append(key) - } + let isPlus = name == "+" || name.lowercased() == "plus" + if isPlus { chord.append(try Self.modifier("shift")) } + let code = try Self.keyCode(isPlus ? "=" : name) + chord.append(Key(keyCode: code, flag: Self.namedModifier(name)?.flag ?? [])) let alreadyHeld = held.snapshot(pid: pid) - guard namesByCode.keys.allSatisfy({ alreadyHeld[$0] == nil }) else { + guard alreadyHeld[code] == nil else { throw RequestParameters.invalid("Release the held key before using it in pressKey") } var selected = Set(alreadyHeld.keys) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift index 6b69122d99..e3d64894c1 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/RequestAdmission.swift @@ -36,13 +36,6 @@ struct RequestParameters: Sendable { return path } } - func pressKeys() throws -> [String] { - switch values["key"] { - case .string(let name) where !name.isEmpty: return [name] - case .array(let items) where !items.isEmpty: return try strings("key") - default: throw Self.invalid("key must be a nonempty string or a nonempty array of key names") - } - } func optionalString(_ key: String) throws -> String? { contains(key) ? try string(key) : nil } func optionalBoolean(_ key: String) throws -> Bool? { guard let raw = values[key] else { return nil } diff --git a/packages/experimental/cua-macos/native/generate-protocol.ts b/packages/experimental/cua-macos/native/generate-protocol.ts index 29ccc58344..6dafb10d01 100644 --- a/packages/experimental/cua-macos/native/generate-protocol.ts +++ b/packages/experimental/cua-macos/native/generate-protocol.ts @@ -13,7 +13,9 @@ export function renderNativeProtocol(): { json: string; swift: string } { sendKeyEvent: z.object({ runId: z.string().min(1) }), mouseMove: z.object({ allowSystemPointer: z.boolean().optional() }), requestPermission: PermissionGuideParameters, openPermissionSettings: PermissionSettingsParameters, - }) + }, [z.object({ + method: z.literal('releaseHeldKeys'), params: z.object({ runId: z.string().min(1) }).strict(), + }).strict()]) const quoted = (values: Iterable) => [...values].sort().map(value => JSON.stringify(value)).join(', ') const swift = [ '// Generated by native/generate-protocol.ts from @deepseek-ai/dsh-cua/native-schema. Do not edit.', diff --git a/packages/experimental/cua-macos/native/protocol.schema.json b/packages/experimental/cua-macos/native/protocol.schema.json index f8a9824752..5c347ae54c 100644 --- a/packages/experimental/cua-macos/native/protocol.schema.json +++ b/packages/experimental/cua-macos/native/protocol.schema.json @@ -993,21 +993,8 @@ "maximum": 4294967295 }, "key": { - "anyOf": [ - { - "type": "string", - "minLength": 1 - }, - { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - ], - "description": "One key name or distinct physical keys to press in order and release in reverse." + "type": "string", + "minLength": 1 }, "modifiers": { "type": "array", @@ -1309,37 +1296,6 @@ ], "additionalProperties": false }, - { - "type": "object", - "properties": { - "id": { - "type": "string" - }, - "method": { - "type": "string", - "const": "releaseHeldKeys" - }, - "params": { - "type": "object", - "properties": { - "runId": { - "type": "string", - "minLength": 1 - } - }, - "required": [ - "runId" - ], - "additionalProperties": false - } - }, - "required": [ - "id", - "method", - "params" - ], - "additionalProperties": false - }, { "type": "object", "properties": { @@ -1500,6 +1456,37 @@ "params" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "method": { + "type": "string", + "const": "releaseHeldKeys" + }, + "params": { + "type": "object", + "properties": { + "runId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "runId" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "method", + "params" + ], + "additionalProperties": false } ] } diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 6649b82dd9..86f5cdef80 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -125,10 +125,12 @@ def check_clicks(helper, window, point, state_file): def check_keyboard(call, owner, state_file, state): count = len(state["events"]) - call("pressKey", {**owner, "key": ["w", "d"]}) - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) - chord = [(event["type"], event.get("keyCode")) for event in state["events"][count:]] - assert chord == [(10, 13), (10, 2), (11, 2), (11, 13)], chord + call("pressKey", {**owner, "key": ["w", "d"]}, "INVALID_ARGUMENT") + call("pressKey", {**owner, "key": "d", "modifiers": ["w"]}, "INVALID_ARGUMENT") + call("pressKey", {**owner, "key": "d", "modifiers": ["shift"]}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 2) + shortcut = [(event["type"], event.get("keyCode"), event["shift"]) for event in state["events"][count:]] + assert shortcut == [(10, 2, True), (11, 2, True)], shortcut count = len(state["events"]) def key(name, direction): @@ -189,7 +191,7 @@ def main(): pid = wait_for_state(state_file, lambda value: value["windowId"] > 0)["pid"] if args.keyboard_only: check_keyboard(call, owner, state_file, json.loads(state_file.read_text())) - print("PASS: W+D short press, two-second hold, independent D up and remaining W cleanup") + print("PASS: Shift+D shortcut, two-second W+D hold, independent D up and remaining W cleanup") return if not args.click_only: call("activate", owner) diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index 52cae6911e..f81b10d1da 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -4,49 +4,43 @@ import Darwin import Testing @testable import CuaNative -@Test(arguments: [ - (["w", "d"], ["shift"], [56, 13, 2, 2, 13, 56]), - (["shift", "w", "d"], [], [56, 13, 2, 2, 13, 56]), - (["a", "="], ["shift"], [56, 0, 24, 24, 0, 56]), -]) -func chordKeepsShiftThroughBothKeyReleases(_ keys: [String], _ modifiers: [String], _ codes: [Int64]) throws { +@Test func shortcutHoldsCommandAndShiftAroundOneKey() throws { var events: [CGEvent] = [] let input = KeyboardInput(post: { event, pid in #expect(pid == 42) events.append(event) }, textEventInterval: 0) - try input.pressKey(keys, modifiers: modifiers, to: 42) - #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == codes) - #expect(events.map(\.type) == [.flagsChanged, .keyDown, .keyDown, .keyUp, .keyUp, .flagsChanged]) - #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, true, false]) + try input.pressKey("s", modifiers: ["cmd", "shift"], to: 42) + #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [55, 56, 1, 1, 56, 55]) + #expect(events.map(\.type) == [.flagsChanged, .flagsChanged, .keyDown, .keyUp, .flagsChanged, .flagsChanged]) + #expect(events.map { $0.flags.contains(.maskShift) } == [false, true, true, true, false, false]) + #expect(events.map { $0.flags.contains(.maskCommand) } == [true, true, true, true, true, false]) } @Test(arguments: [1, 2]) -func cancelledChordReleasesOnlyPressedKeys(_ cancelAfter: Int) { +func cancelledShortcutReleasesOnlyPressedKeys(_ cancelAfter: Int) { let cancellation = CancellationLatch() var events: [CGEvent] = [] let input = KeyboardInput(post: { event, _ in events.append(event) if events.count == cancelAfter { cancellation.cancel() } }, textEventInterval: 0, checkCancellation: cancellation.check) - #expect(throws: NativeFailure.self) { try input.pressKey(["w", "d"], modifiers: [], to: 42) } - let held = [Int64(13), 2].prefix(cancelAfter) + #expect(throws: NativeFailure.self) { try input.pressKey("d", modifiers: ["shift"], to: 42) } + let held = [Int64(56), 2].prefix(cancelAfter) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == Array(held) + held.reversed()) - #expect(events.map(\.type) == Array(repeating: .keyDown, count: cancelAfter) + Array(repeating: .keyUp, count: cancelAfter)) + let types: [CGEventType] = cancelAfter == 1 ? [.flagsChanged, .flagsChanged] : [.flagsChanged, .keyDown, .keyUp, .flagsChanged] + #expect(events.map(\.type) == types) } @Test(arguments: [ - (["w", "unknown"], "Unknown key name: unknown"), - (["w", "W"], "Keys 'w' and 'W' name the same physical key"), - (["Enter", "Return"], "Keys 'Enter' and 'Return' name the same physical key"), - (["a", "+"], "For a multi-key chord, use = with an explicit shift modifier instead of +"), - (["Plus", "w"], "For a multi-key chord, use = with an explicit shift modifier instead of Plus"), + ("unknown", ["shift"], "Unknown key name: unknown"), + ("w", ["d"], "Unsupported key modifier: d"), ]) -func invalidChordPostsNoInput(_ keys: [String], _ message: String) throws { - let input = KeyboardInput(post: { _, _ in Issue.record("Invalid chord posted input") }, textEventInterval: 0) +func invalidShortcutPostsNoInput(_ key: String, _ modifiers: [String], _ message: String) throws { + let input = KeyboardInput(post: { _, _ in Issue.record("Invalid shortcut posted input") }, textEventInterval: 0) do { - try input.pressKey(keys, modifiers: ["shift"], to: 42) - Issue.record("Invalid chord was accepted") + try input.pressKey(key, modifiers: modifiers, to: 42) + Issue.record("Invalid shortcut was accepted") } catch let error as NativeFailure { #expect(error.code == "INVALID_ARGUMENT") #expect(error.message == message) @@ -57,7 +51,7 @@ func invalidChordPostsNoInput(_ keys: [String], _ message: String) throws { func plusAlonePressesShiftEquals(_ alias: String) throws { var events: [CGEvent] = [] let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0) - try input.pressKey([alias], modifiers: [], to: 42) + try input.pressKey(alias, modifiers: [], to: 42) #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 24, 24, 56]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, false]) } @@ -65,7 +59,7 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { @Test func standaloneShiftSetsItsFlagOnlyWhileHeld() throws { var events: [CGEvent] = [] let input = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0) - try input.pressKey(["shift"], modifiers: [], to: 42) + try input.pressKey("shift", modifiers: [], to: 42) #expect(events.map(\.type) == [.flagsChanged, .flagsChanged]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, false]) } @@ -82,8 +76,8 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { try input.keyDown("w", app: "editor", run: "two", recipient: target) #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: target) } #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two") } - #expect(throws: NativeFailure.self) { try input.pressKey(["w"], modifiers: [], to: target.pid) } - try input.pressKey(["d"], modifiers: ["shift"], to: target.pid) + #expect(throws: NativeFailure.self) { try input.pressKey("w", modifiers: [], to: target.pid) } + try input.pressKey("d", modifiers: ["shift"], to: target.pid) try input.releaseHeldKeys(run: "one") #expect(try input.keyUp("w", app: "editor", run: "two")) try input.releaseHeldKeys(run: "two") diff --git a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift index 85fa37aaf0..84a9fec849 100644 --- a/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/ProtocolTests.swift @@ -138,15 +138,3 @@ func rejectsMalformedApplicationIconPaths(_ value: String) throws { let request = try NativeRequest(data: Data("{\"id\":\"icons\",\"method\":\"applicationIcons\",\"params\":{\"paths\":\(value)}}".utf8)) #expect(throws: NativeFailure.self) { try RequestParameters(request).strings("paths") } } - -@Test func invalidPressKeyTypeNamesBothAcceptedForms() throws { - let request = try NativeRequest(data: Data(#"{"id":"call","method":"pressKey","params":{"key":7}}"#.utf8)) - let params = try RequestParameters(request) - do { - _ = try params.pressKeys() - Issue.record("Numeric key was admitted") - } catch let error as NativeFailure { - #expect(error.code == "INVALID_ARGUMENT") - #expect(error.message == "key must be a nonempty string or a nonempty array of key names") - } -} diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 2fe07ef025..6b2f073924 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -13,8 +13,8 @@ const methodDetails = new Map([ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { - if (method === 'pressKey') return `- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` + if (method === 'pressKey') return `${entry} +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/packages/experimental/cua-macos/tests/guidance.spec.ts b/packages/experimental/cua-macos/tests/guidance.spec.ts index 54322e2316..542dbe74bb 100644 --- a/packages/experimental/cua-macos/tests/guidance.spec.ts +++ b/packages/experimental/cua-macos/tests/guidance.spec.ts @@ -31,9 +31,8 @@ it('states the macOS accessibility, keyboard, and mouse levels', () => { expect(GUIDANCE).toContain("sendKeyEvent(key: string, direction: 'down' | 'up')") expect(GUIDANCE).toContain('returns, throws, or the user pauses') expect(COMMON_GUIDANCE).not.toContain('sendKeyEvent(') - expect(pressKey).toContain('key: string | string[]') - expect(pressKey).toContain("pressKey(['w', 'd']) presses W then D and releases D then W") - expect(pressKey).toContain("Packed strings such as 'w+d'") + expect(pressKey).toBe(COMMON_GUIDANCE.split('\n').find(line => line.startsWith('- pressKey('))) + expect(GUIDANCE).toContain('W down, D down, D up, W up') const hover = GUIDANCE.split('\n').find(line => line.startsWith('- mouseMove(')) for (const term of ['AXShowAlternateUI', 'AXShowDefaultUI', 'HOVER_UNAVAILABLE', 'systemPointerHover']) expect(hover).toContain(term) const click = GUIDANCE.split('\n').find(line => line.startsWith('- click(')) diff --git a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts index aefc6fbee6..78135ed0c2 100644 --- a/packages/experimental/cua-macos/tests/protocol-generation.spec.ts +++ b/packages/experimental/cua-macos/tests/protocol-generation.spec.ts @@ -21,6 +21,13 @@ describe('native protocol generation', () => { expect(validate({ id: 'invalid', method: 'setValue', params: target })).toBe(false) }) + it('rejects a key array at both model and native pressKey admission', () => { + const request = { method: 'pressKey', params: { appHandle: 'app', key: ['w', 'd'] } } + expect(Request.safeParse(request).success).toBe(false) + const validate = new Ajv2020().compile(JSON.parse(renderNativeProtocol().json)) + expect(validate({ id: 'shortcut', ...request })).toBe(false) + }) + it.each([ { method: 'getState', params: { appHandle: 'app', maxElements: 1 } }, { method: 'drag', params: { appHandle: 'app', windowId: 1, fromX: 1, fromY: 1, toX: 2, toY: 2, steps: 1 } }, @@ -28,6 +35,7 @@ describe('native protocol generation', () => { { method: 'paste', params: { appHandle: 'app', text: 'text', pasteReadTimeoutMs: 1000 } }, { method: 'mouseMove', params: { appHandle: 'app', windowId: 1, x: 0, y: 0, allowSystemPointer: true } }, { method: 'findApps', params: { query: 'Editor', maxAppMatches: 1 } }, + { method: 'releaseHeldKeys', params: { runId: 'execution' } }, { method: 'launchApp', params: { appHandle: 'pending' } }, { method: 'applicationIcons', params: { paths: ['/Applications/Fixture.app'] } }, { method: 'permissionStatus', params: {} }, diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index 8587d8c7d5..f4abb13c43 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -21,8 +21,8 @@ en: d92d5948a7941e8d zh: d43491ae6521b87e /deepseek-ai-dsh-cua/understand-the-implementation: - en: 181158347d09c629 - zh: 231b2dcaf826d386 + en: 2ab74a1ff120459e + zh: 39b3ef198989f133 /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 9fb8f64eb7..c95e4ae8ec 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -91,7 +91,7 @@ One object facade ([src/api.ts](src/api.ts)) builds a shared `CuaSurface` and de Provider startup capabilities are fixed at installation: platform, methods, app-level accessibility, keyboard scopes, browser support, and coordinate space. The native `getCapabilities` RPC reports runtime permissions and session lock only; `installCua` merges both layers for the model-visible result. The raw RPC remains a common operation representation rather than a capability inventory, so provider guidance states the actions its platform supports. -Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` holds the listed modifiers while pressing the requested keys in order and releasing them in reverse. For example, `pressKey(['w', 'd'])` holds W through the D keystroke. `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. +Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` for the supported operations and input scopes. `pressKey(key, modifiers?)` presses and releases one key while holding the listed modifiers; `sendKeyEvent(key, direction)` sends exactly one key-down or key-up. `typeText` and `paste` deliver literal text at the provider's declared keyboard scope. Keyboard modifier names are plain strings that the provider interprets. Platform providers import `CuaConfigFields` from `@deepseek-ai/dsh-cua/config` to extend the shared configuration. The root Host entry exports `installCua`, `CuaConfig`, and the Typert-discovered `CuaAccess` service; its `apply()` only marks the optional Client contribution. `/client` loads the permission UI through the existing module loader. Separate Host and Client compiler projects keep React, CSS, and browser registrations out of headless imports. `/api` owns the app/window API and its types; `/bridge`, `/native-client`, and `/protocol` retain runtime and platform consumers. `/types` exports only the named types required by generated Remote declarations. The Client uses package-local types. `/typert` supplies Host reflection and `/remote` supplies generated browser descriptors and codecs; permission authority remains on the Host. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index 2f8e31b77c..c1c5ed863c 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -91,7 +91,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 提供方启动能力在安装时固定:平台、方法、应用级辅助功能、键盘作用域、浏览器支持和坐标空间。原生 `getCapabilities` RPC 只报告运行时权限和会话锁定状态;`installCua` 为模型可见结果合并两层。原生 RPC 仍是通用操作表示,而不是能力清单,因此 provider 指引说明其平台支持的动作。 -通过 `await cua.getCapabilities()` 返回的 `methods` 和 `keyboard` 确认支持的操作和输入范围。`pressKey(key, modifiers?)` 按住所列修饰键,依次按下指定的键,再逆序释放。例如,`pressKey(['w', 'd'])` 在按下和松开 D 期间持续按住 W。`sendKeyEvent(key, direction)` 只发送一次按下或抬起。`typeText` 和 `paste` 在 provider 声明的键盘作用域内传送字面文本。键盘修饰键名称是 provider 解释的普通字符串。 +通过 `await cua.getCapabilities()` 返回的 `methods` 和 `keyboard` 确认支持的操作和输入范围。`pressKey(key, modifiers?)` 在按住所列修饰键时按下并释放一个键;`sendKeyEvent(key, direction)` 只发送一次按下或抬起。`typeText` 和 `paste` 在 provider 声明的键盘作用域内传送字面文本。键盘修饰键名称是 provider 解释的普通字符串。 平台提供方从 `@deepseek-ai/dsh-cua/config` 导入 `CuaConfigFields` 来扩展共享配置。根 Host 入口导出 `installCua`、`CuaConfig` 和供 Typert 发现的 `CuaAccess` 服务,`apply()` 只标记可选 Client 贡献。`/client` 通过现有模块加载器加载权限界面。Host 和 Client 使用独立编译项目,headless 导入不会加载 React、CSS 或浏览器注册。`/api` 提供应用、窗口 API 及其类型;`/bridge`、`/native-client` 和 `/protocol` 保留运行时和平台消费者。`/types` 仅导出生成 Remote 声明所需的命名类型,Client 使用包内类型。`/typert` 提供 Host 反射,`/remote` 提供浏览器描述和编解码,权限判断仍由 Host 执行。 diff --git a/packages/experimental/cua/src/native-schema.ts b/packages/experimental/cua/src/native-schema.ts index a6122ed71e..5bb061383f 100644 --- a/packages/experimental/cua/src/native-schema.ts +++ b/packages/experimental/cua/src/native-schema.ts @@ -14,15 +14,19 @@ function variants(schema: Schema): Schema[] { return schema.anyOf ?? schema.oneO /** * Derive native request schemas and admission fields from the shared operation definitions. * @param platformFields Additional native protocol fields accepted by the provider. + * @param privateOperations Additional provider-only request schemas. * @returns Native field and enum tables and the complete wire schema. */ -export function nativeProtocol(platformFields: Partial['method'] | 'requestPermission' | 'openPermissionSettings', z.ZodObject>> = {}): { +export function nativeProtocol( + platformFields: Partial['method'] | 'requestPermission' | 'openPermissionSettings', z.ZodObject>> = {}, + privateOperations: readonly z.ZodObject[] = [], +): { fields: Map> enums: Map>> json: string } { const resources = new Map(Object.entries({ ...NativeResourceParameters, ...platformFields })) - const schemas = [...Request.options, ...NativeOnlyOperations] + const schemas = [...Request.options, ...NativeOnlyOperations, ...privateOperations] .map(schema => z.toJSONSchema(schema)) const fields = new Map>() const enums = new Map>>() diff --git a/packages/experimental/cua/src/protocol.ts b/packages/experimental/cua/src/protocol.ts index e4de9f4734..538c95cfe6 100644 --- a/packages/experimental/cua/src/protocol.ts +++ b/packages/experimental/cua/src/protocol.ts @@ -62,10 +62,7 @@ export const Request = z.discriminatedUnion('method', [ selectionType: z.enum(['text', 'cursor_before', 'cursor_after']).optional() }), operation('typeText', { ...app, windowId: id.optional(), text: z.string() }), operation('paste', { ...app, windowId: id.optional(), text: z.string(), format: z.enum(['text', 'html']).optional() }), - operation('pressKey', { ...app, windowId: id.optional(), - key: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]) - .describe('One key name or distinct physical keys to press in order and release in reverse.'), - modifiers: z.array(z.string()).optional() }), + operation('pressKey', { ...app, windowId: id.optional(), key: z.string().min(1), modifiers: z.array(z.string()).optional() }), operation('sendKeyEvent', { ...app, windowId: id.optional(), key: z.string().min(1), direction: z.enum(['down', 'up']) }), z.object({ method: z.literal('scroll'), params: z.union([ z.object({ ...absoluteCoordinate, @@ -93,7 +90,7 @@ export const NativeResourceParameters = { } /** Host-only launch continuation and user-facing system permission controls; absent from model arguments. */ export const NativeOnlyOperations = [ - operation('launchApp', app), operation('releaseHeldKeys', { runId: z.string().min(1) }), operation('permissionStatus', {}), + operation('launchApp', app), operation('permissionStatus', {}), operation('applicationIcons', { paths: z.array(z.string().min(1)) }), operation('requestPermission', { permission: z.enum(['accessibility', 'screenRecording']) }), operation('openPermissionSettings', { permission: z.enum(['accessibility', 'screenRecording']) }), diff --git a/packages/experimental/cua/src/types.ts b/packages/experimental/cua/src/types.ts index ca34f16e2c..b84663f9e2 100644 --- a/packages/experimental/cua/src/types.ts +++ b/packages/experimental/cua/src/types.ts @@ -160,16 +160,16 @@ export interface CuaSurface { */ paste(text: string, options?: CuaPasteOptions): Promise /** - * Press the keys in order at the current focus, then release them in reverse order. + * Press and release one key at the current input focus. * Rejects when the provider does not support keyboard input at this scope. - * @param key - One provider-defined key name or a nonempty array of distinct physical keys to hold together. + * @param key - Provider-defined key name to press and release; not a chord. * @param modifiers - Platform- or provider-defined modifier names held for this keystroke; omitted means none. * @returns Whether the provider successfully executed the requested operation. */ - pressKey(key: string | string[], modifiers?: string[]): Promise + pressKey(key: string, modifiers?: string[]): Promise /** * Send one key-down or key-up event at the current input focus. - * On macOS, down persists within one run_code until explicit up, program completion (including errors), or user pause. + * Does not send the opposite event. * Rejects when the provider does not support keyboard input at this scope. * @param key - Platform-defined key name; modifier keys may themselves be targets. * @param direction - Explicit event direction; the opposite event is never sent implicitly. diff --git a/packages/experimental/cua/tests/api.spec.ts b/packages/experimental/cua/tests/api.spec.ts index f5b3452dc3..cbaa419951 100644 --- a/packages/experimental/cua/tests/api.spec.ts +++ b/packages/experimental/cua/tests/api.spec.ts @@ -683,8 +683,6 @@ describe('input actions', () => { ['fractional scroll', ({ window }) => window.scroll({ x: 0, y: 0, deltaLinesX: 0.5, deltaLinesY: 0 })], ['negative drag point', ({ window }) => window.drag([0, 0], [-1, 3])], ['empty key', ({ app }) => app.pressKey('')], - ['empty chord', ({ app }) => app.pressKey([])], - ['empty chord member', ({ app }) => app.pressKey(['w', ''])], ] it.each<[string, (surfaces: Surfaces) => Promise]>([ ['getState windowId: Too small: expected number to be >0', ({ app }) => app.getWindow(0)], @@ -710,8 +708,7 @@ describe('input actions', () => { expect(f.dispatch).toHaveBeenCalledTimes(calls) }) - it.each<[string | string[], string[] | undefined, string[]]>([ - [['w', 'd'], undefined, []], + it.each<[string, string[] | undefined, string[]]>([ ['+', undefined, []], ['plus', [], []], ['+', ['command'], ['command']], diff --git a/packages/experimental/cua/tests/protocol.spec.ts b/packages/experimental/cua/tests/protocol.spec.ts index c3d69e309c..50fb329c07 100644 --- a/packages/experimental/cua/tests/protocol.spec.ts +++ b/packages/experimental/cua/tests/protocol.spec.ts @@ -12,8 +12,6 @@ const rejectedRequests: Array<{ reason: string; request: JsonValue }> = [ { reason: 'numeric element id', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: 0 } } }, { reason: 'coordinate click without a window', request: { method: 'click', params: { appHandle: 'app', x: 1, y: 2 } } }, { reason: 'mixed element and coordinate click', request: { method: 'click', params: { appHandle: 'app', snapshotId: 'snapshot', elementId: '0', windowId: 23, x: 1, y: 2 } } }, - { reason: 'empty pressKey chord', request: { method: 'pressKey', params: { appHandle: 'app', key: [] } } }, - { reason: 'non-string pressKey chord member', request: { method: 'pressKey', params: { appHandle: 'app', key: ['w', 7] } } }, { reason: 'non-string pressKey modifier', request: { method: 'pressKey', params: { appHandle: 'app', key: 'a', modifiers: ['command', 7] } } }, { reason: 'sendKeyEvent modifiers', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a', direction: 'down', modifiers: [] } } }, { reason: 'sendKeyEvent without direction', request: { method: 'sendKeyEvent', params: { appHandle: 'app', key: 'a' } } }, @@ -25,11 +23,6 @@ it.each(rejectedRequests)('rejects $reason at operation admission', ({ request } expect(Request.safeParse(request).success).toBe(false) }) -it('admits an ordered chord in a raw pressKey request', () => { - const request = { method: 'pressKey', params: { appHandle: 'app', key: ['w', 'd'] } } - expect(Request.parse(request)).toEqual(request) -}) - it('admits arbitrary provider-defined pressKey modifier names', () => { const request = { method: 'pressKey', params: { appHandle: 'app', key: 'PlatformKey', modifiers: ['platform-modifier', 'shift'] } } expect(Request.parse(request)).toEqual(request) diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 82210fa306..e8deb643fb 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -78,8 +78,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 3a94712d06..33f3636750 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -1032,21 +1032,8 @@ "maximum": 4294967295 }, "key": { - "anyOf": [ - { - "type": "string", - "minLength": 1 - }, - { - "minItems": 1, - "type": "array", - "items": { - "type": "string", - "minLength": 1 - } - } - ], - "description": "One key name or distinct physical keys to press in order and release in reverse." + "type": "string", + "minLength": 1 }, "modifiers": { "type": "array", diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 3acaa30b88..5322aa44d7 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -80,8 +80,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index dc18435318..4c5b91329b 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -80,8 +80,8 @@ A string target is an element id; coordinate targets are [x, y] and are pixels i Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. -- pressKey(key: string | string[], modifiers?: string[]) -> ActionResult — use for a short press. pressKey(['w', 'd']) presses W then D and releases D then W. Each name identifies one physical key. Packed strings such as 'w+d', unknown names and duplicate physical keys are rejected before input. Pass held modifiers separately, as in pressKey('Tab', ['shift']). '+' and 'plus' mean Shift+= when used alone. In a multi-key chord use '=' and pass 'shift' explicitly if needed. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once to hold a key across tool calls within one run_code. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From e2237f26b94ebe1e3412f32fa9ec373c8f8dae10 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 14:23:33 +0800 Subject: [PATCH 093/103] feat(forge): show each changed file as a card A file's trailing collapsed-context strip, the next file's header, and that file's leading strip read as three adjacent rows, so the boundary between files was hard to see. Each file is now a card with an R16 border and a gap before the next one, and its header takes a tint over the view background. The header still sticks to the top of the scroll area while its lines scroll, flush with the edge rather than inside the list's padding. The collapsed-context strips keep their style. Resolves #8104 --- .../client-ui-forge/README.i18n.yaml | 4 +-- .../experimental/client-ui-forge/README.md | 2 +- .../experimental/client-ui-forge/README.zh.md | 2 +- .../src/client/ChangesTab.module.css | 32 ++++++++++++++++--- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 5b25741184..d8c84dfd57 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 05ee6d9ba0b8d2c7 - zh: 98c988e8f957511f + en: 8d017c771840d6de + zh: 0705332c947f825a /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: 7495fe1e0d0ee643 zh: f820a5790ae6e2a7 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 27ff8a01c3..67966cf983 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -38,7 +38,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. - **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 4aca1d2c38..0bdfdea790 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -38,7 +38,7 @@ kind: "package-reference" - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 - **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index f664c4b2fa..ae8a40f3f8 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -346,9 +346,12 @@ } .files { + --forge-files-inset: 10px; flex: 1; + box-sizing: border-box; min-width: 0; min-height: 0; + padding: var(--forge-files-inset); overflow: auto; } @@ -377,14 +380,34 @@ text-align: center; } +/* Each file is one card, so a file's last collapsed-context strip and the next file's header no longer read as adjacent + rows. Diffs share R16; clip, unlike hidden, keeps the card from becoming the sticky header's scroll container. */ .file { - border-bottom: 0.5px solid var(--dsw-alias-border-l3); + overflow: clip; + border: 0.5px solid var(--dsw-alias-border-l4); + border-radius: var(--dsw-radius-lg); + background: var(--forge-changes-bg); } -/* Above the comment plus (z-index 1) of rows scrolled beneath it. */ +.file + .file { + margin-top: 12px; +} + +@container forge-changes (max-width: 380px) { + .files { + --forge-files-inset: 6px; + } + + .file + .file { + margin-top: 8px; + } +} + +/* Above the comment plus (z-index 1) of rows scrolled beneath it. Sticky offsets start inside the list's padding, + so the negative inset keeps a stuck header flush with the scroll area's top edge. */ .fileHeader { position: sticky; - top: 0; + top: calc(-1 * var(--forge-files-inset, 0px)); z-index: 2; display: flex; align-items: center; @@ -393,7 +416,8 @@ min-height: 36px; padding: 0 4px 0 8px; border-bottom: 0.5px solid var(--dsw-alias-border-l3); - background: var(--forge-changes-bg); + /* The hover tint over the view background stays opaque while code scrolls beneath the sticky header. */ + background: linear-gradient(var(--dsw-alias-interactive-bg-hover), var(--dsw-alias-interactive-bg-hover)), var(--forge-changes-bg); } /* A bare chevron: its rotation shows whether the file is expanded, so it takes no fill in any state. */ From dd5cda398ceb95fd50e1c3310a7fd429e9c8cf66 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 14:47:29 +0800 Subject: [PATCH 094/103] feat(cua-macos): send owner key repeats and explain conflicting holds --- .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 4 +- packages/experimental/cua-macos/README.zh.md | 4 +- .../cua-macos/native/README.i18n.yaml | 4 +- .../experimental/cua-macos/native/README.md | 2 +- .../cua-macos/native/README.zh.md | 2 +- .../native/Sources/CuaNative/AXWorker.swift | 12 +++- .../native/Sources/CuaNative/HeldKeys.swift | 46 +++++++++++--- .../Sources/CuaNative/KeyboardInput.swift | 20 +++--- .../native/tests/CapabilitiesFixture.swift | 7 ++- .../native/tests/capabilities_e2e.py | 13 +++- .../tests/swift/KeyboardChordTests.swift | 61 +++++++++++++++++-- .../experimental/cua-macos/src/guidance.ts | 2 +- .../cua-native/system-prompt.expected.md | 2 +- .../session/cua-ptc/system-prompt.expected.md | 2 +- .../system-prompt.expected.md | 2 +- 16 files changed, 146 insertions(+), 41 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 00c45988de..1be5a7abd9 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: db5e8ad4d2ea832a - zh: 647cf55f4851760e + en: 83d4eb62d0d0db2f + zh: 3afde1c3b8c25211 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 971acf4818..26a218c40d 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -81,7 +81,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-exper `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. Each successful down remains active across subsequent tool calls in that execution. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. +For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. The first down holds the key across subsequent tool calls. For an ordinary key already held by this execution, each additional down sends one key-down marked as a repeat to the original process. Choose the interval between calls. One up releases the key. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 57c2f3f371..a40be5399b 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -81,7 +81,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。按下成功后,在同一次执行中调用其他工具时该键仍保持按下。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 +长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久,松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 58af404d5d..57420b0348 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2a69d89b7fc95998 zh: 084575bb31fb40dd /dsh-cua-native-helper/observation-and-input: - en: 0bbc620165d868fa - zh: abe73bd9c7b8cc5d + en: c6787eda94ba4833 + zh: 855e3c6432918775 /dsh-cua-native-helper/verification: en: c87945aeec587bf5 zh: e5d69e4927e2fed3 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index cc3a0de35f..51d0a7b131 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -105,7 +105,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. Explicit up and cleanup verify the original process identity. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. +The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. A repeated down from the owner posts one key-down with `keyboardEventAutorepeat` set and reuses the existing record. Repeats, explicit up and cleanup verify the original process identity. A conflicting down or up reports the key and whether another session or another run holds it. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index 1b0c3f406f..eef79a770f 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -105,7 +105,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。显式松键或执行结束时会核对原进程身份。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 +宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,发送一次带 `keyboardEventAutorepeat` 标志的按下事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift index 1ebde9ee41..b8121fee03 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/AXWorker.swift @@ -215,7 +215,12 @@ actor AXWorker { return .result(Self.actionResult) } if method == "sendKeyEvent", try params.string("direction") == "up" { - let dispatched = try inputs().0.keyUp(params.string("key"), app: params.string("appHandle"), run: params.string("runId")) + let handle = try params.string("appHandle") + let dispatched = try inputs().0.keyUp(params.string("key"), app: handle, run: params.string("runId")) { + try NativePlatform.requireUnlocked(observeSession()) + try NativePlatform.requireAccessibility() + return try ax().keyboardRecipient(validateIdentity(handle), catalog: catalog) + } return .result(.object(["dispatched": .bool(dispatched)])) } let locked = observeSession() @@ -339,8 +344,9 @@ actor AXWorker { readTimeout: .milliseconds(try params.integer("pasteReadTimeoutMs", in: 1...2147483647)), maxElements: try params.integer("maxElements", in: 1...10000), maxDepth: try params.integer("maxDepth", in: 1...100))) case "sendKeyEvent": - let recipient = try ax().keyboardRecipient(identity, catalog: catalog) - try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId"), recipient: recipient) + try inputs().0.keyDown(params.string("key"), app: handle, run: params.string("runId")) { + try ax().keyboardRecipient(identity, catalog: catalog) + } case "typeText", "pressKey": let recipient = try ax().keyboardRecipient(identity, catalog: catalog) try NativePlatform.verify(recipient) diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift index 47c34fbe2a..06f47981d2 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift @@ -26,11 +26,34 @@ final class HeldKeys: @unchecked Sendable { lock.withLock { Dictionary(uniqueKeysWithValues: pressed.filter { $0.recipient.pid == pid }.map { ($0.code, $0.flag) }) } } - func down(owner: Owner, recipient: ProcessIdentity, code: CGKeyCode, flag: CGEventFlags, + private func conflict(_ name: String, holder: Owner, caller: Owner) -> NativeFailure { + let source: String + if holder.connection != caller.connection { source = "another session" } + else if holder.run != caller.run { source = "another run_code execution" } + else { source = "a different application handle in this run_code" } + return RequestParameters.invalid("Key '\(name)' is held for this target by \(source). No event was sent. Wait for the holder to release it or for its run_code to end.") + } + + /// Repeats use the saved recipient even when the selected application's focused panel has changed. + func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { + try lock.withLock { + guard let key = pressed.first(where: { $0.owner == owner && $0.code == code }) else { return false } + guard down.type == .keyDown else { + throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") + } + try NativePlatform.verify(key.recipient) + down.flags = flags(for: key.recipient) + down.setIntegerValueField(.keyboardEventAutorepeat, value: 1) + post(down, key.recipient.pid) + return true + } + } + + func down(owner: Owner, recipient: ProcessIdentity, name: String, code: CGKeyCode, flag: CGEventFlags, down: CGEvent, up: CGEvent, post: (CGEvent, Int32) -> Void) throws { try lock.withLock { - guard !pressed.contains(where: { $0.code == code && ($0.owner == owner || $0.recipient.pid == recipient.pid) }) else { - throw RequestParameters.invalid("Key is already held for this target") + if let key = pressed.first(where: { $0.code == code && $0.recipient.pid == recipient.pid }) { + throw conflict(name, holder: key.owner, caller: owner) } pressed.append(Press(owner: owner, recipient: recipient, code: code, flag: flag, up: up)) down.flags = flags(for: recipient) @@ -56,13 +79,20 @@ final class HeldKeys: @unchecked Sendable { return true } - func up(owner: Owner, code: CGKeyCode, post: (CGEvent, Int32) -> Void) throws -> Bool { - try lock.withLock { - guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { - throw RequestParameters.invalid("This run has not pressed that key for this application") - } + func up(owner: Owner, name: String, code: CGKeyCode, recipientIfUnheld: () throws -> ProcessIdentity, + post: (CGEvent, Int32) -> Void) throws -> Bool { + let dispatched = try lock.withLock { () throws -> Bool? in + guard let index = pressed.firstIndex(where: { $0.owner == owner && $0.code == code }) else { return nil } return try release(at: index, post: post) } + if let dispatched { return dispatched } + let recipient = try recipientIfUnheld() + throw lock.withLock { + if let key = pressed.first(where: { $0.code == code && $0.recipient == recipient }) { + return conflict(name, holder: key.owner, caller: owner) + } + return RequestParameters.invalid("Key '\(name)' is not held for this target. Send 'down' in this run_code before 'up'.") + } } func release(connection: UUID, run: String?, post: (CGEvent, Int32) -> Void) throws { diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift index 1a7ca086ba..b435d4e46b 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/KeyboardInput.swift @@ -22,20 +22,24 @@ final class KeyboardInput { self.checkCancellation = checkCancellation } - func keyDown(_ name: String, app: String, run: String, recipient: ProcessIdentity) throws { - let modifier = Self.namedModifier(name) + func keyDown(_ name: String, app: String, run: String, recipient: () throws -> ProcessIdentity) throws { + let owner = HeldKeys.Owner(connection: connection, run: run, app: app) let code = try Self.keyCode(name) let source = try Self.source() let down = try Self.keyEvent(source: source, code: code, down: true, flags: []) + try checkCancellation() + if try held.repeatIfHeld(owner: owner, name: name, code: code, down: down, post: post) { return } + let target = try recipient() let up = try Self.keyEvent(source: source, code: code, down: false, flags: []) try checkCancellation() - try NativePlatform.verify(recipient) - try held.down(owner: .init(connection: connection, run: run, app: app), recipient: recipient, - code: code, flag: modifier?.flag ?? [], down: down, up: up, post: post) + try NativePlatform.verify(target) + try held.down(owner: owner, recipient: target, name: name, code: code, flag: Self.namedModifier(name)?.flag ?? [], + down: down, up: up, post: post) } - func keyUp(_ name: String, app: String, run: String) throws -> Bool { - try held.up(owner: .init(connection: connection, run: run, app: app), code: Self.keyCode(name), post: post) + func keyUp(_ name: String, app: String, run: String, recipientIfUnheld: () throws -> ProcessIdentity) throws -> Bool { + try held.up(owner: .init(connection: connection, run: run, app: app), name: name, code: Self.keyCode(name), + recipientIfUnheld: recipientIfUnheld, post: post) } func releaseHeldKeys(run: String? = nil) throws { @@ -52,7 +56,7 @@ final class KeyboardInput { chord.append(Key(keyCode: code, flag: Self.namedModifier(name)?.flag ?? [])) let alreadyHeld = held.snapshot(pid: pid) guard alreadyHeld[code] == nil else { - throw RequestParameters.invalid("Release the held key before using it in pressKey") + throw RequestParameters.invalid("Key '\(name)' is already held for this target. Use pressKey after the run_code that holds it releases it.") } var selected = Set(alreadyHeld.keys) var flags = alreadyHeld.values.reduce(CGEventFlags()) { $0.union($1) } diff --git a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift index 1151468790..d937c35ac2 100644 --- a/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift +++ b/packages/experimental/cua-macos/native/tests/CapabilitiesFixture.swift @@ -85,8 +85,11 @@ final class CapabilitiesFixture: NSObject, NSApplicationDelegate, NSWindowDelega guard let self else { return } var value: [String: Any] = ["type": event.type.rawValue, "timestamp": event.timestamp, "flags": event.modifierFlags.rawValue, "shift": event.modifierFlags.contains(.shift), "command": event.modifierFlags.contains(.command)] - if [.keyDown, .keyUp].contains(event.type) { value["keyCode"] = event.keyCode; value["characters"] = event.characters ?? "" } - else { value["button"] = event.buttonNumber } + if [.keyDown, .keyUp].contains(event.type) { + value["keyCode"] = event.keyCode + value["characters"] = event.characters ?? "" + value["repeat"] = event.isARepeat + } else { value["button"] = event.buttonNumber } self.events.append(value) self.persist() } diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 86f5cdef80..66dd004700 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -150,6 +150,17 @@ def check_keyboard(call, owner, state_file, state): state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 4) assert [(e["type"], e["keyCode"]) for e in state["events"][count:]] == [(10, 13), (10, 2), (11, 2), (11, 13)] + for explicit_up in (True, False): + count = len(state["events"]) + key("w", "down") + key("w", "down") + if explicit_up: + key("w", "up") + call("releaseHeldKeys", {"runId": "held-input"}) + state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 3) + repeat = [(e["type"], e["keyCode"], e["repeat"]) for e in state["events"][count:]] + assert repeat == [(10, 13, False), (10, 13, True), (11, 13, False)], repeat + def main(): parser = argparse.ArgumentParser() @@ -191,7 +202,7 @@ def main(): pid = wait_for_state(state_file, lambda value: value["windowId"] > 0)["pid"] if args.keyboard_only: check_keyboard(call, owner, state_file, json.loads(state_file.read_text())) - print("PASS: Shift+D shortcut, two-second W+D hold, independent D up and remaining W cleanup") + print("PASS: Shift+D shortcut, two-second W+D hold, independent D up, explicit W repeat and one final up") return if not args.click_only: call("activate", owner) diff --git a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift index f81b10d1da..a971328ce3 100644 --- a/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift +++ b/packages/experimental/cua-macos/native/tests/swift/KeyboardChordTests.swift @@ -72,15 +72,66 @@ func plusAlonePressesShiftEquals(_ alias: String) throws { #expect(pid == target.pid) events.append(event) }, textEventInterval: 0, held: held) - try input.keyDown("shift", app: "editor", run: "one", recipient: target) - try input.keyDown("w", app: "editor", run: "two", recipient: target) - #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: target) } - #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two") } + try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) + #expect(throws: NativeFailure.self) { try input.keyDown("shift", app: "editor", run: "one", recipient: { target }) } + try input.keyDown("w", app: "editor", run: "two", recipient: { target }) + #expect(throws: NativeFailure.self) { try input.keyDown("W", app: "editor", run: "one", recipient: { target }) } + #expect(throws: NativeFailure.self) { try input.keyUp("w", app: "other", run: "two", recipientIfUnheld: { target }) } #expect(throws: NativeFailure.self) { try input.pressKey("w", modifiers: [], to: target.pid) } try input.pressKey("d", modifiers: ["shift"], to: target.pid) try input.releaseHeldKeys(run: "one") - #expect(try input.keyUp("w", app: "editor", run: "two")) + #expect(try input.keyUp("w", app: "editor", run: "two", recipientIfUnheld: { target })) try input.releaseHeldKeys(run: "two") #expect(events.map { $0.getIntegerValueField(.keyboardEventKeycode) } == [56, 13, 2, 2, 56, 13]) #expect(events.map { $0.flags.contains(.maskShift) } == [true, true, true, true, false, false]) } + +@Test(arguments: [true, false]) +func repeatedDownUsesOriginalRecipientAndOneRelease(_ explicitUp: Bool) throws { + let target = try NativePlatform.identity(getpid()) + var events: [CGEvent] = [] + let input = KeyboardInput(post: { event, pid in + #expect(pid == target.pid) + events.append(event) + }, textEventInterval: 0) + func changedFocus() throws -> ProcessIdentity { + throw RequestParameters.invalid("The repeat or release looked up a new recipient") + } + try input.keyDown("w", app: "editor", run: "one", recipient: { target }) + try input.keyDown("W", app: "editor", run: "one", recipient: changedFocus) + if explicitUp { #expect(try input.keyUp("w", app: "editor", run: "one", recipientIfUnheld: changedFocus)) } + try input.releaseHeldKeys(run: "one") + #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) + #expect(events.map { $0.getIntegerValueField(.keyboardEventAutorepeat) } == [0, 1, 0]) +} + +@Test func foreignSessionCannotRepeatOrReleaseTheOwnersKey() throws { + let target = try NativePlatform.identity(getpid()) + let held = HeldKeys() + var events: [CGEvent] = [] + let a = KeyboardInput(post: { event, _ in events.append(event) }, textEventInterval: 0, held: held) + let b = KeyboardInput(post: { _, _ in Issue.record("Non-owner dispatched an event") }, textEventInterval: 0, held: held) + try a.keyDown("w", app: "a", run: "same-run-id", recipient: { target }) + for direction in ["down", "up"] { + do { + if direction == "down" { try b.keyDown("W", app: "b", run: "same-run-id", recipient: { target }) } + else { _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) } + Issue.record("Non-owner was allowed to send an event") + } catch let failure as NativeFailure { + #expect(failure.code == "INVALID_ARGUMENT") + #expect(failure.message.contains("Key 'W' is held for this target by another session")) + #expect(failure.message.contains("Wait for the holder to release it")) + } + } + try b.releaseHeldKeys() + try a.keyDown("W", app: "a", run: "same-run-id", recipient: { target }) + try a.releaseHeldKeys() + #expect(events.map(\.type) == [.keyDown, .keyDown, .keyUp]) + do { + _ = try b.keyUp("W", app: "b", run: "same-run-id", recipientIfUnheld: { target }) + Issue.record("Unheld key was released") + } catch let failure as NativeFailure { + #expect(failure.code == "INVALID_ARGUMENT") + #expect(failure.message.contains("Key 'W' is not held for this target")) + } +} diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 6b2f073924..839eb56a3c 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -14,7 +14,7 @@ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { if (method === 'pressKey') return `${entry} -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index e8deb643fb..a01916dbe2 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -79,7 +79,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 5322aa44d7..ef5ce31b6d 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 4c5b91329b..9c072b94ea 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' once per key to hold one or more keys across tool calls within one run_code, for example W down, D down, D up, W up. Holding a physical key on a keyboard can produce repeated key-down events after a delay. This method posts one event per call and rejects a second 'down' for a held key. Use the app's response to decide what to do while holding the key and when to send 'up'. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From 6cc45f22bd9c3c569da9210389c927ebd6901319 Mon Sep 17 00:00:00 2001 From: Dudu-0223 Date: Sat, 7 Nov 2026 14:55:25 +0800 Subject: [PATCH 095/103] =?UTF-8?q?feat:=20=E5=9C=A8=E5=86=85=E7=BD=AE?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E4=B8=AD=E5=85=B3=E9=97=AD=20subagent=20?= =?UTF-8?q?=E5=92=8C=20Team=20=E7=9A=84=20interrupt=20=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=20(#7986)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(subagent): disable interrupt tool by default * test(subagent): update remaining default tool inventories * fix: disable agent interruption in shipped configuration * test: configure interruption explicitly in custom preset fixture * test: update tool count in collapse display snapshots * docs: clarify agent interruption opt-in and verify preset controls * test: cover macOS CUA channel policy forwarding on every platform * test: move CUA coverage repair to a separate master change --- .../parent.expected.jsonl | 4 +- apps/cli/tests/web-agent-presets.e2e.ts | 51 +- apps/web/tests/shipped-composition.e2e.ts | 1 - .../guide.i18n.yaml | 16 + .../subagent-interrupt-default/guide.md | 27 + .../subagent-interrupt-default/guide.zh.md | 27 + packages/bundle/base/README.i18n.yaml | 4 +- packages/bundle/base/README.md | 2 + packages/bundle/base/README.zh.md | 2 + packages/bundle/base/cordis.patch.yml | 2 + packages/bundle/web-app/README.i18n.yaml | 4 +- packages/bundle/web-app/README.md | 2 + packages/bundle/web-app/README.zh.md | 2 + .../bundle/web-app/presets/cordis.patch.yml | 2 + packages/bundle/web-app/presets/ptc.patch.yml | 2 + .../bundle/web-app/presets/standard.patch.yml | 2 + packages/team/agent-team/README.i18n.yaml | 4 +- packages/team/agent-team/README.md | 2 +- packages/team/agent-team/README.zh.md | 2 +- .../dynamic-tools/tool-history.json | 3 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../system-prompt.expected.md | 8 - .../notifications.expected.jsonl | 6 +- .../sdk/dynamic-tool-updates/session.v4.jsonl | 6 +- snapshots/sdk/plan-review/session.v4.jsonl | 10 +- .../plan-review/tool-schemas.expected.json | 1936 ++++++++--------- .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../notifications.expected.jsonl | 4 +- .../sdk/tool-error-details/session.v4.jsonl | 4 +- .../system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../advanced-toolchain/session.v4.jsonl | 8 +- .../system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 32 - .../tool-schemas.expected.json | 32 - .../tool-schemas.expected.json | 16 - .../both-mode-turn/system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 32 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../cua-native/tool-schemas.expected.json | 16 - .../session/cua-ptc/system-prompt.expected.md | 8 - .../session.v4.jsonl | 6 +- .../dynamic-tool-updates/session.v4.jsonl | 6 +- .../tool-schemas.expected.json | 48 - .../tool-schemas.expected.json | 16 - .../in-history-series-start/session.v4.jsonl | 6 +- .../lsp-definition/tool-schemas.expected.json | 16 - .../system-prompt.expected.md | 8 - .../mcp-resources/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../office-authoring-checker/session.v4.jsonl | 4 +- .../session.v4.jsonl | 4 +- .../tool-schemas.expected.json | 32 - .../system-prompt.expected.md | 16 - .../office-render-tools/writer.expected.jsonl | 4 +- .../session/office-skills/session.v4.jsonl | 4 +- .../office-skills/tool-schemas.expected.json | 32 - .../tool-schemas.expected.json | 16 - .../session.v4.jsonl | 6 +- .../plugin-manager-mcp/session.v4.jsonl | 4 +- .../tool-schemas.expected.json | 32 - .../plugin-manager/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../ptc-persistent/system-prompt.expected.md | 8 - .../system-prompt.expected.md | 8 - .../ptc-python-turn/system-prompt.expected.md | 10 - .../ptc-read-image/system-prompt.expected.md | 8 - .../system-prompt.expected.md | 8 - .../ptc-turn/system-prompt.expected.md | 8 - .../tool-schemas.expected.json | 16 - .../pwsh-tool-turn/tool-schemas.expected.json | 16 - .../ralph-loop/tool-schemas.1.expected.json | 16 - .../ralph-loop/tool-schemas.2.expected.json | 16 - .../ralph-loop/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.1.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../cordis.snapshot.yml | 2 + .../subagent-no-message-tool/cordis.yml | 2 + .../tool-schemas.1.expected.json | 16 - .../session/team-targets/cordis.snapshot.yml | 4 + snapshots/session/team-targets/cordis.yml | 4 + .../tool-schemas.expected.json | 16 - .../text-turn/tool-schemas.expected.json | 16 - .../web-fetch/tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../worktree/tool-schemas.expected.json | 16 - .../collapse-timing/next-message.expected.md | 2 +- .../web/collapse-timing/verbose.expected.md | 2 +- .../creation-recommendations/session.v4.jsonl | 4 +- .../tool-schemas.expected.json | 32 - .../tool-schemas.expected.json | 16 - .../tool-schemas.expected.json | 16 - .../system-prompt.expected.md | 8 - .../system-prompt.expected.md | 8 - .../plugin-recommendations/session.v4.jsonl | 4 +- .../tool-schemas.expected.json | 32 - .../web/ptc-round/system-prompt.expected.md | 8 - 120 files changed, 1133 insertions(+), 2328 deletions(-) create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md diff --git a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl index 311240e645..a7352b5dd7 100644 --- a/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl +++ b/apps/cli/tests/profiles/headless/tests/expected/subagent-inheritance/parent.expected.jsonl @@ -17,8 +17,8 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[2],"surfaceOp":{"op":"replace","startSeq":2,"endSeq":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Delegate the write probe to a subagent."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} -{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"resume","startsSeries":true}} +{"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Tighten this session to read-only.","messageSeqs":[3],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"delegate-write","name":"subagent","args":["{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"delegate-write","name":"subagent","arguments":"{\"description\": \"Delegated write probe\", \"prompt\": \"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} diff --git a/apps/cli/tests/web-agent-presets.e2e.ts b/apps/cli/tests/web-agent-presets.e2e.ts index 14be185017..ac293e8017 100644 --- a/apps/cli/tests/web-agent-presets.e2e.ts +++ b/apps/cli/tests/web-agent-presets.e2e.ts @@ -289,6 +289,55 @@ describe('the shipped Web composition', () => { expect(ctx.agentPresets.defaultId).toBe('standard') }) + it.each(['standard', 'cordis', 'ptc'] as const)('keeps interruption disabled in %s with Team mode off or on', async (preset) => { + const handle = await ctx.agents.create({ + sessionId: SessionId(`preset-interrupt-${preset}`), + setup: agentCtx => ctx.agentPresets.mount(agentCtx, preset).then(() => undefined), + }) + try { + for (const enabled of [false, true]) { + await ctx.agentTeams.setEnabled(handle.agent, enabled) + const names = toolNames(ctx, handle.agent) + expect(names).not.toContain('interrupt_agent') + expect(names).toEqual(expect.arrayContaining(['send_message', 'list_agents', 'wait_agent'])) + } + } finally { + await handle.dispose() + } + }) + + it.each(['standard', 'cordis', 'ptc'] as const)('restores interruption through a complete %s declaration override', async (preset) => { + const root = await mkdtemp(join(tmpdir(), 'dsh-preset-interrupt-')) + onTestFinished(() => rm(root, { recursive: true, force: true })) + const declaration = composeEntries([webPatches('interrupt migration')]) + .find(row => row.id === `preset-${preset}`)!.config as { + id: string + order: number + plugins: import('@deepseek-ai/cordis-plugin-loader').EntryOptions[] + } + const configured = await bootWeb(root, [{ + id: `preset-${preset}`, + config: { + ...declaration, + plugins: composeEntries([[{ insert: declaration.plugins }, { + id: 'tool-subagent-control', config: { interrupt: true }, + }]]), + }, + }]) + try { + const handle = await configured.agents.create({ + sessionId: SessionId(`preset-interrupt-enabled-${preset}`), + setup: agentCtx => configured.agentPresets.mount(agentCtx, preset).then(() => undefined), + }) + try { + expect(toolNames(configured)).not.toContain('interrupt_agent') + expect(toolNames(configured, handle.agent)).toEqual(expect.arrayContaining([ + 'interrupt_agent', 'send_message', 'list_agents', 'wait_agent', + ])) + } finally { await handle.dispose() } + } finally { await configured.fiber.dispose() } + }) + it('composes the full agent from `standard`', async () => { const handle = await ctx.agents.create({ sessionId: SessionId('preset-standard'), @@ -302,7 +351,7 @@ describe('the shipped Web composition', () => { // depend on ripgrep being present on the machine. expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([ 'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode', - 'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', + 'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'send_message', 'skill', 'subagent', 'subagent_fork', 'team_task_create', 'team_task_get', 'team_task_list', 'team_task_update', 'todo_write', 'update_goal', 'wait_agent', 'web_fetch', 'web_search', diff --git a/apps/web/tests/shipped-composition.e2e.ts b/apps/web/tests/shipped-composition.e2e.ts index 36b74d0e88..35a08e5fb2 100644 --- a/apps/web/tests/shipped-composition.e2e.ts +++ b/apps/web/tests/shipped-composition.e2e.ts @@ -479,7 +479,6 @@ const EXPECTED_TOOLS = [ 'edit', 'exit_plan_mode', 'get_goal', - 'interrupt_agent', 'job_kill', 'job_list', 'job_output', diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml new file mode 100644 index 0000000000..fb72a12add --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md +/: + en: fda192f58c50cd90 + zh: 2ebe5d7389eb9689 +/built-in-configurations-disable-agent-interruption: + en: c253388db5ba6f5a + zh: af138bbc7bfd31b4 +/built-in-configurations-disable-agent-interruption/change: + en: 76b23fa746332e06 + zh: d30315eab3aa53bd +/built-in-configurations-disable-agent-interruption/migration: + en: 0f5bd67305b455dc + zh: a98770b64686d612 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md new file mode 100644 index 0000000000..ddcd5a2149 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "Built-in configurations disable interrupt_agent for subagents and Team mode." +--- + +# Built-in configurations disable agent interruption + +English | [中文](guide.zh.md) + +## Change + +The base bundle and the Web `standard`, `cordis`, and `ptc` presets now set `config.interrupt: false` on their `tool-subagent-control` rows. Models using these configurations no longer receive `interrupt_agent`, including in Team mode. Messaging, discovery, inbox waiting, and the subagent service interruption API remain available. The plugin's own default remains `true`; independent compositions that omit the setting retain interruption. + +## Migration + +Keep `interrupt: false` to retain the built-in behavior. To restore interruption: + +1. Edit `$DSH_HOME/profiles//cordis.patch.yml`. For base-backed profiles such as `headless`, `sdk`, and `acp`, append: + + ```yaml + - id: tool-subagent-control + config: + interrupt: true + ``` + +2. For `web` or `desktop`, instead override each required declaration: `preset-standard`, `preset-cordis`, or `preset-ptc`. Copy that declaration's complete `config` from the installed `@deepseek-ai/dsh-web-app` bundle's `presets/.patch.yml` (source: [standard](../../../../packages/bundle/web-app/presets/standard.patch.yml), [cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml), [ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml)). If your profile already overrides the declaration, edit that override to preserve your customizations. A patch replaces the whole `config`: retain `id`, `order`, and the entire `plugins` list, including the `delegation` group. Within that group's `config`, change the `tool-subagent-control` row's `config.interrupt` to `true`. Use the declaration's outer ID as the patch target, following [Change a shipped preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset). A top-level patch targeting `tool-subagent-control` does not reach the preset's child row; it only changes the disabled Host row. Leave that Host row disabled. +3. Restart the profile and create a new Session using the changed preset; existing Sessions retain their preset revision. Confirm that the model's tool definitions include `interrupt_agent`, `send_message`, `list_agents`, and `wait_agent`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md new file mode 100644 index 0000000000..7f9455936a --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md @@ -0,0 +1,27 @@ +--- +kind: upgrade-guide +description: "内置配置关闭普通 subagent 和 Team 模式的 interrupt_agent。" +--- + +# 内置配置关闭 agent 中断 + +[English](guide.md) | 中文 + +## 变更 + +base 组合包及 Web 的 `standard`、`cordis`、`ptc` preset 现在为各自的 `tool-subagent-control` 行设置 `config.interrupt: false`。使用这些配置的模型不再获得 `interrupt_agent`,也包括 Team 模式。消息、发现、收件箱等待和 subagent 服务的中断 API 仍然可用。插件自身的默认值仍为 `true`;省略该设置的独立组合仍提供中断工具。 + +## 迁移 + +保留 `interrupt: false` 可维持内置行为。如需恢复中断工具: + +1. 编辑 `$DSH_HOME/profiles//cordis.patch.yml`。对于 `headless`、`sdk`、`acp` 等基于 base 的 profile,追加: + + ```yaml + - id: tool-subagent-control + config: + interrupt: true + ``` + +2. 对于 `web` 或 `desktop`,改为覆盖需要启用的声明行:`preset-standard`、`preset-cordis` 或 `preset-ptc`。从已安装的 `@deepseek-ai/dsh-web-app` 组合包的 `presets/.patch.yml` 中复制该声明的完整 `config`(源码:[standard](../../../../packages/bundle/web-app/presets/standard.patch.yml)、[cordis](../../../../packages/bundle/web-app/presets/cordis.patch.yml)、[ptc](../../../../packages/bundle/web-app/presets/ptc.patch.yml))。如果 profile 已经覆盖该声明,编辑已有覆盖以保留自定义配置。patch 会替换整个 `config`:保留 `id`、`order` 和完整的 `plugins` 列表,包括 `delegation` 组。在该组的 `config` 内,将 `tool-subagent-control` 行的 `config.interrupt` 改为 `true`。以声明的外层 ID 为 patch 目标,写法参见[修改内置 preset](../../../../packages/preset/agent-preset/skills/dsh-doc/references/compositions.md#change-a-shipped-preset)。顶层以 `tool-subagent-control` 为目标的 patch 无法修改 preset 内的子行,只会修改已禁用的 Host 行。保持该 Host 行禁用。 +3. 重启 profile,并使用修改后的 preset 创建新 Session;已有 Session 保留原 preset 修订。确认模型的工具定义包含 `interrupt_agent`、`send_message`、`list_agents` 和 `wait_agent`。 diff --git a/packages/bundle/base/README.i18n.yaml b/packages/bundle/base/README.i18n.yaml index b475ce9b82..bd859ea112 100644 --- a/packages/bundle/base/README.i18n.yaml +++ b/packages/bundle/base/README.i18n.yaml @@ -21,8 +21,8 @@ en: 0f971f7ac7c09139 zh: ceb866da681c709c /deepseek-ai-dsh-base/use-this-package/what-you-get: - en: ab2fb279cdd726c5 - zh: ae84c61bddc00ddf + en: dd7e69c32d06cb6a + zh: 9301140a8e023b41 /deepseek-ai-dsh-base/use-this-package/shell-tools-per-platform: en: 2dce12f82d6ee955 zh: d4599eb899a3cd88 diff --git a/packages/bundle/base/README.md b/packages/bundle/base/README.md index 5b5f163694..b2ab5dcf1e 100644 --- a/packages/bundle/base/README.md +++ b/packages/bundle/base/README.md @@ -53,6 +53,8 @@ Both `subagent` and `subagent_fork` create managed children and return the child The bundle also mounts [Agent Teams](../../team/agent-team/README.md) and its task tools. Team mode defaults off per root Session; the root conversation’s **Use Agent Teams** menu switch enables collaboration for that tree without changing the profile. +The `tool-subagent-control` row sets `interrupt: false`, so ordinary subagents and Team mode omit `interrupt_agent`. Set `config.interrupt: true` on that row in a later patch to enable it. The plugin itself still defaults to `true`. + The built-in `working_directory` tool changes the directory for subsequent operations while existing processes and write permissions remain independent. Current directory information appears in user context. Default file editing uses `read`, `write`, and `edit`. The `str_replace_editor` tool remains available as an explicit opt-in. To add it to a base-backed profile, put this entry in the profile, home, or invocation patch: ```yaml diff --git a/packages/bundle/base/README.zh.md b/packages/bundle/base/README.zh.md index 62d6ad03b9..223b88bb0a 100644 --- a/packages/bundle/base/README.zh.md +++ b/packages/bundle/base/README.zh.md @@ -53,6 +53,8 @@ kind: "package-bundle" 此 bundle 还挂载 [Agent Teams](../../team/agent-team/README.zh.md) 及其任务工具。每个根 Session 的 Team 模式默认关闭;根会话菜单中的**使用智能体团队**开关为当前树开启协作,无需修改 profile。 +`tool-subagent-control` 行显式设置 `interrupt: false`,因此普通 subagent 和 Team 模式均不提供 `interrupt_agent`。在后续 patch 中为该行设置 `config.interrupt: true` 可启用它。插件自身的默认值仍为 `true`。 + 内置 `working_directory` 工具改变后续操作使用的目录,已有进程与写权限保持独立。当前目录信息出现在用户上下文中。默认文件编辑使用 `read`、`write` 和 `edit`。`str_replace_editor` 工具仍可显式启用。要将它加入基于 base 的 profile,请在 profile、home 或逐次调用 patch 中添加以下条目: ```yaml diff --git a/packages/bundle/base/cordis.patch.yml b/packages/bundle/base/cordis.patch.yml index 26082074f3..18286618f9 100644 --- a/packages/bundle/base/cordis.patch.yml +++ b/packages/bundle/base/cordis.patch.yml @@ -385,6 +385,8 @@ # separately loaded follow-up tool registers the one global `send_message`. - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' diff --git a/packages/bundle/web-app/README.i18n.yaml b/packages/bundle/web-app/README.i18n.yaml index cef33b6aac..1a650beec8 100644 --- a/packages/bundle/web-app/README.i18n.yaml +++ b/packages/bundle/web-app/README.i18n.yaml @@ -21,8 +21,8 @@ en: e3cac911f080d8ef zh: 60749e9f5c39c1bc /deepseek-ai-dsh-web-app/use-this-package/configuration: - en: b1787804544f2587 - zh: ce09d2c248ffd999 + en: f876c60a37e3cb0e + zh: 42a535554fe4bc40 /deepseek-ai-dsh-web-app/use-this-package/listening-trust-and-public-deployments: en: e6ddea1d2fc40501 zh: ff08b6fa3fc24136 diff --git a/packages/bundle/web-app/README.md b/packages/bundle/web-app/README.md index d80b45463d..aed6c22d91 100644 --- a/packages/bundle/web-app/README.md +++ b/packages/bundle/web-app/README.md @@ -61,6 +61,8 @@ The `minimal` agent preset uses a persistent shell, the `read_image` tool, and a The generated [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-web-app) lists this runtime plugin's accepted fields and their JSDoc. The shipped composition inserts the `schedule` service row and the `ui-schedule` task page row, while the clock reading and the four reminder tools belong to the `standard`, `cordis`, and `ptc` presets. The `tool-subagent` and `tool-subagent-fork` rows in those presets deny the four tools, so a delegated child's scope never lists them. +The `standard`, `cordis`, and `ptc` presets set `config.interrupt: false` on their `tool-subagent-control` rows. To expose `interrupt_agent`, including in Team mode, override the relevant preset declaration as described in the [migration steps](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.md); changing the disabled Host row does not change preset tools. + ### Listening, trust, and public deployments diff --git a/packages/bundle/web-app/README.zh.md b/packages/bundle/web-app/README.zh.md index 8952c0d315..80b1fd2216 100644 --- a/packages/bundle/web-app/README.zh.md +++ b/packages/bundle/web-app/README.zh.md @@ -61,6 +61,8 @@ dsh --profile web --no-open --port 8080 生成的[配置目录](../../../docs/config-catalog.zh.md#deepseek-aidsh-web-app)列出了本运行时插件接受的字段及其 JSDoc。随发行版交付的组合插入 `schedule` 服务行与 `ui-schedule` 任务页面行,时钟读数与四个提醒工具则属于 `standard`、`cordis` 与 `ptc` 三个 preset。这三个 preset 的 `tool-subagent` 与 `tool-subagent-fork` 两行都 deny 这四个工具,因此被委派子 agent 的作用域不会列出它们。 +`standard`、`cordis` 和 `ptc` 三个 preset 在各自的 `tool-subagent-control` 行中设置 `config.interrupt: false`。如需提供 `interrupt_agent`(也适用于 Team 模式),按[迁移步骤](../../../docs/upgrade-guide/v0.2.2-rc.1/subagent-interrupt-default/guide.zh.md)覆盖相应 preset 声明;修改已禁用的 Host 行不会改变 preset 的工具。 + ### 监听、信任与公开部署 diff --git a/packages/bundle/web-app/presets/cordis.patch.yml b/packages/bundle/web-app/presets/cordis.patch.yml index d0c9f7f419..912fb7d3ac 100644 --- a/packages/bundle/web-app/presets/cordis.patch.yml +++ b/packages/bundle/web-app/presets/cordis.patch.yml @@ -90,6 +90,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/bundle/web-app/presets/ptc.patch.yml b/packages/bundle/web-app/presets/ptc.patch.yml index 86ccc4f0ad..7a9329e5db 100644 --- a/packages/bundle/web-app/presets/ptc.patch.yml +++ b/packages/bundle/web-app/presets/ptc.patch.yml @@ -91,6 +91,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/bundle/web-app/presets/standard.patch.yml b/packages/bundle/web-app/presets/standard.patch.yml index d0bca7e336..a3532d0f3a 100644 --- a/packages/bundle/web-app/presets/standard.patch.yml +++ b/packages/bundle/web-app/presets/standard.patch.yml @@ -94,6 +94,8 @@ config: - id: tool-subagent-control name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: tool-subagent name: '@deepseek-ai/dsh-tool-subagent' config: diff --git a/packages/team/agent-team/README.i18n.yaml b/packages/team/agent-team/README.i18n.yaml index 2f1733cd95..3d527874a8 100644 --- a/packages/team/agent-team/README.i18n.yaml +++ b/packages/team/agent-team/README.i18n.yaml @@ -33,8 +33,8 @@ en: 27e822116b00ca32 zh: b49fa665c72692bf /deepseek-ai-dsh-agent-team/use-this-package/waiting-and-interruption: - en: 3c43a806d94f9294 - zh: 04b04e009759c9ce + en: 2d266b76e6fea2a7 + zh: 4c829e65ba77e406 /deepseek-ai-dsh-agent-team/use-this-package/what-success-and-failure-look-like: en: 36814f2b06dc2359 zh: c46af795bc89942f diff --git a/packages/team/agent-team/README.md b/packages/team/agent-team/README.md index a58392c1c3..665cb0e487 100644 --- a/packages/team/agent-team/README.md +++ b/packages/team/agent-team/README.md @@ -80,7 +80,7 @@ File hints produce warnings when two in-progress tasks plan to touch overlapping The standard `wait_agent` tool waits for the exact caller’s next-step inbox and works without Team mode; see [subagent controls](../../subagent/tool-subagent-control/README.md#wait_agent). Task changes and Team mode changes do not end waits, add inbox input, or start idle Agents. Use `send_message` when an Agent needs to act on an update. -An ancestor stops a descendant’s current turn with the standard `interrupt_agent` tool. Interruption keeps unclaimed queued messages and leaves task ownership unchanged. +When the [subagent control plugin](../../subagent/tool-subagent-control/README.md#use-this-package) enables `config.interrupt`, an ancestor can stop a descendant’s current turn with `interrupt_agent`. Built-in configurations disable this tool by default. Interruption keeps unclaimed queued messages and leaves task ownership unchanged. ### What success and failure look like diff --git a/packages/team/agent-team/README.zh.md b/packages/team/agent-team/README.zh.md index 9e57943fa1..4e8db32d87 100644 --- a/packages/team/agent-team/README.zh.md +++ b/packages/team/agent-team/README.zh.md @@ -80,7 +80,7 @@ kind: "package-reference" 标准 `wait_agent` 工具等待当前调用者的下一步收件箱,无需 Team 模式即可使用;参见 [subagent 控制工具](../../subagent/tool-subagent-control/README.zh.md#wait_agent)。任务变化和 Team 模式切换不会结束等待、添加收件箱输入或启动空闲 Agent。需要 Agent 处理更新时使用 `send_message`。 -祖先通过标准 `interrupt_agent` 工具停止后代的当前轮次。中断保留尚未认领的排队消息,也不改变任务归属。 +当 [subagent 控制插件](../../subagent/tool-subagent-control/README.zh.md#use-this-package)启用 `config.interrupt` 时,祖先可通过 `interrupt_agent` 停止后代的当前轮次。内置配置默认关闭此工具。中断保留尚未认领的排队消息,也不改变任务归属。 ### 成功与失败的表现 diff --git a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json index 91ecd5ad13..fd5e22c70b 100644 --- a/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json +++ b/scripts/snapshots/python-sdk-single-exe/dynamic-tools/tool-history.json @@ -52,7 +52,6 @@ "get_goal", "glob", "grep", - "interrupt_agent", "job_kill", "job_list", "job_output", @@ -116,7 +115,6 @@ "get_goal", "glob", "grep", - "interrupt_agent", "job_kill", "job_list", "job_output", @@ -195,7 +193,6 @@ "get_goal", "glob", "grep", - "interrupt_agent", "job_kill", "job_list", "job_output", diff --git a/snapshots/sdk/background-wait-steer/tool-schemas.expected.json b/snapshots/sdk/background-wait-steer/tool-schemas.expected.json index e1d6aa4ee7..3c3f4d2cc9 100644 --- a/snapshots/sdk/background-wait-steer/tool-schemas.expected.json +++ b/snapshots/sdk/background-wait-steer/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/command-attachments/tool-schemas.expected.json b/snapshots/sdk/command-attachments/tool-schemas.expected.json index 61d3f590fb..85bc6d2cf7 100644 --- a/snapshots/sdk/command-attachments/tool-schemas.expected.json +++ b/snapshots/sdk/command-attachments/tool-schemas.expected.json @@ -266,22 +266,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/desktop-context/tool-schemas.expected.json b/snapshots/sdk/desktop-context/tool-schemas.expected.json index 5f29906dab..1209423422 100644 --- a/snapshots/sdk/desktop-context/tool-schemas.expected.json +++ b/snapshots/sdk/desktop-context/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md index 5e1feff690..98d3bca7f1 100644 --- a/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md +++ b/snapshots/sdk/desktop-ptc-context/system-prompt.expected.md @@ -142,11 +142,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -493,9 +488,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl b/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl index 463007668f..252ed9695e 100644 --- a/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl +++ b/snapshots/sdk/dynamic-tool-updates/notifications.expected.jsonl @@ -7,7 +7,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":10,"time":0,"data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":12,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":13,"time":0,"data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":14,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} @@ -15,14 +15,14 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":16,"time":0,"data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{sessionId}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[15],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":17,"time":0,"data":{"turn":1,"step":1}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":18,"time":0,"data":{"turn":1,"step":2}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":19,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":19,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":20,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":19},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":21,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":22,"time":0,"data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/result","seq":23,"time":0,"data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{sessionId}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":24,"time":0,"data":{"turn":1,"step":2}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":25,"time":0,"data":{"turn":1,"step":3}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":26,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":26,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":27,"time":0,"data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{sessionId}}"}},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":28,"time":0,"data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/end","seq":29,"time":0,"data":{"turn":1,"step":3}}}} diff --git a/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl b/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl index 6818a03e2c..9731e89b0b 100644 --- a/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl +++ b/snapshots/sdk/dynamic-tool-updates/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1793796109297,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796109297,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1793796109297,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1793796109297,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1793796109297,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,14 +18,14 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:6}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1793796109316,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796109316,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1793796109316,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1793796109316,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1793796109334,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1793796109334,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1793796109334,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1793796109334,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1793796109334,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/sdk/plan-review/session.v4.jsonl b/snapshots/sdk/plan-review/session.v4.jsonl index 5911c994ea..064eee20d6 100644 --- a/snapshots/sdk/plan-review/session.v4.jsonl +++ b/snapshots/sdk/plan-review/session.v4.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Reply SDK_PLAN_INITIAL without tools.","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":14}} @@ -29,7 +29,7 @@ {"type":"system/message","data":{"turn":2,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:9}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"user/message","data":{"content":[{"type":"text","text":"The user switched this session to plan mode."}],"source":{"kind":"plan-mode","form":"notice","summary":"The user switched this session to plan mode."},"role":"user","id":"{{message:7}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Prepare a plan through exit_plan_mode; revise after feedback and acknowledge approval."}],"source":{"kind":"user"},"role":"user","id":"{{message:8}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} {"type":"developer/message","data":{"turn":2,"step":1,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"exit_plan_mode"}],"role":"developer","id":"{{message:10}}"},"headerSeq":30},"surfaceOp":"append"} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":31}} {"type":"assistant/message","data":{"turn":2,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:11}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-1","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-1","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} @@ -45,7 +45,7 @@ {"type":"plan/mode","data":{"active":false}} {"type":"step/start","data":{"turn":2,"step":3}} {"type":"system/message","data":{"turn":2,"step":3,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:15}}"}},"sourceEventSeqs":[27],"surfaceOp":{"op":"replace","startSeq":27,"endSeq":27}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":46}} {"type":"assistant/message","data":{"turn":2,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"SDK_PLAN_APPROVED"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"text"}]}},"id":"{{message:16}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792108800000,"index":0,"dt":[],"texts":["SDK_PLAN_APPROVED"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"SDK_PLAN_APPROVED"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":2,"step":3}} @@ -62,7 +62,7 @@ {"type":"system/message","data":{"turn":3,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:19}}"}},"sourceEventSeqs":[45],"surfaceOp":{"op":"replace","startSeq":45,"endSeq":45}} {"type":"user/message","data":{"content":[{"type":"text","text":"The user switched this session to plan mode."}],"source":{"kind":"plan-mode","form":"notice","summary":"The user switched this session to plan mode."},"role":"user","id":"{{message:17}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Present another plan for review."}],"source":{"kind":"user"},"role":"user","id":"{{message:18}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":63}} {"type":"assistant/message","data":{"turn":3,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"commands-tool-4","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}},"id":"{{message:20}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-4","name":"exit_plan_mode","args":[""]},{"type":"tool-call-chunks","time0":1792108800000,"index":0,"dt":[],"id":"commands-tool-4","args":["{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"commands-tool-4","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":3,"step":1,"callId":"commands-tool-4","name":"exit_plan_mode","arguments":"{\"plan\": \"# Implement the change\\n\\n- Inspect existing code.\\n- Make the smallest change.\\n- Run focused tests.\"}"}} @@ -81,7 +81,7 @@ {"type":"system/message","data":{"turn":4,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:24}}"}},"sourceEventSeqs":[60],"surfaceOp":{"op":"replace","startSeq":60,"endSeq":60}} {"type":"user/message","data":{"content":[{"type":"text","text":"The user switched this session back to the default mode."}],"source":{"kind":"plan-mode","form":"notice","summary":"The user switched this session back to the default mode."},"role":"user","id":"{{message:22}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Reply SDK_PLAN_OK without tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:23}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","exit_plan_mode","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"series"}} {"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{session:1}}","sessionFormatVersion":4,"throughSeq":82}} {"type":"assistant/message","data":{"turn":4,"step":1,"message":{"role":"assistant","content":[{"type":"text","text":"SDK_PLAN_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"text"}]}},"id":"{{message:25}}"},"usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032},"stream":[{"type":"chunk","time":1792108800000,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792108800000,"index":0,"dt":[],"texts":["SDK_PLAN_OK"]},{"type":"chunk","time":1792108800000,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"SDK_PLAN_OK"}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"usage","usage":{"inputTokens":10000,"outputTokens":32,"totalTokens":10032}}},{"type":"chunk","time":1792108800000,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":4,"step":1}} diff --git a/snapshots/sdk/plan-review/tool-schemas.expected.json b/snapshots/sdk/plan-review/tool-schemas.expected.json index 13159a8596..07f6cdbbe1 100644 --- a/snapshots/sdk/plan-review/tool-schemas.expected.json +++ b/snapshots/sdk/plan-review/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -1208,18 +1192,942 @@ } }, { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", + "name": "job_kill", + "description": "Request cancellation of a running background job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "reason": { + "type": "string", + "description": "Optional short reason, recorded in the log and forwarded to the job." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "job_list", + "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "job_output", + "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", + "parameters": { + "type": "object", + "properties": { + "job_id": { + "type": "string", + "description": "Job id returned by the tool that started the background work." + }, + "wait": { + "type": "boolean", + "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." + }, + "timeout_ms": { + "type": "number", + "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." + } + }, + "required": [ + "job_id" + ] + } + }, + { + "name": "list_agents", + "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "plugin_manager", + "description": "List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.", + "parameters": { + "type": "object", + "properties": { + "action": { + "type": "string", + "description": "Management operation.", + "enum": [ + "list_plugins", + "list_bundles", + "set_plugin", + "set_bundle", + "install_bundle", + "remove_bundle", + "list_version_exemptions", + "set_version_exemption" + ] + }, + "target": { + "type": "string", + "description": "Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle." + }, + "enabled": { + "type": "boolean", + "description": "Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes." + }, + "runtimeVersion": { + "type": "string", + "description": "For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range." + }, + "acceptRisk": { + "type": "boolean", + "description": "For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough." + }, + "approvedBuilds": { + "type": "array", + "description": "For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile.", + "items": { + "type": "string" + } + }, + "registry": { + "type": "string", + "description": "For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable." + }, + "offset": { + "type": "number", + "description": "Zero-based list offset; defaults to 0." + }, + "limit": { + "type": "number", + "description": "List page size, from 1 to 100; defaults to 25." + } + }, + "required": [ + "action" + ] + } + }, + { + "name": "present", + "description": "Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied.", + "parameters": { + "type": "object", + "properties": { + "files": { + "type": "array", + "description": "Usually the 1-2 most important deliverables; at most 4 per call.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "path": { + "type": "string", + "description": "Path of an existing regular file. Relative paths use the Session working directory." + }, + "description": { + "type": "string", + "description": "Brief description for the user." + } + }, + "required": [ + "path" + ] + } + } + }, + "required": [ + "files" + ] + } + }, + { + "name": "read", + "description": "Read a UTF-8 text file and return line-numbered content.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to read, resolved by the filesystem backend." + }, + "offset": { + "type": "number", + "description": "1-based first line to return. Defaults to 1." + }, + "limit": { + "type": "number", + "description": "Maximum number of lines to return. Defaults to 2000." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "read_image", + "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to the image file, resolved by the filesystem backend." + } + }, + "required": [ + "file_path" + ] + } + }, + { + "name": "schedule_create", + "description": "Create a scheduled task. At each occurrence of rrule, prompt is delivered to the target session as a scheduled message from the user. The result includes the task id and the next occurrence as scheduledAt in UTC and scheduledAtLocal in the zone of rrule. After downtime, only the latest missed occurrence is delivered. Delivery can repeat after a crash.", + "parameters": { + "type": "object", + "properties": { + "title": { + "type": "string", + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." + }, + "prompt": { + "type": "string", + "description": "Instruction delivered at each occurrence." + }, + "rrule": { + "type": "string", + "description": "Supported RFC 5545 subset: one DTSTART line, a newline, and one RRULE line. DTSTART ends in Z for UTC or carries TZID with an IANA time zone; a fixed offset such as UTC+5 is Etc/GMT-5, with the sign reversed. DTSTART must name an existing local time. A TZID rule keeps local clock time across daylight-saving changes; generated nonexistent local times are skipped, and repeated ones occur once, at the earlier instant. DTSTART may be in the past; delivery starts with the first occurrence after creation. A one-time delivery is RRULE:FREQ=DAILY;COUNT=1. No SECONDLY; BYSECOND takes one value. COUNT is at most 1000; use UNTIL for longer rules. MINUTELY and HOURLY accept no BY parts, so select clock times with DAILY or WEEKLY plus BYHOUR and BYMINUTE. BYMONTHDAY and ordinal BYDAY require MONTHLY or YEARLY; BYYEARDAY and BYWEEKNO require YEARLY. Ordinal BYDAY cannot combine with BYWEEKNO. Each FREQ period allows at most 10080 candidates before BYSETPOS, which accepts at most 31 values. UNTIL is a UTC instant ending in Z. Example: \"DTSTART;TZID=Asia/Singapore:20260901T080000\\nRRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1\"" + }, + "target": { + "type": "string", + "description": "this_session delivers to this session; new_once delivers to the same new session every time, opened at the first delivery; new opens a different new session for every delivery. New sessions use this session's working directory and preset. With this_session or new_once, a delivery waits until the previous one finishes, and only the latest occurrence that passed meanwhile is delivered. Use this_session for reminders and for follow-ups to this conversation; use new_once or new for independent work, such as a recurring report, and whenever the user asks for a new conversation.", + "enum": [ + "this_session", + "new_once", + "new" + ] + } + }, + "required": [ + "title", + "prompt", + "rrule", + "target" + ] + } + }, + { + "name": "schedule_edit", + "description": "Update, pause, resume, or delete one scheduled task by id. Deleting does not retract queued messages.", + "parameters": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Task id." + }, + "action": { + "type": "string", + "description": "update applies the provided fields, at least one; delete removes the task.", + "enum": [ + "update", + "delete" + ] + }, + "title": { + "type": "string", + "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." + }, + "prompt": { + "type": "string", + "description": "New instruction delivered at each occurrence." + }, + "rrule": { + "type": "string", + "description": "New recurrence in the schedule_create rrule format." + }, + "target": { + "type": "string", + "description": "Omit to retain the destination and its creation settings. Providing target replaces them; new_once reserves a different Session. New targets capture this Session's working directory and preset. Choices are the same as schedule_create.", + "enum": [ + "this_session", + "new_once", + "new" + ] + }, + "active": { + "type": "boolean", + "description": "false pauses the task; true resumes only if its timing has a future occurrence. Otherwise provide a new rrule." + }, + "expectedUpdatedAt": { + "type": "string", + "description": "updatedAt from the latest result that returned this task; if the task changed after that result, the result is schedule_conflict and nothing changes." + } + }, + "required": [ + "id", + "action" + ] + } + }, + { + "name": "schedule_list", + "description": "List scheduled tasks, including tasks created from other sessions. Active tasks come first, ordered by scheduledAt.", + "parameters": { + "type": "object", + "properties": { + "active": { + "type": "boolean", + "description": "true for active tasks only; false for paused and ended tasks only; omitted for all tasks." + }, + "limit": { + "type": "integer", + "description": "Page size from 1 to 500; defaults to 100." + }, + "offset": { + "type": "integer", + "description": "Number of tasks to skip; defaults to 0." + } + } + } + }, + { + "name": "schedule_view", + "description": "View one scheduled task by id.", + "parameters": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Task id." + } + }, + "required": [ + "id" + ] + } + }, + { + "name": "send_message", + "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", "parameters": { "type": "object", "properties": { "agent": { "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." + "description": "The name of another agent in your subagent tree, as shown by list_agents." + }, + "message": { + "type": "string", + "description": "The message to deliver to the agent." } }, "required": [ - "agent" + "agent", + "message" + ] + } + }, + { + "name": "skill", + "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", + "parameters": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "The exact skill name from the available skills list." + } + }, + "required": [ + "name" + ] + } + }, + { + "name": "subagent", + "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "subagent_fork", + "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", + "parameters": { + "type": "object", + "properties": { + "cwd": { + "type": "string", + "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." + }, + "description": { + "type": "string", + "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." + }, + "name": { + "type": "string", + "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." + }, + "prompt": { + "type": "string", + "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." + } + }, + "required": [ + "description", + "prompt" + ] + } + }, + { + "name": "todo_write", + "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", + "parameters": { + "type": "object", + "properties": { + "todos": { + "type": "array", + "description": "The COMPLETE task list, replacing any previous list.", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "content": { + "type": "string", + "description": "What the task is — a short imperative line." + }, + "status": { + "type": "string", + "description": "pending (not started) | in_progress (now) | completed (done).", + "enum": [ + "pending", + "in_progress", + "completed" + ] + } + }, + "required": [ + "content", + "status" + ] + } + } + }, + "required": [ + "todos" + ] + } + }, + { + "name": "update_goal", + "description": "Update the current goal.", + "parameters": { + "type": "object", + "properties": { + "goal_id": { + "type": "string", + "description": "Exact id returned by get_goal." + }, + "revision": { + "type": "number", + "description": "Exact positive revision returned by get_goal." + }, + "action": { + "type": "string", + "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", + "enum": [ + "edit", + "pause", + "resume", + "complete", + "blocked" + ] + }, + "objective": { + "type": "string", + "description": "Replacement objective; valid only with action edit." + }, + "max_goal_rounds": { + "type": "number", + "description": "Replacement cap; valid only with action edit." + }, + "blocked_reason": { + "type": "string", + "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." + } + }, + "required": [ + "goal_id", + "revision", + "action" + ] + } + }, + { + "name": "wait_agent", + "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", + "parameters": { + "type": "object", + "properties": { + "timeout_ms": { + "type": "integer", + "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." + } + } + } + }, + { + "name": "web_fetch", + "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", + "parameters": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The HTTP(S) URL to fetch." + } + }, + "required": [ + "url" + ] + } + }, + { + "name": "web_search", + "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", + "parameters": { + "type": "object", + "properties": { + "queries": { + "type": "array", + "description": "1–10 search queries; their results are merged.", + "items": { + "type": "string" + } + } + }, + "required": [ + "queries" + ] + } + }, + { + "name": "workflow", + "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", + "parameters": { + "type": "object", + "properties": { + "script": { + "type": "string", + "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." + }, + "meta": { + "type": "object", + "description": "The workflow identity as plain JSON, not code.", + "additionalProperties": true, + "properties": { + "name": { + "type": "string", + "description": "Short kebab-case workflow name." + }, + "description": { + "type": "string", + "description": "One-line description of what the workflow does." + }, + "whenToUse": { + "type": "string", + "description": "Optional guidance on when this workflow applies." + }, + "phases": { + "type": "array", + "description": "Optional phase declarations matched by phase() calls.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "title": { + "type": "string", + "description": "The phase title phase() calls match by exact string." + }, + "detail": { + "type": "string", + "description": "Optional one-line description of the phase." + }, + "provider": { + "type": "string", + "description": "Optional provider override this phase is expected to use." + }, + "model": { + "type": "string", + "description": "Optional model override this phase is expected to use." + } + }, + "required": [ + "title" + ] + } + } + }, + "required": [ + "name", + "description" + ] + }, + "args": { + "type": "object", + "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", + "additionalProperties": true + }, + "run_in_background": { + "type": "boolean", + "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." + } + }, + "required": [ + "script", + "meta" + ] + } + }, + { + "name": "working_directory", + "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", + "parameters": { + "type": "object", + "properties": { + "cd": { + "type": "string", + "description": "Existing directory to enter. Omit to read the current directory." + } + } + } + }, + { + "name": "write", + "description": "Create or fully replace a UTF-8 text file.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." + }, + "content": { + "type": "string", + "description": "Full UTF-8 text content to write." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "content" + ] + } + } + ], + [ + { + "name": "apply_patch", + "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", + "parameters": { + "type": "object", + "properties": { + "input": { + "type": "string", + "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "input" + ] + } + }, + { + "name": "ask_user_question", + "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. An answer item with empty selected and no custom means the user skipped that question: continue without it, do not ask it again, and do not treat the skip as permission.", + "parameters": { + "type": "object", + "properties": { + "questions": { + "type": "array", + "description": "Questions to ask the user before continuing.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "id": { + "type": "string", + "description": "Stable id for this question; echoed in the answer." + }, + "question": { + "type": "string", + "description": "The specific question to ask the user." + }, + "header": { + "type": "string", + "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." + }, + "options": { + "type": "array", + "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", + "items": { + "type": "object", + "additionalProperties": true, + "properties": { + "label": { + "type": "string", + "description": "Short user-facing option label." + }, + "description": { + "type": "string", + "description": "One sentence explaining the tradeoff or impact." + } + }, + "required": [ + "label" + ] + } + }, + "multi_select": { + "type": "boolean", + "description": "Whether the user may select more than one option. Defaults to false." + } + }, + "required": [ + "id", + "question" + ] + } + } + }, + "required": [ + "questions" + ] + } + }, + { + "name": "bash", + "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", + "parameters": { + "type": "object", + "properties": { + "description": { + "type": "string", + "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." + }, + "command": { + "type": "string", + "description": "The bash command to execute." + }, + "timeoutMs": { + "type": "number", + "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." + }, + "workdir": { + "type": "string", + "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." + }, + "run_in_background": { + "type": "boolean", + "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "description", + "command" + ] + } + }, + { + "name": "create_goal", + "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", + "parameters": { + "type": "object", + "properties": { + "objective": { + "type": "string", + "description": "The concrete completion objective inferred from the direct human request." + }, + "max_goal_rounds": { + "type": "number", + "description": "Optional positive safe-integer limit on automatic continuation rounds." + } + }, + "required": [ + "objective" + ] + } + }, + { + "name": "edit", + "description": "Edit an existing UTF-8 text file by replacing literal text.", + "parameters": { + "type": "object", + "properties": { + "file_path": { + "type": "string", + "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." + }, + "old_string": { + "type": "string", + "description": "Literal text to replace." + }, + "new_string": { + "type": "string", + "description": "Literal replacement text. Use an empty string to delete the match." + }, + "replace_all": { + "type": "boolean", + "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." + }, + "sandbox_permissions": { + "type": "string", + "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", + "enum": [ + "workspace-write", + "danger-full-access" + ] + }, + "justification": { + "type": "string", + "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." + } + }, + "required": [ + "file_path", + "old_string", + "new_string" + ] + } + }, + { + "name": "exit_plan_mode", + "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", + "parameters": { + "type": "object", + "properties": { + "plan": { + "type": "string", + "description": "The complete plan, as markdown, starting with a # heading that names it." + } + }, + "required": [ + "plan" + ] + } + }, + { + "name": "get_goal", + "description": "Read the current session goal, including the id and revision that update_goal requires.", + "parameters": { + "type": "object", + "properties": {} + } + }, + { + "name": "glob", + "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." + }, + "path": { + "type": "string", + "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." + } + }, + "required": [ + "pattern" + ] + } + }, + { + "name": "grep", + "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Regular expression to search for (ripgrep syntax)." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." + }, + "include": { + "type": "string", + "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." + } + }, + "required": [ + "pattern" ] } }, @@ -2163,22 +3071,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -3119,978 +4011,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, - { - "name": "job_kill", - "description": "Request cancellation of a running background job.", - "parameters": { - "type": "object", - "properties": { - "job_id": { - "type": "string", - "description": "Job id returned by the tool that started the background work." - }, - "reason": { - "type": "string", - "description": "Optional short reason, recorded in the log and forwarded to the job." - } - }, - "required": [ - "job_id" - ] - } - }, - { - "name": "job_list", - "description": "List your background jobs (running and finished) with their ids, kinds, and statuses.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "job_output", - "description": "Read a background job: output since the previous read for stream jobs, or the result of a finished final-output job.", - "parameters": { - "type": "object", - "properties": { - "job_id": { - "type": "string", - "description": "Job id returned by the tool that started the background work." - }, - "wait": { - "type": "boolean", - "description": "Block until the job finishes or the timeout expires; a timed-out wait leaves the job running. Defaults to false." - }, - "timeout_ms": { - "type": "number", - "description": "Max wait in milliseconds with wait: true. Defaults to and is capped by configuration." - } - }, - "required": [ - "job_id" - ] - } - }, - { - "name": "list_agents", - "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "plugin_manager", - "description": "List plugins or bundles in the current profile, enable or disable them, install a bundle, or remove an installed bundle. Every action requires danger-full-access permission or approval for this call. Approval does not change the session permission mode. Changes affect every session in this profile. List first to obtain exact identifiers. Package installation can execute allowed build scripts. Live profiles apply changes immediately, including upgrades of installed packages; a change result that is not applied carries nextStep, which says what to do or tell the user. Unmet DSH version requirements (engines.dsh, else DSH peer dependencies) block installation and activation. Version exemptions risk crashes and data loss: warn the user and obtain explicit permission for the exact plugin and runtime versions before granting one.", - "parameters": { - "type": "object", - "properties": { - "action": { - "type": "string", - "description": "Management operation.", - "enum": [ - "list_plugins", - "list_bundles", - "set_plugin", - "set_bundle", - "install_bundle", - "remove_bundle", - "list_version_exemptions", - "set_version_exemption" - ] - }, - "target": { - "type": "string", - "description": "Plugin entry id, bundle package name, or installation spec, according to action. For an Official catalog entry, pass list_bundles installTarget.spec to install_bundle." - }, - "enabled": { - "type": "boolean", - "description": "Required for set operations; defaults to true for installation. For set_version_exemption, true grants and false revokes." - }, - "runtimeVersion": { - "type": "string", - "description": "For set_version_exemption: exact DSH version from list_version_exemptions. Target must be the manifest package-name@version, not an alias or version range." - }, - "acceptRisk": { - "type": "boolean", - "description": "For granting an exemption: true only after warning the user about possible crashes and data loss and receiving explicit permission for this exact plugin/runtime pair. General installation permission is not enough." - }, - "approvedBuilds": { - "type": "array", - "description": "For install_bundle: pass names from pendingBuilds only after the user explicitly approves running their install scripts in the conversation. This grants persistent permission for this profile.", - "items": { - "type": "string" - } - }, - "registry": { - "type": "string", - "description": "For install_bundle: the npm registry URL asked first, when the user names one; otherwise the configured registry is asked, and its configured fallbacks while a registry is unreachable." - }, - "offset": { - "type": "number", - "description": "Zero-based list offset; defaults to 0." - }, - "limit": { - "type": "number", - "description": "List page size, from 1 to 100; defaults to 25." - } - }, - "required": [ - "action" - ] - } - }, - { - "name": "present", - "description": "Declare existing files as final deliverables for the user. Hosts may show presented files only after your turn ends, so call it once the files are final. If the user needs to review files earlier, such as before a tool call that waits for their answer, link them in your message instead. Use it when the user needs a separate file, especially Office documents, spreadsheets, and slide decks; prefer your final response when that suffices. The user opens the current files; their contents are not copied.", - "parameters": { - "type": "object", - "properties": { - "files": { - "type": "array", - "description": "Usually the 1-2 most important deliverables; at most 4 per call.", - "items": { - "type": "object", - "additionalProperties": false, - "properties": { - "path": { - "type": "string", - "description": "Path of an existing regular file. Relative paths use the Session working directory." - }, - "description": { - "type": "string", - "description": "Brief description for the user." - } - }, - "required": [ - "path" - ] - } - } - }, - "required": [ - "files" - ] - } - }, - { - "name": "read", - "description": "Read a UTF-8 text file and return line-numbered content.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to read, resolved by the filesystem backend." - }, - "offset": { - "type": "number", - "description": "1-based first line to return. Defaults to 1." - }, - "limit": { - "type": "number", - "description": "Maximum number of lines to return. Defaults to 2000." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "read_image", - "description": "Read a PNG/JPEG/WebP/GIF file and return the image itself. Large images are downscaled automatically; do not install image libraries or create thumbnails to inspect an image.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to the image file, resolved by the filesystem backend." - } - }, - "required": [ - "file_path" - ] - } - }, - { - "name": "schedule_create", - "description": "Create a scheduled task. At each occurrence of rrule, prompt is delivered to the target session as a scheduled message from the user. The result includes the task id and the next occurrence as scheduledAt in UTC and scheduledAtLocal in the zone of rrule. After downtime, only the latest missed occurrence is delivered. Delivery can repeat after a crash.", - "parameters": { - "type": "object", - "properties": { - "title": { - "type": "string", - "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." - }, - "prompt": { - "type": "string", - "description": "Instruction delivered at each occurrence." - }, - "rrule": { - "type": "string", - "description": "Supported RFC 5545 subset: one DTSTART line, a newline, and one RRULE line. DTSTART ends in Z for UTC or carries TZID with an IANA time zone; a fixed offset such as UTC+5 is Etc/GMT-5, with the sign reversed. DTSTART must name an existing local time. A TZID rule keeps local clock time across daylight-saving changes; generated nonexistent local times are skipped, and repeated ones occur once, at the earlier instant. DTSTART may be in the past; delivery starts with the first occurrence after creation. A one-time delivery is RRULE:FREQ=DAILY;COUNT=1. No SECONDLY; BYSECOND takes one value. COUNT is at most 1000; use UNTIL for longer rules. MINUTELY and HOURLY accept no BY parts, so select clock times with DAILY or WEEKLY plus BYHOUR and BYMINUTE. BYMONTHDAY and ordinal BYDAY require MONTHLY or YEARLY; BYYEARDAY and BYWEEKNO require YEARLY. Ordinal BYDAY cannot combine with BYWEEKNO. Each FREQ period allows at most 10080 candidates before BYSETPOS, which accepts at most 31 values. UNTIL is a UTC instant ending in Z. Example: \"DTSTART;TZID=Asia/Singapore:20260901T080000\\nRRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1\"" - }, - "target": { - "type": "string", - "description": "this_session delivers to this session; new_once delivers to the same new session every time, opened at the first delivery; new opens a different new session for every delivery. New sessions use this session's working directory and preset. With this_session or new_once, a delivery waits until the previous one finishes, and only the latest occurrence that passed meanwhile is delivered. Use this_session for reminders and for follow-ups to this conversation; use new_once or new for independent work, such as a recurring report, and whenever the user asks for a new conversation.", - "enum": [ - "this_session", - "new_once", - "new" - ] - } - }, - "required": [ - "title", - "prompt", - "rrule", - "target" - ] - } - }, - { - "name": "schedule_edit", - "description": "Update, pause, resume, or delete one scheduled task by id. Deleting does not retract queued messages.", - "parameters": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Task id." - }, - "action": { - "type": "string", - "description": "update applies the provided fields, at least one; delete removes the task.", - "enum": [ - "update", - "delete" - ] - }, - "title": { - "type": "string", - "description": "Task name of at most 120 characters in the user's language: action plus object. Omit timing, status, ids, and bracketed suffixes." - }, - "prompt": { - "type": "string", - "description": "New instruction delivered at each occurrence." - }, - "rrule": { - "type": "string", - "description": "New recurrence in the schedule_create rrule format." - }, - "target": { - "type": "string", - "description": "Omit to retain the destination and its creation settings. Providing target replaces them; new_once reserves a different Session. New targets capture this Session's working directory and preset. Choices are the same as schedule_create.", - "enum": [ - "this_session", - "new_once", - "new" - ] - }, - "active": { - "type": "boolean", - "description": "false pauses the task; true resumes only if its timing has a future occurrence. Otherwise provide a new rrule." - }, - "expectedUpdatedAt": { - "type": "string", - "description": "updatedAt from the latest result that returned this task; if the task changed after that result, the result is schedule_conflict and nothing changes." - } - }, - "required": [ - "id", - "action" - ] - } - }, - { - "name": "schedule_list", - "description": "List scheduled tasks, including tasks created from other sessions. Active tasks come first, ordered by scheduledAt.", - "parameters": { - "type": "object", - "properties": { - "active": { - "type": "boolean", - "description": "true for active tasks only; false for paused and ended tasks only; omitted for all tasks." - }, - "limit": { - "type": "integer", - "description": "Page size from 1 to 500; defaults to 100." - }, - "offset": { - "type": "integer", - "description": "Number of tasks to skip; defaults to 0." - } - } - } - }, - { - "name": "schedule_view", - "description": "View one scheduled task by id.", - "parameters": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Task id." - } - }, - "required": [ - "id" - ] - } - }, - { - "name": "send_message", - "description": "Send a message to an agent. A working agent receives it at its next step; an idle agent starts a new turn with it. Returns delivery confirmation.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of another agent in your subagent tree, as shown by list_agents." - }, - "message": { - "type": "string", - "description": "The message to deliver to the agent." - } - }, - "required": [ - "agent", - "message" - ] - } - }, - { - "name": "skill", - "description": "Load the full instructions for a skill. Call it before acting on a task that names or clearly matches a skill in the session skill catalog.", - "parameters": { - "type": "object", - "properties": { - "name": { - "type": "string", - "description": "The exact skill name from the available skills list." - } - }, - "required": [ - "name" - ] - } - }, - { - "name": "subagent", - "description": "Delegate a self-contained task to a subagent (a separate agent that works in its own context) to offload focused, independent work — research, a scoped implementation, an analysis — so it does not consume this conversation's context. The subagent returns its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", - "parameters": { - "type": "object", - "properties": { - "cwd": { - "type": "string", - "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." - }, - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." - }, - "name": { - "type": "string", - "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." - }, - "prompt": { - "type": "string", - "description": "The complete, self-contained task for the subagent. It does not share this conversation's context, so include everything it needs." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "subagent_fork", - "description": "Delegate a task to a subagent that inherits this conversation: a child agent seeded with all completed turns so far (it does not see the current in-flight turn). Use this when the subtask builds on this conversation's context — a follow-up analysis, a review, a continuation — without consuming this conversation's context for the work itself. You receive its result, not its intermediate steps. This tool starts an independently managed subagent and immediately returns its name. If you are still online when it finishes, the runtime automatically delivers its completion notice. The notice includes the final answer unless the child sent you a message just before finishing. Use `send_message` to steer it while running or continue its conversation after it finishes.", - "parameters": { - "type": "object", - "properties": { - "cwd": { - "type": "string", - "description": "Initial child working directory. Relative paths use your current directory; omitted inherits it. Later directory changes in either agent are independent." - }, - "description": { - "type": "string", - "description": "A short (3-5 word) description of the delegated task, for display. Use the language of the user's current request." - }, - "name": { - "type": "string", - "description": "Optional short name for the subagent, unique among the subagents you create: lower-case letters, digits, and hyphens, starting with a letter, at most 32 characters; lead is reserved for the root agent. Omitted names default to agent-1, agent-2, and so on." - }, - "prompt": { - "type": "string", - "description": "The task for the subagent. It already sees this conversation's completed turns, so build on them freely and state only what is new." - } - }, - "required": [ - "description", - "prompt" - ] - } - }, - { - "name": "todo_write", - "description": "Record and update a task list to plan multi-step work and show progress; skip it for trivial single-step tasks. Add one todo per concrete step before you start. While work remains, keep the todos being worked on `in_progress`, several only when work runs in parallel. Mark each todo `completed` as soon as it is done.", - "parameters": { - "type": "object", - "properties": { - "todos": { - "type": "array", - "description": "The COMPLETE task list, replacing any previous list.", - "items": { - "type": "object", - "additionalProperties": false, - "properties": { - "content": { - "type": "string", - "description": "What the task is — a short imperative line." - }, - "status": { - "type": "string", - "description": "pending (not started) | in_progress (now) | completed (done).", - "enum": [ - "pending", - "in_progress", - "completed" - ] - } - }, - "required": [ - "content", - "status" - ] - } - } - }, - "required": [ - "todos" - ] - } - }, - { - "name": "update_goal", - "description": "Update the current goal.", - "parameters": { - "type": "object", - "properties": { - "goal_id": { - "type": "string", - "description": "Exact id returned by get_goal." - }, - "revision": { - "type": "number", - "description": "Exact positive revision returned by get_goal." - }, - "action": { - "type": "string", - "description": "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.", - "enum": [ - "edit", - "pause", - "resume", - "complete", - "blocked" - ] - }, - "objective": { - "type": "string", - "description": "Replacement objective; valid only with action edit." - }, - "max_goal_rounds": { - "type": "number", - "description": "Replacement cap; valid only with action edit." - }, - "blocked_reason": { - "type": "string", - "description": "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress." - } - }, - "required": [ - "goal_id", - "revision", - "action" - ] - } - }, - { - "name": "wait_agent", - "description": "Wait for input at your next step, including agent messages, completion notifications, and user steering. Returns immediately if new input is pending. `timedOut: false` means new input is pending. Pending input is delivered to the model after code execution finishes.", - "parameters": { - "type": "object", - "properties": { - "timeout_ms": { - "type": "integer", - "description": "Wait duration in milliseconds, from 10000 through 3600000. Defaults to 30000." - } - } - } - }, - { - "name": "web_fetch", - "description": "Fetch the content of a specific HTTP(S) URL and return it decoded to text.", - "parameters": { - "type": "object", - "properties": { - "url": { - "type": "string", - "description": "The HTTP(S) URL to fetch." - } - }, - "required": [ - "url" - ] - } - }, - { - "name": "web_search", - "description": "Search the web for current information. Returns an optional summary answer and a list of source URLs.", - "parameters": { - "type": "object", - "properties": { - "queries": { - "type": "array", - "description": "1–10 search queries; their results are merged.", - "items": { - "type": "string" - } - } - }, - "required": [ - "queries" - ] - } - }, - { - "name": "workflow", - "description": "Run a JavaScript workflow script that orchestrates subagents at scale. Use this for work that fans out across many independent pieces — an audit over many files, a migration, multi-angle research, adversarial verification of findings — where you write the orchestration as a script instead of delegating turn by turn.\n\nScript-body hooks:\n- `agent(prompt, opts?): Promise` — run one subagent to completion. Without `opts.schema` it resolves to the child's final text; with `opts.schema` (an object-rooted JSON Schema using ONLY type/properties/required/additionalProperties/items/enum/const/oneOf) it resolves to the validated object. Resolves `null` when the child fails (filter with `.filter(Boolean)`). Other opts: `label` (display), `phase` (progress group), and independent `provider`/`model` LLM target overrides.\n- `pipeline(items, ...stages): Promise` — run each item through the stages independently with NO barrier between stages (prefer this for multi-stage work). Each stage receives `(prev, item, index)`. A stage throw drops that ITEM to `null` and skips its remaining stages.\n- `parallel(thunks): Promise` — run zero-argument functions concurrently and await ALL of them (a barrier; use only when a stage genuinely needs every prior result together). A throwing thunk resolves to `null`.\n- `phase(title)` — start a progress phase; `log(message)` — narrate progress; `args` — the tool call's `args` input, verbatim.\n\nMisused hooks (bad arguments, unknown options, unsupported schemas, tripped caps) end the whole script instead of producing `null`. The script has no filesystem, network, timer, or Node.js APIs; the agents do the work.", - "parameters": { - "type": "object", - "properties": { - "script": { - "type": "string", - "description": "The plain JavaScript body, not TypeScript and without an `export const meta` statement; top-level await is allowed. End with `return `; the JSON-serializable value is this tool's result." - }, - "meta": { - "type": "object", - "description": "The workflow identity as plain JSON, not code.", - "additionalProperties": true, - "properties": { - "name": { - "type": "string", - "description": "Short kebab-case workflow name." - }, - "description": { - "type": "string", - "description": "One-line description of what the workflow does." - }, - "whenToUse": { - "type": "string", - "description": "Optional guidance on when this workflow applies." - }, - "phases": { - "type": "array", - "description": "Optional phase declarations matched by phase() calls.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "title": { - "type": "string", - "description": "The phase title phase() calls match by exact string." - }, - "detail": { - "type": "string", - "description": "Optional one-line description of the phase." - }, - "provider": { - "type": "string", - "description": "Optional provider override this phase is expected to use." - }, - "model": { - "type": "string", - "description": "Optional model override this phase is expected to use." - } - }, - "required": [ - "title" - ] - } - } - }, - "required": [ - "name", - "description" - ] - }, - "args": { - "type": "object", - "description": "Optional JSON input exposed to the script as the `args` global (wrap a bare list as a field, e.g. {\"files\": [...]}).", - "additionalProperties": true - }, - "run_in_background": { - "type": "boolean", - "description": "Run as a background job: return a job id immediately instead of waiting; the return value arrives with the completion notice." - } - }, - "required": [ - "script", - "meta" - ] - } - }, - { - "name": "working_directory", - "description": "Read the current working directory, or change it with cd. Relative paths use the current directory. Existing shells and running processes keep their own directories.", - "parameters": { - "type": "object", - "properties": { - "cd": { - "type": "string", - "description": "Existing directory to enter. Omit to read the current directory." - } - } - } - }, - { - "name": "write", - "description": "Create or fully replace a UTF-8 text file.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to write, resolved by the filesystem backend. Provide `file_path` before `content` in the arguments." - }, - "content": { - "type": "string", - "description": "Full UTF-8 text content to write." - }, - "sandbox_permissions": { - "type": "string", - "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." - } - }, - "required": [ - "file_path", - "content" - ] - } - } - ], - [ - { - "name": "apply_patch", - "description": "Create, update, delete, or move UTF-8 text files with one patch; prefer it over multiple edit calls when a change spans several files or separated regions.", - "parameters": { - "type": "object", - "properties": { - "input": { - "type": "string", - "description": "Patch text: start with *** Begin Patch and end with *** End Patch. Use *** Add File: path with + lines; *** Update File: path, optionally followed by *** Move to: path, with @@ or @@ context and space-prefixed context, + added, or - removed lines; *** End of File anchors the last hunk to the file end. Use *** Delete File: path to delete. Paths are relative to the Session working directory." - }, - "sandbox_permissions": { - "type": "string", - "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." - } - }, - "required": [ - "input" - ] - } - }, - { - "name": "ask_user_question", - "description": "Ask the user a concise question when you need confirmation, a choice, or missing information before proceeding. An answer item with empty selected and no custom means the user skipped that question: continue without it, do not ask it again, and do not treat the skip as permission.", - "parameters": { - "type": "object", - "properties": { - "questions": { - "type": "array", - "description": "Questions to ask the user before continuing.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "id": { - "type": "string", - "description": "Stable id for this question; echoed in the answer." - }, - "question": { - "type": "string", - "description": "The specific question to ask the user." - }, - "header": { - "type": "string", - "description": "Optional short heading for the question, such as \"Confirm\" or \"Choose Mode\"." - }, - "options": { - "type": "array", - "description": "Optional choices to show the user. If you recommend one, put it first and append \"(Recommended)\" to that label.", - "items": { - "type": "object", - "additionalProperties": true, - "properties": { - "label": { - "type": "string", - "description": "Short user-facing option label." - }, - "description": { - "type": "string", - "description": "One sentence explaining the tradeoff or impact." - } - }, - "required": [ - "label" - ] - } - }, - "multi_select": { - "type": "boolean", - "description": "Whether the user may select more than one option. Defaults to false." - } - }, - "required": [ - "id", - "question" - ] - } - } - }, - "required": [ - "questions" - ] - } - }, - { - "name": "bash", - "description": "Execute a bash command (`bash -c`) and return its stdout/stderr. Each call runs in a fresh shell; pass `workdir` instead of using `cd`. Managed `$DSH_*` variables expose current harness environment facts. Long output is truncated to its tail; the full output is saved to a file whose path is reported when available. Provide `description` before `command` in the arguments. Before any delete or move, verify that the resolved absolute target path is the intended one; never run it against a computed path you have not checked. An unset variable expands to an empty string, so guard variables in such paths with `${VAR:?}`. Commands may run under a file sandbox; a blocked file operation is reported as `[sandbox: file access denied under mode]`, a policy denial: do not retry another way.", - "parameters": { - "type": "object", - "properties": { - "description": { - "type": "string", - "description": "Clear, concise description of what this command does in active voice, 5-10 words (shown in the UI). Examples: \"ls\" → \"List files in current directory\"; \"git status\" → \"Show working tree status\"; \"npm install\" → \"Install package dependencies\"." - }, - "command": { - "type": "string", - "description": "The bash command to execute." - }, - "timeoutMs": { - "type": "number", - "description": "Timeout in milliseconds. The executor applies its configured default and cap; on expiry the command moves to the background as a job instead of being killed." - }, - "workdir": { - "type": "string", - "description": "Working directory for this command. Defaults to the session workspace; a relative path is resolved against it." - }, - "run_in_background": { - "type": "boolean", - "description": "Run in the background and return a job id immediately (collect with job_output, stop with job_kill). No timeout applies." - }, - "sandbox_permissions": { - "type": "string", - "description": "The narrowest wider sandbox mode for a one-shot retry of the exact command the sandbox just denied; the retry asks the user for approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact command needs the wider access. Use the language of the user’s current request." - } - }, - "required": [ - "description", - "command" - ] - } - }, - { - "name": "create_goal", - "description": "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.", - "parameters": { - "type": "object", - "properties": { - "objective": { - "type": "string", - "description": "The concrete completion objective inferred from the direct human request." - }, - "max_goal_rounds": { - "type": "number", - "description": "Optional positive safe-integer limit on automatic continuation rounds." - } - }, - "required": [ - "objective" - ] - } - }, - { - "name": "edit", - "description": "Edit an existing UTF-8 text file by replacing literal text.", - "parameters": { - "type": "object", - "properties": { - "file_path": { - "type": "string", - "description": "Path to edit, resolved by the filesystem backend. Provide `file_path` before `old_string` and `new_string` in the arguments." - }, - "old_string": { - "type": "string", - "description": "Literal text to replace." - }, - "new_string": { - "type": "string", - "description": "Literal replacement text. Use an empty string to delete the match." - }, - "replace_all": { - "type": "boolean", - "description": "Replace all matches. Defaults to false; when false, old_string must appear exactly once." - }, - "sandbox_permissions": { - "type": "string", - "description": "The narrowest wider sandbox mode for a one-shot retry of the exact operation the sandbox just denied; the retry asks the user for approval.", - "enum": [ - "workspace-write", - "danger-full-access" - ] - }, - "justification": { - "type": "string", - "description": "Required with sandbox_permissions: one sentence for the user explaining why this exact file operation needs the wider access. Use the language of the user’s current request." - } - }, - "required": [ - "file_path", - "old_string", - "new_string" - ] - } - }, - { - "name": "exit_plan_mode", - "description": "Use only in plan mode. Present your plan for the user's review and, on approval, leave plan mode. The user may approve (carry out the plan from your next step) or keep planning — their feedback comes back in the tool result; revise and present again.", - "parameters": { - "type": "object", - "properties": { - "plan": { - "type": "string", - "description": "The complete plan, as markdown, starting with a # heading that names it." - } - }, - "required": [ - "plan" - ] - } - }, - { - "name": "get_goal", - "description": "Read the current session goal, including the id and revision that update_goal requires.", - "parameters": { - "type": "object", - "properties": {} - } - }, - { - "name": "glob", - "description": "Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.", - "parameters": { - "type": "object", - "properties": { - "pattern": { - "type": "string", - "description": "Glob pattern to match file paths against (e.g. \"**/*.ts\", \"src/**/*.test.js\"). A pattern with no \"/\" matches the basename at any depth, so \"*\" and \"*.ts\" both search the whole tree; include a separator to anchor the depth." - }, - "path": { - "type": "string", - "description": "Directory to search in. Defaults to the session workspace; a relative path resolves against it." - } - }, - "required": [ - "pattern" - ] - } - }, - { - "name": "grep", - "description": "Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.", - "parameters": { - "type": "object", - "properties": { - "pattern": { - "type": "string", - "description": "Regular expression to search for (ripgrep syntax)." - }, - "path": { - "type": "string", - "description": "File or directory to search. Defaults to the session workspace; a relative path resolves against it." - }, - "include": { - "type": "string", - "description": "One glob filter for which files to search (e.g. \"*.ts\", \"*.{js,jsx}\"). Not a list; negation is not supported." - } - }, - "required": [ - "pattern" - ] - } - }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json b/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-activation-limit/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json b/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-continuable-inheritance/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json b/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-continuable/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json b/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json index ccc6927ef0..81aaececa6 100644 --- a/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-diagnostic/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json index 7429a130fa..1f122af658 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json index 62b13c9954..9fd1e04d56 100644 --- a/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json +++ b/snapshots/sdk/subagent-dsh-sdk-dynamic-route/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json b/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-list-agents/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json b/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json +++ b/snapshots/sdk/subagent-send-message/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json index d1e5090032..52d309609b 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.1.expected.json @@ -222,22 +222,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json index d1e5090032..52d309609b 100644 --- a/snapshots/sdk/team-default-enabled/tool-schemas.expected.json +++ b/snapshots/sdk/team-default-enabled/tool-schemas.expected.json @@ -222,22 +222,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/sdk/tool-error-details/notifications.expected.jsonl b/snapshots/sdk/tool-error-details/notifications.expected.jsonl index 675b8118eb..d96af775ab 100644 --- a/snapshots/sdk/tool-error-details/notifications.expected.jsonl +++ b/snapshots/sdk/tool-error-details/notifications.expected.jsonl @@ -7,7 +7,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":8,"time":0,"data":{"content":[{"type":"text","text":"Exercise a native denial and a caught PTC inner denial, then reply ERROR_DETAILS_OK."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":9,"time":0,"data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"user/message","seq":10,"time":0,"data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":11,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/context","seq":12,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"session/title","seq":13,"time":0,"data":{"title":"Exercise a native denial and","messageSeqs":[8],"source":{"kind":"fallback"}}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":14,"time":0,"data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"denied-native","name":"bash","args":["{\"command\":\"echo AUTO_DENIED\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} @@ -17,7 +17,7 @@ {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"step/start","seq":18,"time":0,"data":{"turn":1,"step":2}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"system/message","seq":19,"time":0,"data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"request/header","seq":20,"time":0,"data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}}}} -{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":21,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":20},"surfaceOp":"append"}}} +{"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"developer/message","seq":21,"time":0,"data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{sessionId}}"},"headerSeq":20},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"assistant/message","seq":22,"time":0,"data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{sessionId}}"},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"denied-code","name":"run_code","args":["{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/call","seq":23,"time":0,"data":{"turn":1,"step":2,"callId":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}}} {"method":"session.event","params":{"sessionId":"{{sessionId}}","event":{"type":"tool/ptc-dispatch-start","seq":24,"time":0,"data":{"rootCallId":"denied-code","parentCallId":"denied-code","subCallId":"denied-code:ptc:1","name":"bash","arguments":{"command":"echo AUTO_DENIED"}}}}} diff --git a/snapshots/sdk/tool-error-details/session.v4.jsonl b/snapshots/sdk/tool-error-details/session.v4.jsonl index 5207c04c20..0095f09f67 100644 --- a/snapshots/sdk/tool-error-details/session.v4.jsonl +++ b/snapshots/sdk/tool-error-details/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Exercise a native denial and a caught PTC inner denial, then reply ERROR_DETAILS_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Exercise a native denial and","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1793796132469,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796132470,"index":0,"dt":[],"id":"denied-native","name":"bash","args":["{\"command\":\"echo AUTO_DENIED\"}"]},{"type":"chunk","time":1793796132470,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-native","name":"bash","arguments":"{\"command\":\"echo AUTO_DENIED\"}"}}},{"type":"chunk","time":1793796132470,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -20,7 +20,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:7}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:8}}"},"headerSeq":20},"surfaceOp":"append"} +{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:8}}"},"headerSeq":20},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1793796132486,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793796132486,"index":0,"dt":[],"id":"denied-code","name":"run_code","args":["{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"]},{"type":"chunk","time":1793796132486,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}}},{"type":"chunk","time":1793796132486,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"denied-code","name":"run_code","arguments":"{\"code\":\"try { await tools.bash({command: \\\"echo AUTO_DENIED\\\"}) } catch (error) { return error.message }\",\"description\":\"Catch one denied inner call\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"denied-code","parentCallId":"denied-code","subCallId":"denied-code:ptc:1","name":"bash","arguments":{"command":"echo AUTO_DENIED"}}} diff --git a/snapshots/sdk/tool-error-details/system-prompt.expected.md b/snapshots/sdk/tool-error-details/system-prompt.expected.md index 0e5cf03a8b..ccfe4750ea 100644 --- a/snapshots/sdk/tool-error-details/system-prompt.expected.md +++ b/snapshots/sdk/tool-error-details/system-prompt.expected.md @@ -157,11 +157,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -426,9 +421,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/sdk/tool-error-details/tool-schemas.expected.json b/snapshots/sdk/tool-error-details/tool-schemas.expected.json index d47fe772df..bf3d9439fe 100644 --- a/snapshots/sdk/tool-error-details/tool-schemas.expected.json +++ b/snapshots/sdk/tool-error-details/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/advanced-toolchain/session.v4.jsonl b/snapshots/session/advanced-toolchain/session.v4.jsonl index 2c3ad47d45..c1a09eb618 100644 --- a/snapshots/session/advanced-toolchain/session.v4.jsonl +++ b/snapshots/session/advanced-toolchain/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Run this advanced flow exactly once: list runtime inspect providers; discover providers through run_code when available; delegate once to a direct spawn child; run one workflow that delegates to another spawn child; list providers again; then reply with exactly ADVANCED_HEADLESS_OK."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Run this advanced flow exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect_list","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715021,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715022,"index":0,"dt":[],"id":"advanced-inspect-before","name":"cordis_inspect_list","args":["{}"]},{"type":"chunk","time":1791315715022,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-inspect-before","name":"cordis_inspect_list","arguments":"{}"}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715022,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} {"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["run_code"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"cordis_inspect_list"},{"type":"tool-removal","toolName":"cordis_inspect_query"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"interrupt_agent"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} +{"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"run_code"},{"type":"tool-removal","toolName":"apply_patch"},{"type":"tool-removal","toolName":"bash"},{"type":"tool-removal","toolName":"cordis_inspect_list"},{"type":"tool-removal","toolName":"cordis_inspect_query"},{"type":"tool-removal","toolName":"create_goal"},{"type":"tool-removal","toolName":"edit"},{"type":"tool-removal","toolName":"get_goal"},{"type":"tool-removal","toolName":"glob"},{"type":"tool-removal","toolName":"grep"},{"type":"tool-removal","toolName":"job_kill"},{"type":"tool-removal","toolName":"job_list"},{"type":"tool-removal","toolName":"job_output"},{"type":"tool-removal","toolName":"list_agents"},{"type":"tool-removal","toolName":"read"},{"type":"tool-removal","toolName":"read_image"},{"type":"tool-removal","toolName":"send_message"},{"type":"tool-removal","toolName":"skill"},{"type":"tool-removal","toolName":"subagent"},{"type":"tool-removal","toolName":"subagent_fork"},{"type":"tool-removal","toolName":"todo_write"},{"type":"tool-removal","toolName":"update_goal"},{"type":"tool-removal","toolName":"wait_agent"},{"type":"tool-removal","toolName":"web_fetch"},{"type":"tool-removal","toolName":"web_search"},{"type":"tool-removal","toolName":"workflow"},{"type":"tool-removal","toolName":"working_directory"},{"type":"tool-removal","toolName":"write"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715055,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715055,"index":0,"dt":[],"id":"advanced-code","name":"run_code","args":["{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"]},{"type":"chunk","time":1791315715055,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715055,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"advanced-code","name":"run_code","arguments":"{\"code\":\"const inspected = await tools.cordis_inspect_list({}); return inspected.providers.map(provider => provider.id);\",\"description\":\"Discover runtime APIs through PTC\"}"}} {"type":"tool/ptc-dispatch-start","data":{"rootCallId":"advanced-code","parentCallId":"advanced-code","subCallId":"advanced-code:ptc:1","name":"cordis_inspect_list","arguments":{}}} @@ -28,8 +28,8 @@ {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} {"type":"system/message","data":{"turn":1,"step":3,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:10}}"}},"sourceEventSeqs":[18],"surfaceOp":{"op":"replace","startSeq":18,"endSeq":18}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} -{"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"cordis_inspect_list"},{"type":"tool-addition","toolName":"cordis_inspect_query"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"interrupt_agent"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"},{"type":"tool-removal","toolName":"run_code"}],"role":"developer","id":"{{message:11}}"},"headerSeq":29},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","bash","cordis_inspect_list","cordis_inspect_query","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"apply_patch"},{"type":"tool-addition","toolName":"bash"},{"type":"tool-addition","toolName":"cordis_inspect_list"},{"type":"tool-addition","toolName":"cordis_inspect_query"},{"type":"tool-addition","toolName":"create_goal"},{"type":"tool-addition","toolName":"edit"},{"type":"tool-addition","toolName":"get_goal"},{"type":"tool-addition","toolName":"glob"},{"type":"tool-addition","toolName":"grep"},{"type":"tool-addition","toolName":"job_kill"},{"type":"tool-addition","toolName":"job_list"},{"type":"tool-addition","toolName":"job_output"},{"type":"tool-addition","toolName":"list_agents"},{"type":"tool-addition","toolName":"read"},{"type":"tool-addition","toolName":"read_image"},{"type":"tool-addition","toolName":"send_message"},{"type":"tool-addition","toolName":"skill"},{"type":"tool-addition","toolName":"subagent"},{"type":"tool-addition","toolName":"subagent_fork"},{"type":"tool-addition","toolName":"todo_write"},{"type":"tool-addition","toolName":"update_goal"},{"type":"tool-addition","toolName":"wait_agent"},{"type":"tool-addition","toolName":"web_fetch"},{"type":"tool-addition","toolName":"web_search"},{"type":"tool-addition","toolName":"workflow"},{"type":"tool-addition","toolName":"working_directory"},{"type":"tool-addition","toolName":"write"},{"type":"tool-removal","toolName":"run_code"}],"role":"developer","id":"{{message:11}}"},"headerSeq":29},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":3,"outputTokens":3},"stream":[{"type":"chunk","time":1791315715200,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1791315715200,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":["{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"]},{"type":"chunk","time":1791315715200,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}}},{"type":"chunk","time":1791315715200,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3}}},{"type":"chunk","time":1791315715200,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\":\"Check direct child\",\"prompt\":\"Reply with exactly DIRECT_CHILD_OK and nothing else.\",\"run_in_background\":false}"}} {"type":"subagent/catalog","data":{"version":3,"childId":"{{session:2}}","childCreatedAt":1791315715221,"mode":"continuable","label":"Check direct child","name":"agent-1"}} diff --git a/snapshots/session/advanced-toolchain/system-prompt.expected.md b/snapshots/session/advanced-toolchain/system-prompt.expected.md index 4327bd60c2..2761bf68ad 100644 --- a/snapshots/session/advanced-toolchain/system-prompt.expected.md +++ b/snapshots/session/advanced-toolchain/system-prompt.expected.md @@ -170,11 +170,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -441,9 +436,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/advanced-toolchain/tool-schemas.expected.json b/snapshots/session/advanced-toolchain/tool-schemas.expected.json index 8b209628c6..60c0d74948 100644 --- a/snapshots/session/advanced-toolchain/tool-schemas.expected.json +++ b/snapshots/session/advanced-toolchain/tool-schemas.expected.json @@ -228,22 +228,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -965,22 +949,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/agent-instructions/tool-schemas.expected.json b/snapshots/session/agent-instructions/tool-schemas.expected.json index 330f640f56..05b7194e33 100644 --- a/snapshots/session/agent-instructions/tool-schemas.expected.json +++ b/snapshots/session/agent-instructions/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -844,22 +828,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/apply-patch-update/tool-schemas.expected.json b/snapshots/session/apply-patch-update/tool-schemas.expected.json index 842f8ad9d4..827b3a3e9b 100644 --- a/snapshots/session/apply-patch-update/tool-schemas.expected.json +++ b/snapshots/session/apply-patch-update/tool-schemas.expected.json @@ -159,22 +159,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "list_agents", "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", diff --git a/snapshots/session/both-mode-turn/system-prompt.expected.md b/snapshots/session/both-mode-turn/system-prompt.expected.md index 0442b72193..3cc2d5e4c5 100644 --- a/snapshots/session/both-mode-turn/system-prompt.expected.md +++ b/snapshots/session/both-mode-turn/system-prompt.expected.md @@ -120,11 +120,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -389,9 +384,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json b/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json index 755e8e2317..277db426bf 100644 --- a/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json +++ b/snapshots/session/browser-use-chrome-devtools-mcp/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json b/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json index 0b0a8eb9a3..efa2e54853 100644 --- a/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json +++ b/snapshots/session/browser-use-playwright-mcp/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json b/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json index 6917c9788c..b83b65b7bc 100644 --- a/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json +++ b/snapshots/session/browser-use-stagehand-native/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/compaction-recovery/tool-schemas.expected.json b/snapshots/session/compaction-recovery/tool-schemas.expected.json index 86eea456d6..ae0b7ce3a7 100644 --- a/snapshots/session/compaction-recovery/tool-schemas.expected.json +++ b/snapshots/session/compaction-recovery/tool-schemas.expected.json @@ -159,22 +159,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -788,22 +772,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json b/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json index aa794f54ac..3a3f73ce68 100644 --- a/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json +++ b/snapshots/session/computer-use-cua-driver-mcp/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json b/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json index 204b124365..acf3b16718 100644 --- a/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json +++ b/snapshots/session/computer-use-cua-driver-native/tool-schemas.expected.json @@ -233,22 +233,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json b/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json index cd6e6548e5..b1df2e293d 100644 --- a/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json +++ b/snapshots/session/cordis-inspect-jsdoc/tool-schemas.expected.json @@ -228,22 +228,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/cua-native/tool-schemas.expected.json b/snapshots/session/cua-native/tool-schemas.expected.json index 33f3636750..565485ea46 100644 --- a/snapshots/session/cua-native/tool-schemas.expected.json +++ b/snapshots/session/cua-native/tool-schemas.expected.json @@ -1545,22 +1545,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index 587436227a..b0af17e860 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -173,11 +173,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -443,9 +438,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl b/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl index 60e4ea8b5f..b295cf23d8 100644 --- a/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl +++ b/snapshots/session/dynamic-tool-prompt-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","systemPromptUpdate":"in-history"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790149644504,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644504,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790149644504,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,14 +18,14 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1790149644534,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644534,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790149644534,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790149644535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:11}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790149644557,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790149644557,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790149644557,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/dynamic-tool-updates/session.v4.jsonl b/snapshots/session/dynamic-tool-updates/session.v4.jsonl index 718e23f2fe..c2e7bc3bad 100644 --- a/snapshots/session/dynamic-tool-updates/session.v4.jsonl +++ b/snapshots/session/dynamic-tool-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790049391235,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391235,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790049391235,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790049391235,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -17,14 +17,14 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_task_read"},"toolCallId":"call_task_read","content":[{"type":"text","text":"{{cwd}}/task.txt\nfile\n\n1: Reply with the single word DONE after reading this file.\n\n(End of file - total 1 lines)\n"}],"isError":false,"id":"{{message:5}}"},"meta":{"path":"{{cwd}}/task.txt","offset":1,"lines":[{"number":1,"text":"Reply with the single word DONE after reading this file."}],"totalLines":1}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:6}}"},"headerSeq":18},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:7}}"},"stream":[{"type":"chunk","time":1790049391255,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790049391255,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790049391255,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790049391255,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:8}}"}},"sourceEventSeqs":[21],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:9}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:10}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790049391270,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790049391270,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790049391270,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790049391270,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json b/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json index a3e5000b90..082427d65d 100644 --- a/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json +++ b/snapshots/session/dynamic-tool-updates/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -844,22 +828,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -1508,22 +1476,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/fs-glob-sampling/tool-schemas.expected.json b/snapshots/session/fs-glob-sampling/tool-schemas.expected.json index 1763014d03..f3889efab3 100644 --- a/snapshots/session/fs-glob-sampling/tool-schemas.expected.json +++ b/snapshots/session/fs-glob-sampling/tool-schemas.expected.json @@ -159,22 +159,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "list_agents", "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", diff --git a/snapshots/session/in-history-series-start/session.v4.jsonl b/snapshots/session/in-history-series-start/session.v4.jsonl index ee4aa2eba1..3d91c63da2 100644 --- a/snapshots/session/in-history-series-start/session.v4.jsonl +++ b/snapshots/session/in-history-series-start/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","systemPromptUpdate":"in-history"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1792735518085,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792735518085,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1792735518085,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1792735518085,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1792735518085,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,7 +18,7 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1792735518105,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1792735518105,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1792735518105,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1792735518105,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} @@ -26,7 +26,7 @@ {"type":"step/end","data":{"turn":1,"step":2}} {"type":"user/message","data":{"content":[{"type":"text","text":"Snapshot checkpoint replacing the first admitted user message."}],"source":{"kind":"test-compaction"},"role":"user","id":"{{message:10}}"},"sourceEventSeqs":[8],"surfaceOp":{"op":"replace","startSeq":8,"endSeq":8}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"high"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:11}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:12}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1792735518120,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1792735518120,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1792735518120,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1792735518120,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1792735518120,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/lsp-definition/tool-schemas.expected.json b/snapshots/session/lsp-definition/tool-schemas.expected.json index e78092b598..6f0c4997d9 100644 --- a/snapshots/session/lsp-definition/tool-schemas.expected.json +++ b/snapshots/session/lsp-definition/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md index 5df4972023..4e7f0f4ab6 100644 --- a/snapshots/session/mcp-resources-ptc/system-prompt.expected.md +++ b/snapshots/session/mcp-resources-ptc/system-prompt.expected.md @@ -128,11 +128,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -418,9 +413,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/mcp-resources/tool-schemas.expected.json b/snapshots/session/mcp-resources/tool-schemas.expected.json index 669bfabee6..49aee6d79b 100644 --- a/snapshots/session/mcp-resources/tool-schemas.expected.json +++ b/snapshots/session/mcp-resources/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/mcp-template-error/tool-schemas.expected.json b/snapshots/session/mcp-template-error/tool-schemas.expected.json index bfad6be741..9adf9d084c 100644 --- a/snapshots/session/mcp-template-error/tool-schemas.expected.json +++ b/snapshots/session/mcp-template-error/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json b/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json index 0fee5ddc7b..4947b4edeb 100644 --- a/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json +++ b/snapshots/session/multimodal-spill-ends/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/office-authoring-checker/session.v4.jsonl b/snapshots/session/office-authoring-checker/session.v4.jsonl index 325a1cb92c..2af2dfe8c8 100644 --- a/snapshots/session/office-authoring-checker/session.v4.jsonl +++ b/snapshots/session/office-authoring-checker/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Load the Office Word, PowerPoint, and Excel authoring skills. Read their structural-check instructions and reply DONE. Do not create files."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the Office Word, PowerPoint,","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-docx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1793628043727,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628043727,"index":0,"dt":[],"id":"call_office_skill","name":"skill","args":["{\"name\":\"office-docx\"}"]},{"type":"chunk","time":1793628043727,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-docx\"}"}}},{"type":"chunk","time":1793628043727,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,7 +18,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_skill"},"toolCallId":"call_office_skill","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below.\n\nKeep scripts, intermediate files, and final documents in the workspace; runtime and skill resources are read-only. Use the requested language and preserve the document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\npython-docx cannot read legacy `.doc` files. Use `office_convert` with `format: \"docx\"`, copy the result into the workspace, then edit the copy.\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. For ordinary text edits, do not unzip the document, enumerate ZIP members, dump raw XML, or inspect core properties, headers, or footers unrelated to the target. Investigate these only for a concrete failure, an ambiguous target, an unsupported feature, or an explicit user requirement. Rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. These checks complete routine validation; deliver the file once they pass. ZIP integrity, package inventories, and metadata matter only for a concrete failure.\n\nCall `office_render` on the changed page when the user asks for images or visual inspection, or when styling, font color, spacing, sizing, or text alignment is the requested edit; a request to skip rendering takes precedence. New documents and content edits, with incidental basic formatting, are checked with python-docx alone. For PDF output, call `office_convert` with `format: \"pdf\"`, then copy the returned temporary file to the destination.\n\nA fully transparent or uniformly blank image of populated content means the renderer failed, which ends visual checks for the task and leaves the source as it is. When content and structure checks pass, state the visual status only as \"Content and structure checks passed; visual inspection was not completed.\" or \"内容与结构检查通过;视觉检查未完成。\".\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current file without copying or preserving its bytes; keep it in place and omit temporary QA reports unless requested. If `present` is unavailable, deliver the final workspace path with the session's supported method.\n\n## Python environment\n\nFollow an explicit user or applicable AGENTS.md requirement for a Python environment. Otherwise use the project's or user's existing Python, such as `python3` or `python` on PATH. Before the first script, check that this Python can import the libraries the workflow needs. If Python or a library is missing, tell the user which packages to install; do not install packages into a global environment without the user's agreement.\n\n"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"office_convert"},{"type":"tool-addition","toolName":"office_recalculate"},{"type":"tool-addition","toolName":"office_render"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pptx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1793628043746,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628043746,"index":0,"dt":[],"id":"call_office_2","name":"skill","args":["{\"name\":\"office-pptx\"}"]},{"type":"chunk","time":1793628043746,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pptx\"}"}}},{"type":"chunk","time":1793628043746,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"skill","arguments":"{\"name\":\"office-pptx\"}"}} diff --git a/snapshots/session/office-progressive-native/session.v4.jsonl b/snapshots/session/office-progressive-native/session.v4.jsonl index 7d84dd306b..fe32bf2d08 100644 --- a/snapshots/session/office-progressive-native/session.v4.jsonl +++ b/snapshots/session/office-progressive-native/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Load the office router, then the authoring skill for this workflow. Render page 1 of report.docx, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the office router, then","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"stream":[{"type":"chunk","time":1793628044587,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628044588,"index":0,"dt":[],"id":"call_office_skill","name":"skill","args":["{\"name\":\"office\"}"]},{"type":"chunk","time":1793628044588,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office\"}"}}},{"type":"chunk","time":1793628044588,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,7 +18,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_skill"},"toolCallId":"call_office_skill","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Office task routing\n\nLoad `office-docx`, `office-pptx`, or `office-xlsx` to create, read, or edit; operations alone need no format skill.\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\n- `office_render`: Office or PDF images, visual checks, and appearance or slide checks required by the format skill; skip it when asked.\n- `office_recalculate`: formulas, with `format: \"xlsx\"` or `\"ods\"`.\n- `office_convert` with `format`; Office inputs only, not PDFs. For PDF export alone, check the copy is nonempty and starts with `%PDF-`, then deliver it without rendering.\n\nCopy temporary outputs to the destination, keeping existing files unless asked to replace them. Reuse loaded skills.\n\n"}],"isError":false,"id":"{{message:6}}"}},"sourceEventSeqs":[15],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"office_convert"},{"type":"tool-addition","toolName":"office_recalculate"},{"type":"tool-addition","toolName":"office_render"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1793628044612,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628044612,"index":0,"dt":[],"id":"call_office_2","name":"skill","args":["{\"name\":\"office-xlsx\"}"]},{"type":"chunk","time":1793628044612,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}}},{"type":"chunk","time":1793628044612,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}} diff --git a/snapshots/session/office-progressive-native/tool-schemas.expected.json b/snapshots/session/office-progressive-native/tool-schemas.expected.json index cb30cd581f..b472568322 100644 --- a/snapshots/session/office-progressive-native/tool-schemas.expected.json +++ b/snapshots/session/office-progressive-native/tool-schemas.expected.json @@ -142,22 +142,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -754,22 +738,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/office-progressive-ptc/system-prompt.expected.md b/snapshots/session/office-progressive-ptc/system-prompt.expected.md index 26e78e3934..f93624c469 100644 --- a/snapshots/session/office-progressive-ptc/system-prompt.expected.md +++ b/snapshots/session/office-progressive-ptc/system-prompt.expected.md @@ -99,11 +99,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -334,9 +329,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { @@ -631,11 +623,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -895,9 +882,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/office-render-tools/writer.expected.jsonl b/snapshots/session/office-render-tools/writer.expected.jsonl index 31300316ee..b12e3b4f8f 100644 --- a/snapshots/session/office-render-tools/writer.expected.jsonl +++ b/snapshots/session/office-render-tools/writer.expected.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-docx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Word documents\n\nUse `python-docx` for DOCX creation and ordinary edits unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below.\n\nKeep scripts, intermediate files, and final documents in the workspace; runtime and skill resources are read-only. Use the requested language and preserve the document's design unless a redesign is requested.\n\nName Python scripts for their task, such as `edit_docx.py`; avoid module names such as `inspect.py`, `docx.py`, or `zipfile.py` that shadow imported libraries.\n\n## Create and edit\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\npython-docx cannot read legacy `.doc` files. Use `office_convert` with `format: \"docx\"`, copy the result into the workspace, then edit the copy.\n\nFor text edits, locate the target by its text or position and inspect only its runs and formatting. A title can be an ordinary paragraph without a Title style or document-property title. Update the relevant runs; assigning paragraph `.text` destroys run formatting. Save a new file unless an in-place edit is requested. For ordinary text edits, do not unzip the document, enumerate ZIP members, dump raw XML, or inspect core properties, headers, or footers unrelated to the target. Investigate these only for a concrete failure, an ambiguous target, an unsupported feature, or an explicit user requirement. Rebuilding a document can lose unsupported features.\n\nUse paragraph styles for headings and body text. Size tables for the section that contains them, and account for merged cells and nested tables. Chinese, Japanese, and Korean text may need an explicit `w:eastAsia` font assignment in addition to `run.font.name`; font names alone do not establish glyph availability or rendered appearance.\n\nFor a new document, use the selected Python executable:\n\n```python\nfrom docx import Document\n\ndocument = Document()\ndocument.add_heading(\"Project report\", level=0)\ndocument.add_paragraph(\"Summary\", style=\"Heading 1\")\ndocument.add_paragraph(\"The requested findings go here.\")\ndocument.save(\"report.docx\")\n```\n\npython-docx does not paginate or render documents. Do not represent ordinary replacement, colored text, or comments as tracked changes. When real revisions or unsupported OOXML features matter, preserve their package parts and verify the requested operation rather than silently discarding them. When writing package parts directly, create a new ZIP and copy each unchanged member once; appending a replacement member duplicates its name and corrupts the package.\n\n## Check and deliver\n\nReopen the saved document with python-docx and verify the requested content, related formatting, and unchanged content that must be preserved. These checks complete routine validation; deliver the file once they pass. ZIP integrity, package inventories, and metadata matter only for a concrete failure.\n\nCall `office_render` on the changed page when the user asks for images or visual inspection, or when styling, font color, spacing, sizing, or text alignment is the requested edit; a request to skip rendering takes precedence. New documents and content edits, with incidental basic formatting, are checked with python-docx alone. For PDF output, call `office_convert` with `format: \"pdf\"`, then copy the returned temporary file to the destination.\n\nA fully transparent or uniformly blank image of populated content means the renderer failed, which ends visual checks for the task and leaves the source as it is. When content and structure checks pass, state the visual status only as \"Content and structure checks passed; visual inspection was not completed.\" or \"内容与结构检查通过;视觉检查未完成。\".\n\nCall `present({\"files\":[{\"path\":\"report.docx\"}]})` with the actual final DOCX path. It exposes the current file without copying or preserving its bytes; keep it in place and omit temporary QA reports unless requested. If `present` is unavailable, deliver the final workspace path with the session's supported method.\n\n## Python environment\n\nFollow an explicit user or applicable AGENTS.md requirement for a Python environment. Otherwise use the project's or user's existing Python, such as `python3` or `python` on PATH. Before the first script, check that this Python can import the libraries the workflow needs. If Python or a library is missing, tell the user which packages to install; do not install packages into a global environment without the user's agreement.\n\n"}],"source":{"kind":"skill-invocation","name":"office-docx","form":"instructions"},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"/office-docx Load the Office rendering","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1793793369677,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793793369678,"index":0,"dt":[],"id":"call_office_skill","name":"skill","args":["{\"name\":\"office-xlsx\"}"]},{"type":"chunk","time":1793793369678,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_skill","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}}},{"type":"chunk","time":1793793369678,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_office_skill"},"toolCallId":"call_office_skill","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-xlsx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Excel workbooks\n\nUse `openpyxl` and `pandas` unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below.\n\nKeep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.\n\nName Python scripts for their task, such as `edit_xlsx.py`; avoid module names such as `inspect.py`, `openpyxl.py`, or `pandas.py` that shadow imported libraries.\n\n## Read and modify\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\nopenpyxl cannot read legacy `.xls` files. Use `office_convert` with `format: \"xlsx\"`, copy the result into the workspace, then edit the copy.\n\nUse `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.\n\nUse pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.\n\nFor a new workbook, the selected Python environment can write editable values, styles, and formulas directly:\n\n```python\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Font\n\nworkbook = Workbook()\nsheet = workbook.active\nsheet.title = \"Revenue\"\nfor row in [(\"Quarter\", \"Revenue\"), (\"Q1\", 12), (\"Q2\", 18), (\"Total\", \"=SUM(B2:B3)\")]:\n sheet.append(row)\nfor cell in sheet[1]:\n cell.font = Font(bold=True)\nsheet.column_dimensions[\"A\"].width = 18\nsheet.column_dimensions[\"B\"].width = 18\nworkbook.save(\"report.xlsx\")\n```\n\nPreserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook(\"input.xlsx\", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.\n\nWriting a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate formulas; `data_only=True` returns cached values that may be absent or stale. When calculated results must be refreshed, call `office_recalculate` with `format: \"xlsx\"`, and copy the returned temporary workbook to a new file in the workspace. Open the copy with openpyxl using both `data_only=False` and `data_only=True` to check that formulas survive and cached values match the expected results. If recalculation fails, preserve the original workbook and report that calculated values were not refreshed. Do not replace requested formulas with constants or report stale or absent cached values as newly calculated results.\n\nDo not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros. Preserve the original and verify each workbook feature the task depends on.\n\n## Check and deliver\n\nReopen the saved workbook with openpyxl and verify the requested sheet names, values, types, formulas, styles, and totals against the source data, including unchanged content that must be preserved. These checks do not calculate formulas or judge workbook appearance.\n\nCall `office_render` when the user asks for images or visual inspection, or when the task targets appearance, such as cell fill colors, text alignment, spacing, or sizing; a request to skip rendering takes precedence. Do not render new workbooks or data or formula edits merely to verify accompanying bold headers or number formats; check these with openpyxl alone.\n\nRender worksheets by `sheet` and the affected `range`; worksheet numbers are not PDF page numbers. Earlier images of an unchanged source remain current. A fully transparent or uniformly blank image of populated content means the renderer failed, which ends visual checks for the task and leaves the source as it is. When content and structure checks pass, state the visual status only as \"Content and structure checks passed; visual inspection was not completed.\" or \"内容与结构检查通过;视觉检查未完成。\".\n\nRecalculate when refreshed calculated values are needed. For PDF output, call `office_convert` with `format: \"pdf\"`, then copy the returned temporary file to the destination. Deliver after the requested data checks pass and the required operations finish.\n\nCall `present({\"files\":[{\"path\":\"report.xlsx\"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session's supported file delivery method.\n\n## Python environment\n\nFollow an explicit user or applicable AGENTS.md requirement for a Python environment. Otherwise use the project's or user's existing Python, such as `python3` or `python` on PATH. Before the first script, check that this Python can import the libraries the workflow needs. If Python or a library is missing, tell the user which packages to install; do not install packages into a global environment without the user's agreement.\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"office_convert"},{"type":"tool-addition","toolName":"office_recalculate"},{"type":"tool-addition","toolName":"office_render"}],"role":"developer","id":"{{message:8}}"},"headerSeq":20},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1793793369702,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793793369702,"index":0,"dt":[],"id":"call_office_2","name":"office_tools","args":["{\"action\":\"load\"}"]},{"type":"chunk","time":1793793369702,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}}},{"type":"chunk","time":1793793369702,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_office_2","name":"office_tools","arguments":"{\"action\":\"load\"}"}} diff --git a/snapshots/session/office-skills/session.v4.jsonl b/snapshots/session/office-skills/session.v4.jsonl index 2d9f5a3fa5..c02ddac911 100644 --- a/snapshots/session/office-skills/session.v4.jsonl +++ b/snapshots/session/office-skills/session.v4.jsonl @@ -10,7 +10,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"Load the office-pptx and office-xlsx skills with the skill tool, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","load_workspace_dependencies","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","load_workspace_dependencies","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}} {"type":"session/title","data":{"title":"Load the office-pptx and office-xlsx","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"Load the requested skill."},{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"office-pptx\"}"},{"type":"tool-call","id":"call_skill_xlsx","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:5}}"},"usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5},"stream":[{"type":"chunk","time":1793628049543,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793628049543,"index":0,"dt":[],"texts":["Load the requested skill."]},{"type":"chunk","time":1793628049543,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628049543,"index":1,"dt":[],"id":"call_skill_load","name":"skill","args":["{\"name\":\"office-pptx\"}"]},{"type":"chunk","time":1793628049543,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"Load the requested skill."}}},{"type":"chunk","time":1793628049543,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_skill_load","name":"skill","arguments":"{\"name\":\"office-pptx\"}"}}},{"type":"chunk","time":1793628049543,"chunk":{"type":"block-start","index":2,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1793628049543,"index":2,"dt":[],"id":"call_skill_xlsx","name":"skill","args":["{\"name\":\"office-xlsx\"}"]},{"type":"chunk","time":1793628049543,"chunk":{"type":"block-end","index":2,"block":{"type":"tool-call","id":"call_skill_xlsx","name":"skill","arguments":"{\"name\":\"office-xlsx\"}"}}},{"type":"chunk","time":1793628049543,"chunk":{"type":"usage","usage":{"inputTokens":100,"outputTokens":20,"cacheReadTokens":0,"reasoningTokens":5}}},{"type":"chunk","time":1793628049543,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -20,7 +20,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_skill_xlsx"},"toolCallId":"call_skill_xlsx","content":[{"type":"text","text":"\n\nBase directory for this skill: {{cwd}}/office-skills/office-xlsx\nResolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.\n\n\n\n# Excel workbooks\n\nUse `openpyxl` and `pandas` unless an explicit user or applicable AGENTS.md requirement names another library. Run Python as described in the Python environment section below.\n\nKeep scripts, working files, and outputs in the task workspace. The runtime and skill directory are shared read-only resources. Save to a new workbook unless the user requests an in-place edit.\n\nName Python scripts for their task, such as `edit_xlsx.py`; avoid module names such as `inspect.py`, `openpyxl.py`, or `pandas.py` that shadow imported libraries.\n\n## Read and modify\n\nIf `office_render`, `office_convert`, or `office_recalculate` is not in your tools, load `office` with `skill`; they appear next step.\n\nopenpyxl cannot read legacy `.xls` files. Use `office_convert` with `format: \"xlsx\"`, copy the result into the workspace, then edit the copy.\n\nUse `openpyxl` for existing XLSX workbooks and targeted cell or style changes. Load with `data_only=False` when formulas must survive. Inspect sheet names, the affected cell types, formulas, styles, merged ranges, and referenced ranges before editing. Check the saved file by reopening it, including unchanged content that the request requires preserving.\n\nUse pandas for data analysis and transformations. A DataFrame is not the workbook: exporting it over an existing file can lose sheets, formulas, charts, and formatting. Write analysis results back to the intended ranges with openpyxl. `XlsxWriter` can create new workbooks, but cannot read or modify existing ones.\n\nFor a new workbook, the selected Python environment can write editable values, styles, and formulas directly:\n\n```python\nfrom openpyxl import Workbook\nfrom openpyxl.styles import Font\n\nworkbook = Workbook()\nsheet = workbook.active\nsheet.title = \"Revenue\"\nfor row in [(\"Quarter\", \"Revenue\"), (\"Q1\", 12), (\"Q2\", 18), (\"Total\", \"=SUM(B2:B3)\")]:\n sheet.append(row)\nfor cell in sheet[1]:\n cell.font = Font(bold=True)\nsheet.column_dimensions[\"A\"].width = 18\nsheet.column_dimensions[\"B\"].width = 18\nworkbook.save(\"report.xlsx\")\n```\n\nPreserve numbers, dates, booleans, and identifiers as the intended cell types; formatting is not a type conversion. For modifications, load the existing file with `openpyxl.load_workbook(\"input.xlsx\", data_only=False)`, change the requested ranges, and save a separate result. Avoid a DataFrame round trip when workbook features must survive.\n\nWriting a formula does not calculate its result. openpyxl and XlsxWriter do not evaluate formulas; `data_only=True` returns cached values that may be absent or stale. When calculated results must be refreshed, call `office_recalculate` with `format: \"xlsx\"`, and copy the returned temporary workbook to a new file in the workspace. Open the copy with openpyxl using both `data_only=False` and `data_only=True` to check that formulas survive and cached values match the expected results. If recalculation fails, preserve the original workbook and report that calculated values were not refreshed. Do not replace requested formulas with constants or report stale or absent cached values as newly calculated results.\n\nDo not rename `.xls`, `.xlsb`, encrypted files, or macro-enabled files to `.xlsx`. They need an appropriate supported operation. `keep_vba=True` can preserve VBA package content in an XLSM workflow, but does not execute or edit macros. Preserve the original and verify each workbook feature the task depends on.\n\n## Check and deliver\n\nReopen the saved workbook with openpyxl and verify the requested sheet names, values, types, formulas, styles, and totals against the source data, including unchanged content that must be preserved. These checks do not calculate formulas or judge workbook appearance.\n\nCall `office_render` when the user asks for images or visual inspection, or when the task targets appearance, such as cell fill colors, text alignment, spacing, or sizing; a request to skip rendering takes precedence. Do not render new workbooks or data or formula edits merely to verify accompanying bold headers or number formats; check these with openpyxl alone.\n\nRender worksheets by `sheet` and the affected `range`; worksheet numbers are not PDF page numbers. Earlier images of an unchanged source remain current. A fully transparent or uniformly blank image of populated content means the renderer failed, which ends visual checks for the task and leaves the source as it is. When content and structure checks pass, state the visual status only as \"Content and structure checks passed; visual inspection was not completed.\" or \"内容与结构检查通过;视觉检查未完成。\".\n\nRecalculate when refreshed calculated values are needed. For PDF output, call `office_convert` with `format: \"pdf\"`, then copy the returned temporary file to the destination. Deliver after the requested data checks pass and the required operations finish.\n\nCall `present({\"files\":[{\"path\":\"report.xlsx\"}]})` with the actual final workbook path. It exposes the current source file without copying or preserving its bytes, so keep that file in place and omit intermediate scripts and reports unless requested. If `present` is unavailable, use the session's supported file delivery method.\n\n## Python environment\n\nFollow an explicit user or applicable AGENTS.md requirement for a Python environment. Otherwise call `load_workspace_dependencies` and run scripts with its Python executable and bundled libraries. Do not install packages or search for a system Python for the default workflow. If the tool is unavailable, use an already configured environment and report a missing dependency only when it prevents the requested operation.\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[17],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","load_workspace_dependencies","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","load_workspace_dependencies","office_convert","office_recalculate","office_render","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"office_convert"},{"type":"tool-addition","toolName":"office_recalculate"},{"type":"tool-addition","toolName":"office_render"}],"role":"developer","id":"{{message:8}}"},"headerSeq":21},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The skill is loaded."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4},"stream":[{"type":"chunk","time":1793628049569,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1793628049569,"index":0,"dt":[],"texts":["The skill is loaded."]},{"type":"chunk","time":1793628049569,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1793628049570,"index":1,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1793628049570,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The skill is loaded."}}},{"type":"chunk","time":1793628049570,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1793628049570,"chunk":{"type":"usage","usage":{"inputTokens":180,"outputTokens":10,"cacheReadTokens":0,"reasoningTokens":4}}},{"type":"chunk","time":1793628049570,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} diff --git a/snapshots/session/office-skills/tool-schemas.expected.json b/snapshots/session/office-skills/tool-schemas.expected.json index 7b123f5a26..a142aaf1b4 100644 --- a/snapshots/session/office-skills/tool-schemas.expected.json +++ b/snapshots/session/office-skills/tool-schemas.expected.json @@ -142,22 +142,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -762,22 +746,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json b/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json index 49a86b7987..b48f632b42 100644 --- a/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json +++ b/snapshots/session/persistent-pwsh-tool-turn/tool-schemas.expected.json @@ -114,22 +114,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "list_agents", "description": "List your entire subagent tree: the root agent and all reachable continuable descendants, including yourself. Rows carry names, descriptions, and status. A descendant's name is its path from the root, such as reviewer/checker. You can message any other agent in the subagent tree. running means it is working; inactive means no turn is executing; it does not indicate task completion, success, or failure. corrupt, unsupported, or unavailable means this row's own descendants could not be read; the row itself is still a member you can message. While you remain active, you will be notified when a direct child finishes; there is no need to keep checking its status. Use send_message to continue the conversation.", diff --git a/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl b/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl index 42bc133f87..ae4e3e85ba 100644 --- a/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl +++ b/snapshots/session/pi-ai-conversation-updates/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Read task.txt, call the newly available snapshot_ping tool once, then reply DONE."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"moonshotai","model":"kimi-k3","contextWindow":1048576,"systemPromptUpdate":"in-history"}} {"type":"session/title","data":{"title":"Read task.txt, call the newly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:4}}"},"usage":{"inputTokens":10,"outputTokens":5},"stream":[{"type":"chunk","time":1790149644504,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644504,"index":0,"dt":[],"id":"call_task_read","name":"read","args":["{\"file_path\":\"task.txt\"}"]},{"type":"chunk","time":1790149644504,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_task_read","name":"read","arguments":"{\"file_path\":\"task.txt\"}"}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"usage","usage":{"inputTokens":10,"outputTokens":5}}},{"type":"chunk","time":1790149644504,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -18,14 +18,14 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","snapshot_ping","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:8}}"},"stream":[{"type":"chunk","time":1790149644534,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1790149644534,"index":0,"dt":[],"id":"call_dynamic_ping","name":"snapshot_ping","args":["{}"]},{"type":"chunk","time":1790149644534,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}}},{"type":"chunk","time":1790149644535,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_dynamic_ping","name":"snapshot_ping","arguments":"{}"}} {"type":"tool/result","data":{"turn":1,"step":2,"message":{"role":"tool","source":{"kind":"tool","callId":"call_dynamic_ping"},"toolCallId":"call_dynamic_ping","content":[{"type":"text","text":"pong"}],"isError":false,"id":"{{message:9}}"}},"sourceEventSeqs":[22],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":2}} {"type":"step/start","data":{"turn":1,"step":3}} -{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"moonshotai","model":"kimi-k3"},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":3,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-removal","toolName":"snapshot_ping"}],"role":"developer","id":"{{message:10}}"}},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"moonshotai","model":"kimi-k3"},"id":"{{message:11}}"},"usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10},"stream":[{"type":"chunk","time":1790149644557,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":1790149644557,"index":0,"dt":[],"texts":["DONE"]},{"type":"chunk","time":1790149644557,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"usage","usage":{"inputTokens":12,"outputTokens":2,"cacheReadTokens":10}}},{"type":"chunk","time":1790149644557,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":3}} diff --git a/snapshots/session/plugin-manager-mcp/session.v4.jsonl b/snapshots/session/plugin-manager-mcp/session.v4.jsonl index eef17eba67..934d6d0411 100644 --- a/snapshots/session/plugin-manager-mcp/session.v4.jsonl +++ b/snapshots/session/plugin-manager-mcp/session.v4.jsonl @@ -9,7 +9,7 @@ {"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Use plugin_manager with action set_plugin, target include:demo, enabled true to activate the configured MCP entry. Then call its newly discovered mcp__demo__ping tool and report the result. Do not use other tools."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","plugin_manager","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","plugin_manager","read","read_image","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}} {"type":"session/title","data":{"title":"Use plugin_manager with action set_plugi","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to activate a plugin via plugin_manager, then call an MCP tool. Let me do the plugin_manager call first.\n\nNote: they say \"Do not use other tools\" other than plugin_manager and the mcp tool. But I need to first enable it. Let's call plugin_manager set_plugin.\n\nLet me also list plugins first? The instruction says use plugin_manager with action set_plugin, target include:demo, enabled true. Let's just do that."},{"type":"tool-call","id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","arguments":"{\"action\": \"set_plugin\", \"target\": \"include:demo\", \"enabled\": true}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"75d99e21-1d47-4a33-bb88-340a1e84b749"},{"type":"tool-call"}]}},"id":"{{message:4}}"},"usage":{"inputTokens":7220,"outputTokens":174,"cacheReadTokens":0,"cacheWriteTokens":0,"totalTokens":7394},"stream":[{"type":"chunk","time":1789984418848,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789984418848,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," activate"," a"," plugin"," via"," plugin","_manager",","," then"," call"," an"," M","CP"," tool","."," Let"," me"," do"," the"," plugin","_manager"," call"," first",".\n\n","Note",":"," they"," say"," \"","Do"," not"," use"," other"," tools","\""," other"," than"," plugin","_manager"," and"," the"," m","cp"," tool","."," But"," I"," need"," to"," first"," enable"," it","."," Let","'s"," call"," plugin","_manager"," set","_","plugin",".\n\n","Let"," me"," also"," list"," plugins"," first","?"," The"," instruction"," says"," use"," plugin","_manager"," with"," action"," set","_","plugin",","," target"," include",":","demo",","," enabled"," true","."," Let","'s"," just"," do"," that","."]},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to activate a plugin via plugin_manager, then call an MCP tool. Let me do the plugin_manager call first.\n\nNote: they say \"Do not use other tools\" other than plugin_manager and the mcp tool. But I need to first enable it. Let's call plugin_manager set_plugin.\n\nLet me also list plugins first? The instruction says use plugin_manager with action set_plugin, target include:demo, enabled true. Let's just do that."}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789984418849,"index":1,"dt":[],"id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","args":[""]},{"type":"tool-call-chunks","time0":1789984418849,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"id":"call_00_xLhr9wia3A5m7wuSRWwD0436","args":["{","\"","action","\"",": ","\"","set","_","plugin","\"",", ","\"","target","\"",": ","\"","include",":","demo","\"",", ","\"","en","abled","\"",": ","true","}"]},{"type":"chunk","time":1789984418849,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_xLhr9wia3A5m7wuSRWwD0436","name":"plugin_manager","arguments":"{\"action\": \"set_plugin\", \"target\": \"include:demo\", \"enabled\": true}"}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"usage","usage":{"inputTokens":7220,"outputTokens":174,"cacheReadTokens":0,"cacheWriteTokens":0,"totalTokens":7394}}},{"type":"chunk","time":1789984418849,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"75d99e21-1d47-4a33-bb88-340a1e84b749"},{"type":"tool-call"}]}}}]},"surfaceOp":"append"} @@ -18,7 +18,7 @@ {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"system/message","data":{"turn":1,"step":2,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:6}}"}},"sourceEventSeqs":[7],"surfaceOp":{"op":"replace","startSeq":7,"endSeq":7}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_mcp_resource_templates","list_mcp_resources","mcp__demo__ping","plugin_manager","read","read_image","read_mcp_resource","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","maxTokens":256000,"reasoningEffort":"max"},"adapterDefaults":{"reasoningEffort":true,"maxTokens":true},"tools":["apply_patch","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_mcp_resource_templates","list_mcp_resources","mcp__demo__ping","plugin_manager","read","read_image","read_mcp_resource","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change","startsSeries":true}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"list_mcp_resource_templates"},{"type":"tool-addition","toolName":"list_mcp_resources"},{"type":"tool-addition","toolName":"mcp__demo__ping"},{"type":"tool-addition","toolName":"read_mcp_resource"}],"role":"developer","id":"{{message:7}}"},"headerSeq":19},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The plugin was enabled. Now call mcp__demo__ping.\n\nWait — the tool was already listed in my tools before enabling. Let's call it anyway."},{"type":"tool-call","id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"b1ec1efe-4be6-4836-a10c-e5d6bfdce520"},{"type":"tool-call"}]}},"id":"{{message:8}}"},"usage":{"inputTokens":7035,"outputTokens":59,"cacheReadTokens":768,"cacheWriteTokens":0,"totalTokens":7862},"stream":[{"type":"chunk","time":1789984418998,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1789984418998,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," plugin"," was"," enabled","."," Now"," call"," m","cp","__","demo","__","ping",".\n\n","Wait"," —"," the"," tool"," was"," already"," listed"," in"," my"," tools"," before"," enabling","."," Let","'s"," call"," it"," anyway","."]},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The plugin was enabled. Now call mcp__demo__ping.\n\nWait — the tool was already listed in my tools before enabling. Let's call it anyway."}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1789984418998,"index":1,"dt":[],"id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","args":[""]},{"type":"tool-call-chunks","time0":1789984418998,"index":1,"dt":[],"id":"call_00_miuKfLCTz5Cb38gdp8kK5186","args":["{}"]},{"type":"chunk","time":1789984418998,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"usage","usage":{"inputTokens":7035,"outputTokens":59,"cacheReadTokens":768,"cacheWriteTokens":0,"totalTokens":7862}}},{"type":"chunk","time":1789984418998,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"deepseek-v4-flash"},"blocks":[{"type":"reasoning","signature":"b1ec1efe-4be6-4836-a10c-e5d6bfdce520"},{"type":"tool-call"}]}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_00_miuKfLCTz5Cb38gdp8kK5186","name":"mcp__demo__ping","arguments":"{}"}} diff --git a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json index 9e466482ae..67353604d2 100644 --- a/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager-mcp/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -905,22 +889,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/plugin-manager/tool-schemas.expected.json b/snapshots/session/plugin-manager/tool-schemas.expected.json index 9a3cb7b7ec..cb0de5ebb9 100644 --- a/snapshots/session/plugin-manager/tool-schemas.expected.json +++ b/snapshots/session/plugin-manager/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/product-subagent-both/tool-schemas.expected.json b/snapshots/session/product-subagent-both/tool-schemas.expected.json index e0b04634a2..999751c5b9 100644 --- a/snapshots/session/product-subagent-both/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-both/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/product-subagent-codex/tool-schemas.expected.json b/snapshots/session/product-subagent-codex/tool-schemas.expected.json index e4f873ab07..23570e15e5 100644 --- a/snapshots/session/product-subagent-codex/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-codex/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/product-subagent-oar/tool-schemas.expected.json b/snapshots/session/product-subagent-oar/tool-schemas.expected.json index dcb39765d0..c42658816f 100644 --- a/snapshots/session/product-subagent-oar/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-oar/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json b/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json index a803e45fba..3c64ee2747 100644 --- a/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json +++ b/snapshots/session/product-subagent-result-diagnostic/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/ptc-persistent/system-prompt.expected.md b/snapshots/session/ptc-persistent/system-prompt.expected.md index d4bd10b89b..89e23ec4fa 100644 --- a/snapshots/session/ptc-persistent/system-prompt.expected.md +++ b/snapshots/session/ptc-persistent/system-prompt.expected.md @@ -120,11 +120,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -393,9 +388,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/ptc-policy-change/system-prompt.expected.md b/snapshots/session/ptc-policy-change/system-prompt.expected.md index 6679176807..ca761dccb8 100644 --- a/snapshots/session/ptc-policy-change/system-prompt.expected.md +++ b/snapshots/session/ptc-policy-change/system-prompt.expected.md @@ -120,11 +120,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -391,9 +386,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/ptc-python-turn/system-prompt.expected.md b/snapshots/session/ptc-python-turn/system-prompt.expected.md index 1e477ace45..0873748931 100644 --- a/snapshots/session/ptc-python-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-python-turn/system-prompt.expected.md @@ -236,14 +236,6 @@ class GrepOutputMatches(TypedDict): class GrepOutput(TypedDict): matches: list[GrepOutputMatches] -class InterruptAgentArgs(TypedDict): - # The name of an agent created under you: your direct child or a deeper descendant. - agent: str - # Additional keys beyond those declared are allowed. - -class InterruptAgentOutput(TypedDict): - accepted: bool - class JobKillArgs(TypedDict): # Job id returned by the tool that started the background work. job_id: str @@ -551,8 +543,6 @@ class Tools(Protocol): """Find files, not directories, whose paths match a glob pattern, including hidden and ignored files. Returns up to 100 paths in modification-time order; a larger result keeps the first paths and reports where the complete list was saved.""" async def grep(self, args: GrepArgs) -> GrepOutput: """Search file contents with a ripgrep regular expression. Returns matching lines with line numbers, grouped by file. Returns up to 250 matches; a larger result reports where the complete match list was saved.""" - async def interrupt_agent(self, args: InterruptAgentArgs) -> InterruptAgentOutput: - """Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.""" async def job_kill(self, args: JobKillArgs) -> JobKillOutput: """Request cancellation of a running background job.""" async def job_list(self, args: dict[str, Any]) -> list[JobListOutput]: diff --git a/snapshots/session/ptc-read-image/system-prompt.expected.md b/snapshots/session/ptc-read-image/system-prompt.expected.md index 322fc6ae12..08651e72a0 100644 --- a/snapshots/session/ptc-read-image/system-prompt.expected.md +++ b/snapshots/session/ptc-read-image/system-prompt.expected.md @@ -120,11 +120,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -389,9 +384,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index dd88fa8d9e..fe5f42348b 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -180,11 +180,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -454,9 +449,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/ptc-turn/system-prompt.expected.md b/snapshots/session/ptc-turn/system-prompt.expected.md index 026b5523c5..55ff52414b 100644 --- a/snapshots/session/ptc-turn/system-prompt.expected.md +++ b/snapshots/session/ptc-turn/system-prompt.expected.md @@ -120,11 +120,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -393,9 +388,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json b/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json index 69bf8f0cc3..1343ed9d8e 100644 --- a/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json +++ b/snapshots/session/pty-tools-sandbox-backend/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json b/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json index bb43126dd4..cd4dea7393 100644 --- a/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json +++ b/snapshots/session/pwsh-tool-turn/tool-schemas.expected.json @@ -114,22 +114,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/ralph-loop/tool-schemas.1.expected.json b/snapshots/session/ralph-loop/tool-schemas.1.expected.json index 2bee257e89..a1cbe4db85 100644 --- a/snapshots/session/ralph-loop/tool-schemas.1.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/ralph-loop/tool-schemas.2.expected.json b/snapshots/session/ralph-loop/tool-schemas.2.expected.json index 2bee257e89..a1cbe4db85 100644 --- a/snapshots/session/ralph-loop/tool-schemas.2.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.2.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/ralph-loop/tool-schemas.expected.json b/snapshots/session/ralph-loop/tool-schemas.expected.json index b5ebba3799..d9c16c2fee 100644 --- a/snapshots/session/ralph-loop/tool-schemas.expected.json +++ b/snapshots/session/ralph-loop/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/session-query-spill/tool-schemas.expected.json b/snapshots/session/session-query-spill/tool-schemas.expected.json index f43e5f586d..1f68092d11 100644 --- a/snapshots/session/session-query-spill/tool-schemas.expected.json +++ b/snapshots/session/session-query-spill/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json b/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json index 3ab6a2fc39..e106eb2948 100644 --- a/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json +++ b/snapshots/session/subagent-acp-diagnostic/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json b/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json index d74795aead..f44253beb1 100644 --- a/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-agent-preset/tool-schemas.1.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/subagent-agent-preset/tool-schemas.expected.json b/snapshots/session/subagent-agent-preset/tool-schemas.expected.json index 089af47c6f..bc17f7317b 100644 --- a/snapshots/session/subagent-agent-preset/tool-schemas.expected.json +++ b/snapshots/session/subagent-agent-preset/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json b/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json index a64d9377c1..a68e1bba9c 100644 --- a/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json +++ b/snapshots/session/subagent-child-question-rejection/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/subagent-no-message-tool/cordis.snapshot.yml b/snapshots/session/subagent-no-message-tool/cordis.snapshot.yml index 3cbd35c106..380fbee018 100644 --- a/snapshots/session/subagent-no-message-tool/cordis.snapshot.yml +++ b/snapshots/session/subagent-no-message-tool/cordis.snapshot.yml @@ -73,6 +73,8 @@ fetch: true searchTimeoutMs: 60000 - name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: preset-child name: '@deepseek-ai/dsh-agent-preset' config: diff --git a/snapshots/session/subagent-no-message-tool/cordis.yml b/snapshots/session/subagent-no-message-tool/cordis.yml index 0f15062ac9..fa1f0dbd6c 100644 --- a/snapshots/session/subagent-no-message-tool/cordis.yml +++ b/snapshots/session/subagent-no-message-tool/cordis.yml @@ -32,6 +32,8 @@ fetch: true searchTimeoutMs: 60000 - name: '@deepseek-ai/dsh-tool-subagent-control' + config: + interrupt: false - id: preset-child name: '@deepseek-ai/dsh-agent-preset' config: diff --git a/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json b/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json index c52a5d9a66..4f86239c75 100644 --- a/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json +++ b/snapshots/session/subagent-tool-filter/tool-schemas.1.expected.json @@ -73,22 +73,6 @@ "properties": {} } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/team-targets/cordis.snapshot.yml b/snapshots/session/team-targets/cordis.snapshot.yml index 061e1b28a9..4c1be6faf4 100644 --- a/snapshots/session/team-targets/cordis.snapshot.yml +++ b/snapshots/session/team-targets/cordis.snapshot.yml @@ -47,3 +47,7 @@ - insert: - id: enable-team-fixture name: ../../../packages/team/agent-team/tests/enable-team-fixture.ts + +- id: tool-subagent-control + config: + interrupt: true diff --git a/snapshots/session/team-targets/cordis.yml b/snapshots/session/team-targets/cordis.yml index b09a716ba0..fe7ac6df21 100644 --- a/snapshots/session/team-targets/cordis.yml +++ b/snapshots/session/team-targets/cordis.yml @@ -1,3 +1,7 @@ - insert: - id: enable-team-fixture name: ../../../packages/team/agent-team/tests/enable-team-fixture.ts + +- id: tool-subagent-control + config: + interrupt: true diff --git a/snapshots/session/terminal-panel-tools/tool-schemas.expected.json b/snapshots/session/terminal-panel-tools/tool-schemas.expected.json index 96b394650d..0a1bbcadda 100644 --- a/snapshots/session/terminal-panel-tools/tool-schemas.expected.json +++ b/snapshots/session/terminal-panel-tools/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/text-turn/tool-schemas.expected.json b/snapshots/session/text-turn/tool-schemas.expected.json index 53f6a4bf69..08fc35470a 100644 --- a/snapshots/session/text-turn/tool-schemas.expected.json +++ b/snapshots/session/text-turn/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/web-fetch/tool-schemas.expected.json b/snapshots/session/web-fetch/tool-schemas.expected.json index 7429a130fa..1f122af658 100644 --- a/snapshots/session/web-fetch/tool-schemas.expected.json +++ b/snapshots/session/web-fetch/tool-schemas.expected.json @@ -187,22 +187,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/workspace-dependencies/tool-schemas.expected.json b/snapshots/session/workspace-dependencies/tool-schemas.expected.json index ff780e4c28..85be772822 100644 --- a/snapshots/session/workspace-dependencies/tool-schemas.expected.json +++ b/snapshots/session/workspace-dependencies/tool-schemas.expected.json @@ -142,22 +142,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/session/worktree/tool-schemas.expected.json b/snapshots/session/worktree/tool-schemas.expected.json index e14f6246bf..273604b19b 100644 --- a/snapshots/session/worktree/tool-schemas.expected.json +++ b/snapshots/session/worktree/tool-schemas.expected.json @@ -204,22 +204,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/web/collapse-timing/next-message.expected.md b/snapshots/web/collapse-timing/next-message.expected.md index 8e6393f8ec..68d30345d0 100644 --- a/snapshots/web/collapse-timing/next-message.expected.md +++ b/snapshots/web/collapse-timing/next-message.expected.md @@ -14,7 +14,7 @@ - button "Context injection runtime-context" - button "Context injection skill-catalog" - button "Context injection time-context" -- button "Tools updated 34 added" +- button "Tools updated 33 added" - button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." - paragraph: DONE - button "Copy" diff --git a/snapshots/web/collapse-timing/verbose.expected.md b/snapshots/web/collapse-timing/verbose.expected.md index 6652729078..60117faf20 100644 --- a/snapshots/web/collapse-timing/verbose.expected.md +++ b/snapshots/web/collapse-timing/verbose.expected.md @@ -22,7 +22,7 @@ - button "Context injection runtime-context" - button "Context injection skill-catalog" - button "Context injection time-context" -- button "Tools updated 34 added" +- button "Tools updated 33 added" - button "Think Both files have been read. a.txt contains \"alpha\" and b.txt contains \"beta\". I'll now reply with DONE as instructed." - paragraph: DONE - button "Copy" diff --git a/snapshots/web/creation-recommendations/session.v4.jsonl b/snapshots/web/creation-recommendations/session.v4.jsonl index 3cf76fcece..e616ebffff 100644 --- a/snapshots/web/creation-recommendations/session.v4.jsonl +++ b/snapshots/web/creation-recommendations/session.v4.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `dsh-doc`: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n- `official-plugins`: Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers.\n- `personalized-pages`: Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"dsh-doc","description":"Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile."},{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."},{"name":"official-plugins","description":"Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers."},{"name":"personalized-pages","description":"Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"I wish I had a","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792674450282,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792674450282,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}}},{"type":"chunk","time":1792674450283,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_creation_skill"},"toolCallId":"call_creation_skill","content":[{"type":"text","text":"\n\nResources for this skill are managed by provider \"dsh-personalized-pages\".\nLoad referenced resources only as needed.\n\n\n\n# Personalized pages\n\nUse this workflow in the main conversation to plan an optional new page or small tool for any task, not just DSH. You decide whether a page helps, check existing capabilities, and hand the Creator a short plan. A `propose_action` call saves the proposal and shows a card below your answer; nothing is built until the user clicks Create. Plan from the conversation and the catalog at the end of this skill. Do not read files, configuration or source to validate a page idea; name an uninspected source as an unverified dependency and leave its details to the Creator.\n\n## When to propose\n\nPropose a page in these cases:\n\n- The user asks for a page, tab, panel, tool or interface in this app, or says they want something to keep, revisit or update later (“以后每次”, “能不能一直”, “希望能有”). One-off use still qualifies when the interface is explicitly requested.\n- Your answer is a table, list or chart, and the user has said the data will keep changing or that they will interact with it (“每周更新”, “我来改状态”, “要勾选”). The continuation must come from the user's own words; a table alone, or data that merely looks dynamic, is not enough. Deliver the requested answer first, then offer the page.\n- The user wants to keep watching live data of this app itself (a Session's usage, a running task's output, files changing in the workspace). A text answer cannot stay current, so a page qualifies even without the words above; name the data source in the brief and leave how it is read to the Creator.\n\nDo not propose a page in these cases:\n\n- The user asks for a file, code, document or an existing-project change: keep that delivery form.\n- The wish appears inside quoted text, pasted content, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks how an existing feature works, or has declined recommendations or asked for text only: stay silent on pages for the rest of this conversation.\n- The request changes a page created earlier: explain how it would change, do not create a replacement copy, and do not claim an update happened.\n- The request is a capability the agent lacks, such as a tool, automation or access, rather than a page: check the catalog below and point to the official plugin that provides it; do not plan a page around a missing tool.\n\n## Check existing capabilities\n\nCompare the need with the official plugins listed at the end of this skill. If one covers it, say its name, what it does, whether it is enabled, and that it lives under Plugins; offer no page card. A partial match does not cancel an explicit unmet need. The catalog is not a full inventory of built-in UI: missing details do not prove absence, and do not read source to find out. DSH already has Chat, Trajectory, a right sidebar for files and context, and a Plugins page.\n\n## Plan and hand off\n\nThe Creator cannot read this conversation. Give it exactly these fields:\n\n| Field | Contents |\n|:--|:--|\n| `title` | Short page name in the user's language. |\n| `brief` | One to three sentences: purpose, behavior, input, calculations and persistence scope. It is the card text and the implementation request at once. |\n| `initialContent` | Only supplied content the page starts with: items, rows, values, units and period, preserving gaps. Omit for an empty page. |\n| `slot` | Location, chosen below. |\n\nKeep the plan to what was asked or agreed. Editing, deletion, history, extra fields, data sources and automation need a basis in the request. Resolve “these items” into the actual content. Content that mentions an action stays content. Keep each number's meaning and period; a weekly addition is not a cumulative total. If an unresolved distinction changes a calculation, give the factual answer, ask one question, and propose later.\n\n## Choose the location\n\nHonor a location the user named. Otherwise:\n\n- `sidebar-right`: content tied to this Session or task, especially anything to watch while chatting, including live logs.\n- `sidebar-left`: a global feature or an ongoing personal record used across Sessions, opened from a left entry as a standalone page.\n- `page`: a Session-bound streaming view or interaction in a tab beside Chat and Trajectory, only when the user does not need it visible while chatting.\n\nSupplying data in this conversation does not make a record Session-bound.\n\n## Offer without starting\n\nTo propose, call `propose_action` once, in the same turn as loading this skill, with `action: \"create_personalized_page\"`, `title`, `brief` and `details` holding `slot` and, when there is supplied content, `initialContent`. The call is the submission: the card appears below your answer; a refused call creates no card, and its error says why. Then write your final answer. One proposal per turn, and one unstarted card per conversation: if a card is still waiting, do not propose another; a new proposal replaces it only when the user changed the plan. Plan-only and read-only requests still get a card; do not ask for approval instead of proposing it. Only clicking Create starts the background Creator; do not wait, poll, claim installation or ask for a report-back. Answer any direct question; the call's result says how to end the answer. Do not repeat the plan, list extra features, narrate the call or mention schema names.\n\n```json\n{\"action\":\"create_personalized_page\",\"title\":\"本次验收清单\",\"brief\":\"在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。\",\"details\":{\"slot\":\"sidebar-right\",\"initialContent\":\"1. 导出成功\\n2. 断网提示清楚\"}}\n```\n\n## Examples\n\n- “想有个地方放书签,以后自己加标题和网址;旧的不用导入。” → `brief`: “提供一个可反复打开的书签页,手动新增标题和网址并保存到本机,从空白开始。” No `initialContent`. `sidebar-left`.\n- “当前会话旁放验收清单,能勾选和取消,状态跟着会话。条目:导出成功;断网提示清楚。” → `brief`: “在当前会话右侧展示验收清单,可勾选和取消,状态随会话保存。” `initialContent`: “1. 导出成功\\n2. 断网提示清楚”. `sidebar-right`.\n- “这三周 bug 数 12、9、15,说说趋势。以后每周我把新数字贴给你,想自己更新着看。” → answer the trend first, then `brief`: “按周手动录入 bug 数并展示各周变化,保存到本机。” `initialContent`: “第 1 周 12,第 2 周 9,第 3 周 15”. `sidebar-left`.\n- “我想用语音说话代替打字。” → the catalog lists 语音输入; explain it and where to enable it; no card.\n- “把我之前做的读书页评分改成五星。” → explain the change to that page; no card and no copy.\n- “帮我把这句话翻成英文:我想要一个所有会话都能打开的读书页。” → translate only; no card.\n- “把三个方案排成表格比较一下,看完就行。” → the table only; no card.\n\n## Existing capabilities to check against this page plan\n\n[{\"name\":\"@deepseek-ai/dsh-personalized-recommendations\",\"title\":{\"en\":\"Personalized recommendations\",\"de\":\"Personalisierte Empfehlungen\",\"es\":\"Recomendaciones personalizadas\",\"fr\":\"Recommandations personnalisées\",\"ja\":\"パーソナライズされたおすすめ\",\"pt\":\"Recomendações personalizadas\",\"ru\":\"Персональные рекомендации\",\"zh\":\"个性化推荐\"},\"description\":{\"en\":\"Shows recommendation cards below the answer for what you want from DSH: when you want a page or small tool you can keep, it proposes a new personalized page, built in the background after you click Create; when you ask how to do something in this app or say a capability is missing, it recommends the built-in plugin that provides it, turned on when you click Enable.\",\"de\":\"Zeigt für Ihre individuellen Anforderungen an DSH Empfehlungskarten unter der Antwort an: Wenn Sie eine Seite oder ein kleines Tool zur dauerhaften Nutzung möchten, wird eine neue personalisierte Seite vorgeschlagen, die nach einem Klick auf Erstellen im Hintergrund erstellt wird; wenn Sie fragen, wie etwas in dieser App geht, oder sagen, dass eine Funktion fehlt, wird das integrierte Plugin empfohlen, das sie bereitstellt, und nach einem Klick auf Aktivieren eingeschaltet.\",\"es\":\"Muestra tarjetas de recomendación debajo de la respuesta para tus necesidades personalizadas en DSH: cuando quieres una página o una pequeña herramienta para conservar, propone una nueva página personalizada, que se genera en segundo plano al hacer clic en Crear; cuando preguntas cómo hacer algo en esta aplicación o dices que falta una función, recomienda el complemento integrado que la ofrece, que se activa al hacer clic en Habilitar.\",\"fr\":\"Affiche des cartes de recommandation sous la réponse pour vos besoins personnalisés dans DSH : lorsque vous voulez une page ou un petit outil à conserver, propose une nouvelle page personnalisée, générée en arrière-plan après un clic sur Créer ; lorsque vous demandez comment faire quelque chose dans cette application ou signalez qu’une fonctionnalité manque, recommande le plugin intégré qui la fournit, activé lorsque vous cliquez sur Activer.\",\"ja\":\"DSH に対するあなた個人のニーズに合わせて、回答の下におすすめカードを表示します。長く使えるページや小さなツールが欲しいときは新しいパーソナルページを提案し、「作成」をクリックするとバックグラウンドで生成します。このアプリで何かをする方法を尋ねたときや機能が足りないと言ったときは、それを提供する内蔵プラグインを推薦し、「有効にする」をクリックすると有効になります。\",\"pt\":\"Mostra cartões de recomendação abaixo da resposta para suas necessidades personalizadas no DSH: quando você quer uma página ou uma pequena ferramenta para manter, propõe uma nova página personalizada, gerada em segundo plano depois que você clica em Criar; quando você pergunta como fazer algo neste aplicativo ou diz que falta um recurso, recomenda o plug-in integrado que o oferece, ativado quando você clica em Ativar.\",\"ru\":\"Показывает карточки рекомендаций под ответом с учетом ваших индивидуальных потребностей в DSH: когда вам нужна страница или небольшой инструмент для постоянного использования, предлагает новую персональную страницу, которая создается в фоне после нажатия «Создать»; когда вы спрашиваете, как что-то сделать в этом приложении, или говорите, что не хватает какой-то возможности, рекомендует встроенный плагин, который ее предоставляет, и включает его после нажатия «Включить».\",\"zh\":\"针对你对 DSH 的个性化需求,在回答下方展示推荐卡片:想要能长期使用的页面或小工具时,提议新增个性化页面,点击创建后在后台生成;问到本应用怎么做某件事或缺少某项能力时,推荐对应的内置插件,点击启用后开启。\"},\"enabled\":true},{\"name\":\"@deepseek-ai/dsh-experimental-inspector-profile\",\"title\":{\"en\":\"Developer tools\",\"de\":\"Entwicklertools\",\"es\":\"Herramientas de desarrollador\",\"fr\":\"Outils de développement\",\"ja\":\"開発者ツール\",\"pt\":\"Ferramentas de desenvolvedor\",\"ru\":\"Инструменты разработчика\",\"zh\":\"开发者工具\"},\"description\":{\"en\":\"For troubleshooting: view what DSH recorded for a session in Session log, inspect per-turn and per-step statistics in the Statistics tab, and debug the DSH backend in Chrome DevTools.\",\"de\":\"Zur Fehlersuche: Sehen Sie in „Sitzungsprotokoll“, was DSH für eine Sitzung aufgezeichnet hat, prüfen Sie im Tab „Statistik“ Kontext, Dauer, Cache und Werkzeugkosten pro Runde und Schritt und debuggen Sie das DSH-Backend in Chrome DevTools.\",\"es\":\"Para solucionar problemas: vea en «Registro de sesión» lo que DSH registró de una sesión, consulte el contexto, los tiempos, la caché y el coste de herramientas por turno y paso en la pestaña «Estadísticas», y depure el backend de DSH en Chrome DevTools.\",\"fr\":\"Pour le dépannage : consultez dans « Journal de session » ce que DSH a enregistré pour une session, examinez le contexte, les durées, le cache et le coût des outils par tour et étape dans l’onglet « Statistiques », et déboguez le backend de DSH dans Chrome DevTools.\",\"ja\":\"トラブルシューティング用です。「セッションログ」で DSH がセッションについて記録した内容を確認し、「統計」タブでターン/ステップごとのコンテキスト、時間、キャッシュ、ツールコストを確認し、Chrome DevTools で DSH バックエンドをデバッグできます。\",\"pt\":\"Para solução de problemas: veja em «Registro da sessão» o que o DSH registrou de uma sessão, consulte contexto, tempos, cache e custo de ferramentas por turno e etapa na aba «Estatísticas» e depure o backend do DSH no Chrome DevTools.\",\"ru\":\"Для диагностики: просматривайте в «Журнале сеанса», что DSH записал для сеанса, смотрите контекст, время, кэш и стоимость инструментов по ходам и шагам на вкладке «Статистика» и отлаживайте бэкенд DSH в Chrome DevTools.\",\"zh\":\"用于排查问题:在「会话数据诊断」中查看 DSH 为会话记录的内容,在「统计」页签查看每轮/每步的上下文、耗时、缓存和工具成本,并在 Chrome DevTools 中调试 DSH 后端。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\",\"title\":{\"en\":\"Voice input\",\"de\":\"Spracheingabe\",\"es\":\"Entrada de voz\",\"fr\":\"Saisie vocale\",\"ja\":\"音声入力\",\"pt\":\"Entrada de voz\",\"ru\":\"Голосовой ввод\",\"zh\":\"语音输入\"},\"description\":{\"en\":\"Transcribe recordings locally with SenseVoice; first use requires installing dependencies.\",\"de\":\"Transkribieren Sie Aufnahmen lokal mit SenseVoice; Für die erste Verwendung müssen Abhängigkeiten installiert werden.\",\"es\":\"Transcribe grabaciones localmente con SenseVoice; El primer uso requiere instalar dependencias.\",\"fr\":\"Transcrivez les enregistrements localement avec SenseVoice ; la première utilisation nécessite l'installation de dépendances.\",\"ja\":\"ローカルの SenseVoice で録音を文字に起こします。初回利用時には依存関係のインストールが必要です。\",\"pt\":\"Transcreva gravações localmente com SenseVoice; o primeiro uso requer a instalação de dependências.\",\"ru\":\"Транскрибируйте записи локально с помощью SenseVoice; при первом использовании требуется установка зависимостей.\",\"zh\":\"在本机使用 SenseVoice 转写录音,首次使用需安装依赖。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-auto-review\",\"title\":{\"en\":\"Auto authorization review\",\"de\":\"Automatische Autorisierungsüberprüfung\",\"es\":\"Revisión de autorización automática\",\"fr\":\"Examen des autorisations automatiques\",\"ja\":\"自動認可レビュー\",\"pt\":\"Revisão de autorização automática\",\"ru\":\"Проверка автоматической авторизации\",\"zh\":\"自动授权审查\"},\"description\":{\"en\":\"Adds an Auto review access mode: before each tool call, a model checks it against what you asked for, runs allowed calls at once, and holds denied calls for your approval.\",\"de\":\"Fügt den Zugriffsmodus „Auto review“ hinzu: Vor jedem Tool-Aufruf prüft ein Modell den Aufruf anhand Ihrer Anforderung; zugelassene Aufrufe laufen sofort, abgelehnte Aufrufe warten auf Ihre Genehmigung.\",\"es\":\"Añade el modo de acceso “Auto review”: antes de cada llamada a una herramienta, un modelo comprueba la llamada frente a lo que usted pidió; las llamadas permitidas se ejecutan de inmediato y las denegadas esperan su aprobación.\",\"fr\":\"Ajoute le mode d'accès « Auto review » : avant chaque appel d'outil, un modèle vérifie l'appel par rapport à ce que vous avez demandé ; les appels autorisés s'exécutent immédiatement et les appels refusés attendent votre approbation.\",\"ja\":\"「自動認可レビュー」アクセスモードを追加します。各ツール呼び出しの前に、モデルがその呼び出しをあなたの依頼内容と照らし合わせて確認し、許可された呼び出しは即座に実行され、拒否された呼び出しはあなたの承認を待ちます。\",\"pt\":\"Adiciona o modo de acesso “Auto review”: antes de cada chamada de ferramenta, um modelo verifica a chamada em relação ao que você pediu; as chamadas permitidas são executadas imediatamente e as negadas aguardam sua aprovação.\",\"ru\":\"Добавляет режим доступа «Auto review»: перед каждым вызовом инструмента модель сверяет вызов с вашей просьбой; разрешённые вызовы выполняются сразу, а отклонённые ждут вашего одобрения.\",\"zh\":\"提供“自动审查”访问模式:每次工具调用前,由模型对照你的要求检查,获准的调用立即运行,被拒绝的调用等你审批。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-cot-translation-bundle\",\"title\":{\"en\":\"Machine translation of reasoning\",\"de\":\"Maschinelle Übersetzung der Argumentation\",\"es\":\"Traducción automática de razonamiento\",\"fr\":\"Traduction automatique du raisonnement\",\"ja\":\"思考内容の機械翻訳\",\"pt\":\"Tradução automática de raciocínio\",\"ru\":\"Машинный перевод рассуждений\",\"zh\":\"思考过程机器翻译\"},\"description\":{\"en\":\"Translates expanded Think rows into your chosen language as the agent writes them, and View original switches back.\",\"de\":\"Übersetzt aufgeklappte „Denken Sie nach“-Zeilen, während der Agent sie schreibt, in die von Ihnen gewählte Sprache, und „Original ansehen“ wechselt zurück.\",\"es\":\"Traduce las filas “pensar” expandidas al idioma que elija mientras el agente las escribe, y “Ver original” vuelve al texto original.\",\"fr\":\"Traduit les lignes « Pensez » développées dans la langue de votre choix pendant que l'agent les écrit, et « Voir l'original » permet de revenir au texte d'origine.\",\"ja\":\"エージェントが書き出すのと同時に、展開された「思考」行を選択した言語に翻訳します。「原文を表示」で原文に戻せます。\",\"pt\":\"Traduz as linhas “Pense” expandidas para o idioma que você escolher enquanto o agente as escreve, e “Ver original” volta ao texto original.\",\"ru\":\"Переводит развёрнутые строки «Подумайте» на выбранный вами язык по мере того, как агент их пишет, а «Посмотреть оригинал» возвращает исходный текст.\",\"zh\":\"智能体输出时,把展开的“思考”行翻译成你选择的语言,点击“查看原文”可切换回原文。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-badge-skill-bundle\",\"title\":{\"en\":\"DSH badge skill\",\"de\":\"DSH-Abzeichen-Fertigkeit\",\"es\":\"Habilidad de insignia DSH\",\"fr\":\"Compétence du badge DSH\",\"ja\":\"DSH バッジスキル\",\"pt\":\"DSH habilidade de distintivo\",\"ru\":\"DSH значок навыка\",\"zh\":\"DSH 徽章技能\"},\"description\":{\"en\":\"Let agents add a “powered by dsh” badge to documents, pull requests, and other outputs.\",\"de\":\"Lassen Sie Agenten Dokumente, Pull-Requests und andere Ausgaben mit einem „powered by dsh“-Badge versehen.\",\"es\":\"Permita que los agentes agreguen una insignia \\\"con tecnología de dsh\\\" a documentos, solicitudes de extracción y otros resultados.\",\"fr\":\"Laissez les agents ajouter un badge « propulsé par dsh » aux documents, demandes d'extraction et autres sorties.\",\"ja\":\"エージェントが文書や PR などの成果物に「powered by dsh」バッジを追加できます。\",\"pt\":\"Permita que os agentes adicionem um selo “powered by dsh” a documentos, pull requests e outros resultados.\",\"ru\":\"Позвольте агентам добавлять значок «Powered by dsh» к документам, запросам на включение и другим результатам.\",\"zh\":\"让 Agent 为文档、PR 等产出添加「powered by dsh」徽章。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-ralph-bundle\",\"title\":{\"en\":\"Ralph loops\",\"de\":\"Ralph-Loops\",\"es\":\"Bucles de Ralph\",\"fr\":\"Boucles Ralph\",\"ja\":\"Ralph ループ\",\"pt\":\"Loops de Ralph\",\"ru\":\"Ральф петли\",\"zh\":\"Ralph 循环\"},\"description\":{\"en\":\"Ask for a Ralph loop with a goal, and the agent starts a fresh agent on it round after round until the goal is met, a blocker is reported, or the round limit is reached.\",\"de\":\"Bitten Sie um eine Ralph-Schleife mit einem Ziel, und der Agent startet Runde um Runde einen neuen Agenten darauf, bis das Ziel erreicht ist, ein Hindernis gemeldet wird oder das Rundenlimit erreicht ist.\",\"es\":\"Pida un bucle Ralph con un objetivo, y el agente inicia un agente nuevo sobre él ronda tras ronda hasta que se cumpla el objetivo, se informe de un bloqueo o se alcance el límite de rondas.\",\"fr\":\"Demandez une boucle Ralph avec un objectif, et l'agent lance un nouvel agent dessus, tour après tour, jusqu'à ce que l'objectif soit atteint, qu'un blocage soit signalé ou que la limite de tours soit atteinte.\",\"ja\":\"目標を指定して Ralph ループを依頼すると、エージェントは、目標が達成されるか、阻害要因が報告されるか、ラウンド数の上限に達するまで、ラウンドごとに新しいエージェントを起動してその目標に取り組ませます。\",\"pt\":\"Peça um loop Ralph com um objetivo, e o agente inicia um novo agente nele rodada após rodada até que o objetivo seja atingido, um bloqueio seja informado ou o limite de rodadas seja alcançado.\",\"ru\":\"Попросите запустить цикл Ralph с целью, и агент будет раунд за раундом запускать для неё нового агента, пока цель не будет достигнута, не будет сообщено о препятствии или не будет достигнут лимит раундов.\",\"zh\":\"要求用 Ralph 循环完成一个目标后,智能体会一轮接一轮地启动新的智能体处理它,直到目标达成、报告受阻或达到轮次上限。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-titles-bundle\",\"title\":{\"en\":\"Conversation-following titles\",\"de\":\"Konversationsfolgende Titel\",\"es\":\"Títulos que siguen la conversación\",\"fr\":\"Titres de suivi de conversation\",\"ja\":\"会話に追従するタイトル\",\"pt\":\"Títulos que acompanham conversas\",\"ru\":\"Заголовки, следующие за разговором\",\"zh\":\"随对话更新的标题\"},\"description\":{\"en\":\"Writes a session's title from all of your messages and updates it when the main task changes, instead of only from the first message.\",\"de\":\"Erstellt den Titel einer Sitzung aus all Ihren Nachrichten und aktualisiert ihn, wenn sich die Hauptaufgabe ändert, statt ihn nur aus der ersten Nachricht zu bilden.\",\"es\":\"Escribe el título de una sesión a partir de todos sus mensajes y lo actualiza cuando cambia la tarea principal, en lugar de basarse solo en el primer mensaje.\",\"fr\":\"Rédige le titre d'une session à partir de tous vos messages et le met à jour lorsque la tâche principale change, au lieu de se baser uniquement sur le premier message.\",\"ja\":\"最初のメッセージだけでなく、あなたのすべてのメッセージからセッションのタイトルを作成し、主なタスクが変わったときに更新します。\",\"pt\":\"Escreve o título de uma sessão a partir de todas as suas mensagens e o atualiza quando a tarefa principal muda, em vez de usar apenas a primeira mensagem.\",\"ru\":\"Составляет заголовок сеанса по всем вашим сообщениям и обновляет его при смене основной задачи, а не только по первому сообщению.\",\"zh\":\"根据你的所有消息生成会话标题,并在主要任务变化时更新,而不是只根据第一条消息生成。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-terminal-bundle\",\"title\":{\"en\":\"Persistent terminals\",\"de\":\"Persistente Terminals\",\"es\":\"Terminales persistentes\",\"fr\":\"Terminaux persistants\",\"ja\":\"永続ターミナル\",\"pt\":\"Terminais persistentes\",\"ru\":\"Постоянные терминалы\",\"zh\":\"持久终端\"},\"description\":{\"en\":\"Gives the agent terminals that open as sidebar tabs you can watch and take over by typing in them. Processes keep running between tool calls, so it can start a dev server or REPL and come back later to read output; it can also read terminals you open yourself.\",\"de\":\"Stellt dem Agenten Terminals bereit, die als Seitenleisten-Tabs geöffnet werden; Sie können zusehen und durch Tippen die Kontrolle übernehmen. Prozesse laufen zwischen Tool-Aufrufen weiter, sodass er einen Entwicklungsserver oder eine REPL starten und später die Ausgabe lesen kann; er kann auch Terminals lesen, die Sie selbst öffnen.\",\"es\":\"Proporciona al agente terminales que se abren como pestañas de la barra lateral, que puede observar y controlar escribiendo en ellas. Los procesos siguen ejecutándose entre llamadas a herramientas, de modo que puede iniciar un servidor de desarrollo o un REPL y volver más tarde para leer la salida; también puede leer los terminales que usted abra.\",\"fr\":\"Fournit à l'agent des terminaux qui s'ouvrent comme onglets de la barre latérale ; vous pouvez les observer et en prendre le contrôle en y tapant. Les processus continuent de s'exécuter d'un appel d'outil à l'autre, afin qu'il puisse lancer un serveur de développement ou un REPL et revenir plus tard lire la sortie ; il peut aussi lire les terminaux que vous ouvrez vous-même.\",\"ja\":\"エージェントに、サイドバーのタブとして開くターミナルを提供します。様子を見守ることができ、入力すれば操作を引き継げます。プロセスはツール呼び出し間も実行され続けるため、開発サーバーや REPL を起動して後から出力を読めます。あなたが自分で開いたターミナルも読み取れます。\",\"pt\":\"Fornece ao agente terminais que abrem como abas da barra lateral, que você pode acompanhar e assumir digitando neles. Os processos continuam em execução entre chamadas de ferramentas, para que ele possa iniciar um servidor de desenvolvimento ou um REPL e voltar depois para ler a saída; ele também pode ler os terminais que você mesmo abrir.\",\"ru\":\"Предоставляет агенту терминалы, которые открываются вкладками боковой панели; вы можете наблюдать за ними и взять управление, начав вводить текст. Процессы продолжают работать между вызовами инструментов, поэтому агент может запустить сервер разработки или REPL и позже прочитать вывод; он также может читать терминалы, которые вы открыли сами.\",\"zh\":\"为智能体提供以侧栏标签页打开的终端,你可以旁观,也可以直接在其中键入来接管。进程在多次工具调用之间持续运行,因此它可以启动开发服务器或 REPL,稍后再读取输出;它也能读取你自己打开的终端。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-liveshare\",\"title\":{\"en\":\"LiveShare Session Sharing\",\"de\":\"LiveShare-Sitzungsfreigabe\",\"es\":\"Compartir sesión de LiveShare\",\"fr\":\"Partage de session LiveShare\",\"ja\":\"LiveShare セッション共有\",\"pt\":\"Compartilhamento de sessão do LiveShare\",\"ru\":\"Совместный доступ к сеансу LiveShare\",\"zh\":\"LiveShare 会话分享\"},\"description\":{\"en\":\"Share the current Session with a colleague, who can drive it in a browser, edit files inside the granted workspace when the share allows writes, or branch their own Session from the completed history.\",\"de\":\"Teilt die aktuelle Sitzung mit einer Kollegin oder einem Kollegen, die oder der sie im Browser bedienen, bei erlaubten Schreibzugriffen Dateien im freigegebenen Arbeitsbereich bearbeiten oder aus der abgeschlossenen Historie eine eigene Sitzung abzweigen kann.\",\"es\":\"Comparte la sesión actual con un compañero, que puede dirigirla en un navegador, editar archivos dentro del espacio de trabajo concedido cuando el recurso compartido permite escritura, o crear su propia sesión a partir del historial completado.\",\"fr\":\"Partagez la session en cours avec un collègue, qui peut la piloter dans un navigateur, modifier des fichiers dans l'espace de travail accordé lorsque le partage autorise l'écriture, ou créer sa propre session à partir de l'historique terminé.\",\"ja\":\"現在のセッションを同僚と共有し、ブラウザから操作してもらう、共有が書き込みを許可する場合は付与されたワークスペース内のファイルを編集してもらう、または完了した履歴から自分のセッションを分岐してもらえます。\",\"pt\":\"Compartilhe a sessão atual com um colega, que pode conduzi-la no navegador, editar arquivos dentro do espaço de trabalho concedido quando o compartilhamento permite escrita, ou ramificar a própria sessão a partir do histórico concluído.\",\"ru\":\"Поделитесь текущим сеансом с коллегой: он сможет управлять им в браузере, редактировать файлы в предоставленном рабочем пространстве, если общий доступ разрешает запись, или ответвить собственный сеанс из завершённой истории.\",\"zh\":\"把当前会话分享给同事,对方可在浏览器中驱动该会话、在分享允许写入时修改授权工作区内的文件,或从已完成历史分支出自己的会话。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-session-search\",\"title\":{\"en\":\"Session search\",\"de\":\"Sitzungssuche\",\"es\":\"búsqueda de sesión\",\"fr\":\"Recherche de sessions\",\"ja\":\"セッション検索\",\"pt\":\"Pesquisa de sessão\",\"ru\":\"Поиск сеанса\",\"zh\":\"会话搜索\"},\"description\":{\"en\":\"Ask about earlier work, such as “How did we fix the pool leak last week?”, and the agent searches your earlier sessions in the same workspace to answer.\",\"de\":\"Fragen Sie nach früherer Arbeit, etwa „Wie haben wir letzte Woche das Pool-Leck behoben?“, und der Agent durchsucht Ihre früheren Sitzungen aus demselben Arbeitsverzeichnis, um zu antworten.\",\"es\":\"Pregunte por trabajo anterior, como “¿Cómo arreglamos la fuga del pool la semana pasada?”, y el agente busca en sus sesiones anteriores del mismo directorio de trabajo para responder.\",\"fr\":\"Posez une question sur un travail antérieur, par exemple « Comment avons-nous corrigé la fuite du pool la semaine dernière ? », et l'agent recherche dans vos sessions antérieures du même répertoire de travail pour répondre.\",\"ja\":\"「先週プールのリークをどう直した?」のように以前の作業について尋ねると、エージェントは同じ作業ディレクトリの過去のセッションを検索して回答します。\",\"pt\":\"Pergunte sobre trabalhos anteriores, como “Como corrigimos o vazamento do pool na semana passada?”, e o agente pesquisa suas sessões anteriores do mesmo diretório de trabalho para responder.\",\"ru\":\"Спросите о прошлой работе, например «Как мы исправили утечку в пуле на прошлой неделе?», и агент выполнит поиск по вашим прошлым сеансам из того же рабочего каталога, чтобы ответить.\",\"zh\":\"询问以往的工作,例如“上周我们是怎么修好连接池泄漏的?”,智能体会搜索同一工作区的历史会话来回答。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-tool-worktree\",\"title\":{\"en\":\"Git worktrees\",\"de\":\"Git-Arbeitsbäume\",\"es\":\"árboles de trabajo de git\",\"fr\":\"Arbres de travail Git\",\"ja\":\"Git ワークツリー\",\"pt\":\"Árvores de trabalho Git\",\"ru\":\"Рабочие деревья Git\",\"zh\":\"Git 工作树\"},\"description\":{\"en\":\"Ask for work on a new branch, and the agent creates a separate Git worktree and continues there, leaving your current checkout as it is.\",\"de\":\"Bitten Sie um Arbeit auf einem neuen Branch, und der Agent erstellt einen separaten Git-Worktree und arbeitet dort weiter, während Ihr aktueller Checkout unverändert bleibt.\",\"es\":\"Pida trabajar en una rama nueva, y el agente crea un worktree de Git independiente y continúa allí, dejando su checkout actual tal como está.\",\"fr\":\"Demandez à travailler sur une nouvelle branche, et l'agent crée un worktree Git distinct et y poursuit le travail, en laissant votre copie de travail actuelle telle quelle.\",\"ja\":\"新しいブランチでの作業を依頼すると、エージェントは別の Git ワークツリーを作成してそこで作業を続け、現在のチェックアウトはそのまま残します。\",\"pt\":\"Peça para trabalhar em um novo branch, e o agente cria um worktree do Git separado e continua lá, deixando seu checkout atual como está.\",\"ru\":\"Попросите поработать в новой ветке, и агент создаст отдельное рабочее дерево Git и продолжит работу там, оставив вашу текущую рабочую копию как есть.\",\"zh\":\"要求在新分支上工作时,智能体会创建单独的 Git 工作树并在其中继续,你当前的工作树保持原样。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-cua-bundle\",\"title\":{\"en\":\"Computer use\",\"de\":\"Computernutzung\",\"es\":\"Uso de la computadora\",\"fr\":\"Utilisation de l'ordinateur\",\"ja\":\"Computer Use\",\"pt\":\"Uso do computador\",\"ru\":\"Использование компьютера\",\"zh\":\"Computer Use\"},\"description\":{\"en\":\"Currently supports macOS; Windows support is in development. Loads computer use for existing and new PTC sessions. Switch to PTC mode and grant Accessibility and Screen Recording permissions to use it.\",\"de\":\"Unterstützt derzeit macOS; Die Windows-Unterstützung befindet sich in der Entwicklung. Lädt die Computernutzung für bestehende und neue PTC-Sitzungen. Wechseln Sie in den PTC-Modus und erteilen Sie die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung, um ihn zu verwenden.\",\"es\":\"Actualmente es compatible con macOS; El soporte para Windows está en desarrollo. Carga el uso de la computadora para sesiones PTC nuevas y existentes. Cambie al modo PTC y otorgue permisos de Accesibilidad y Grabación de pantalla para usarlo.\",\"fr\":\"Prend actuellement en charge macOS ; La prise en charge de Windows est en cours de développement. Charge l'utilisation de l'ordinateur pour les sessions PTC existantes et nouvelles. Passez en mode PTC et accordez les autorisations d’accessibilité et d’enregistrement d’écran pour l’utiliser.\",\"ja\":\"現在は macOS のみ対応し、Windows 対応は開発中です。既存および新規の PTC セッションに Computer Use を読み込みます。PTC モードに切り替え、アクセシビリティと画面収録の権限を許可して使用してください。\",\"pt\":\"Atualmente suporta macOS; O suporte Windows está em desenvolvimento. Carrega o uso do computador para sessões PTC novas e existentes. Mude para o modo PTC e conceda permissões de acessibilidade e gravação de tela para usá-lo.\",\"ru\":\"В настоящее время поддерживается macOS; Поддержка Windows находится в разработке. Загружает использование компьютера для существующих и новых сеансов PTC. Переключитесь в режим PTC и предоставьте разрешения на доступность и запись экрана для его использования.\",\"zh\":\"目前仅支持 macOS,Windows 支持正在开发中。为已有及新建 PTC 会话加载 Computer Use。请切换到 PTC 模式来使用,并授予辅助功能和屏幕录制权限。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-plugin-market-bundle\",\"title\":{\"en\":\"Custom plugin indexes\",\"de\":\"Benutzerdefinierte Plugin-Indizes\",\"es\":\"Índices de complementos personalizados\",\"fr\":\"Index de plugins personnalisés\",\"ja\":\"カスタムプラグインインデックス\",\"pt\":\"Índices de plug-ins personalizados\",\"ru\":\"Пользовательские индексы плагинов\",\"zh\":\"自定义插件索引\"},\"description\":{\"en\":\"Adds a Discover tab to Plugins, where you browse and install plugins from plugin indexes you add.\",\"de\":\"Fügt unter „Plugins“ den Tab „Entdecken“ hinzu, in dem Sie Plugins aus von Ihnen hinzugefügten Plugin-Indizes durchsuchen und installieren.\",\"es\":\"Añade la pestaña “Descubrir” a “Complementos”, donde puede explorar e instalar complementos de los índices de complementos que agregue.\",\"fr\":\"Ajoute à « Plugins » un onglet « Découvrez » où vous parcourez et installez des plugins provenant des index de plugins que vous ajoutez.\",\"ja\":\"「プラグイン」に「見つける」タブを追加し、追加したプラグインインデックスからプラグインを閲覧・インストールできるようにします。\",\"pt\":\"Adiciona a guia “Descubra” a “Plug-ins”, onde você navega e instala plug-ins dos índices de plug-ins que adiciona.\",\"ru\":\"Добавляет в «Плагины» вкладку «Откройте для себя», где можно просматривать и устанавливать плагины из добавленных вами индексов плагинов.\",\"zh\":\"在插件页添加“发现”标签页,从你添加的插件索引中浏览和安装插件。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-experimental-forge-bundle\",\"title\":{\"en\":\"Change requests & worktrees\",\"de\":\"Änderungsanfragen und Arbeitsbäume\",\"es\":\"Solicitudes de cambio y árboles de trabajo\",\"fr\":\"Demandes de modification et arbres de travail\",\"ja\":\"変更リクエストとワークツリー\",\"pt\":\"Solicitações de alteração e árvores de trabalho\",\"ru\":\"Запросы на изменение и рабочие деревья\",\"zh\":\"变更请求与工作树\"},\"description\":{\"en\":\"Keep linked GitHub pull requests beside your conversation: follow checks and reviews, inspect diffs, and send feedback to the agent. Review local changes and use a separate worktree to isolate each task. GitHub features require the gh CLI installed and signed in on the host.\",\"de\":\"Verknüpfte GitHub-Pull-Requests neben der Unterhaltung verfolgen: Prüfungen und Reviews ansehen, Code vergleichen und Feedback an den Agenten senden. Lokale Änderungen prüfen und Aufgaben mit separaten Arbeitsbäumen isolieren. GitHub-Funktionen erfordern eine installierte gh-CLI und eine Anmeldung auf dem Host.\",\"es\":\"Sigue los pull requests de GitHub vinculados a la conversación: consulta comprobaciones y revisiones, compara código y envía comentarios al agente. Revisa cambios locales y aísla cada tarea en un árbol de trabajo separado. Las funciones de GitHub requieren instalar la CLI gh e iniciar sesión en el equipo anfitrión.\",\"fr\":\"Suivez les pull requests GitHub liées à votre conversation : consultez les vérifications et les revues, comparez le code et transmettez vos remarques à l’agent. Examinez les modifications locales et isolez chaque tâche dans un arbre de travail séparé. Les fonctions GitHub nécessitent la CLI gh installée et une connexion sur l’hôte.\",\"ja\":\"会話のサイドバーで関連付けられた GitHub PR をまとめて確認できます。チェックやレビューの状況、コードの差分を確認し、修正案をエージェントに渡せます。ローカルの変更確認や、独立したワークツリーによるタスクの分離にも対応します。GitHub 機能にはホストでの gh CLI のインストールとログインが必要です。\",\"pt\":\"Acompanhe os pull requests do GitHub vinculados à conversa: consulte verificações e revisões, compare código e envie comentários ao agente. Revise alterações locais e isole cada tarefa em uma árvore de trabalho separada. Os recursos do GitHub exigem a CLI gh instalada e uma sessão iniciada no host.\",\"ru\":\"Следите за связанными с беседой pull request GitHub: проверками, рецензиями и различиями в коде, а затем передавайте замечания агенту. Просматривайте локальные изменения и изолируйте задачи в отдельных рабочих деревьях. Для функций GitHub требуется установить CLI gh и войти в аккаунт на хосте.\",\"zh\":\"在会话侧栏集中跟踪关联的 GitHub PR:查看检查状态、评审意见与代码差异,并把修改建议交给智能体继续处理。也可查看本地改动,用独立工作树隔离任务。GitHub 功能需要本机安装 gh 并登录。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-claude-code\",\"title\":{\"de\":\"Claude Code-Subagent\",\"en\":\"Claude Code subagent\",\"es\":\"Subagente Claude Code\",\"fr\":\"Sous-agent Claude Code\",\"ja\":\"Claude Code サブエージェント\",\"pt\":\"Claude Code subagente\",\"ru\":\"Субагент Claude Code\",\"zh\":\"Claude Code 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Claude Code, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Claude Code using its native authentication and settings.\",\"es\":\"Delegue una tarea a Claude Code utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Claude Code à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Claude Code のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Claude Code usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Claude Code, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Claude Code 原生认证和设置委派单个任务。\"},\"enabled\":false},{\"name\":\"@deepseek-ai/dsh-subagent-codex\",\"title\":{\"de\":\"Codex-Subagent\",\"en\":\"Codex subagent\",\"es\":\"Subagente Codex\",\"fr\":\"Sous-agent Codex\",\"ja\":\"Codex サブエージェント\",\"pt\":\"Codex subagente\",\"ru\":\"Субагент Codex\",\"zh\":\"Codex 子智能体\"},\"description\":{\"de\":\"Delegieren Sie eine Aufgabe an Codex, indem Sie dessen native Authentifizierung und Einstellungen verwenden.\",\"en\":\"Delegate one task to Codex using its native authentication and settings.\",\"es\":\"Delegue una tarea a Codex utilizando su autenticación y configuración nativas.\",\"fr\":\"Déléguez une tâche à Codex à l’aide de son authentification et de ses paramètres natifs.\",\"ja\":\"Codex のネイティブの認証と設定を使用して、単独のタスクを委派します。\",\"pt\":\"Delegue uma tarefa a Codex usando sua autenticação e configurações nativas.\",\"ru\":\"Делегируйте одну задачу Codex, используя его встроенную аутентификацию и настройки.\",\"zh\":\"使用 Codex 原生认证和设置委派单个任务。\"},\"enabled\":false}]\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"propose_action"}],"role":"developer","id":"{{message:8}}"},"headerSeq":20},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_creation_card","name":"propose_action","arguments":"{\"action\":\"create_personalized_page\",\"title\":\"Counter\",\"brief\":\"Need: Keep a small counter visible across conversations.\\nLocation: A card titled Today’s achievements in the right sidebar.\\nControls: Increment and reset buttons beside the current value.\\nStorage: Save changes in browser storage across navigation and refresh.\\nAppearance: Follow the existing sidebar theme in light and dark mode.\\nCompletion: Both controls work and reopening restores the saved value.\",\"details\":{\"slot\":\"sidebar-right\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1792674450652,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792674450652,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_creation_card","name":"propose_action","arguments":"{\"action\":\"create_personalized_page\",\"title\":\"Counter\",\"brief\":\"Need: Keep a small counter visible across conversations.\\nLocation: A card titled Today’s achievements in the right sidebar.\\nControls: Increment and reset buttons beside the current value.\\nStorage: Save changes in browser storage across navigation and refresh.\\nAppearance: Follow the existing sidebar theme in light and dark mode.\\nCompletion: Both controls work and reopening restores the saved value.\",\"details\":{\"slot\":\"sidebar-right\"}}"}}},{"type":"chunk","time":1792674450652,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_creation_card","name":"propose_action","arguments":"{\"action\":\"create_personalized_page\",\"title\":\"Counter\",\"brief\":\"Need: Keep a small counter visible across conversations.\\nLocation: A card titled Today’s achievements in the right sidebar.\\nControls: Increment and reset buttons beside the current value.\\nStorage: Save changes in browser storage across navigation and refresh.\\nAppearance: Follow the existing sidebar theme in light and dark mode.\\nCompletion: Both controls work and reopening restores the saved value.\",\"details\":{\"slot\":\"sidebar-right\"}}"}} diff --git a/snapshots/web/creation-recommendations/tool-schemas.expected.json b/snapshots/web/creation-recommendations/tool-schemas.expected.json index c2a0dcee64..3c82da7581 100644 --- a/snapshots/web/creation-recommendations/tool-schemas.expected.json +++ b/snapshots/web/creation-recommendations/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -1220,22 +1204,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/web/creator-persona/tool-schemas.expected.json b/snapshots/web/creator-persona/tool-schemas.expected.json index e08b7ab898..09c4043629 100644 --- a/snapshots/web/creator-persona/tool-schemas.expected.json +++ b/snapshots/web/creator-persona/tool-schemas.expected.json @@ -263,22 +263,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/web/fresh-round-trip/tool-schemas.expected.json b/snapshots/web/fresh-round-trip/tool-schemas.expected.json index 1f92009d96..eee574186f 100644 --- a/snapshots/web/fresh-round-trip/tool-schemas.expected.json +++ b/snapshots/web/fresh-round-trip/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/web/official-subagent-bundle/system-prompt.expected.md b/snapshots/web/official-subagent-bundle/system-prompt.expected.md index 853d504a03..c50bd1640e 100644 --- a/snapshots/web/official-subagent-bundle/system-prompt.expected.md +++ b/snapshots/web/official-subagent-bundle/system-prompt.expected.md @@ -129,11 +129,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -433,9 +428,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/web/optional-string-editor/system-prompt.expected.md b/snapshots/web/optional-string-editor/system-prompt.expected.md index 1ae9c46211..fe757ece2c 100644 --- a/snapshots/web/optional-string-editor/system-prompt.expected.md +++ b/snapshots/web/optional-string-editor/system-prompt.expected.md @@ -129,11 +129,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -439,9 +434,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { diff --git a/snapshots/web/plugin-recommendations/session.v4.jsonl b/snapshots/web/plugin-recommendations/session.v4.jsonl index 2eebfabd89..0fb5b5e921 100644 --- a/snapshots/web/plugin-recommendations/session.v4.jsonl +++ b/snapshots/web/plugin-recommendations/session.v4.jsonl @@ -11,7 +11,7 @@ {"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nCurrent DeepSeek Harness implementation checkout: \"{{sourceRoot}}\".\n\nCurrent DeepSeek Harness Web GUI URL: \"{{webUrl}}\".\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"harness:source","text":"Current DeepSeek Harness implementation checkout: \"{{sourceRoot}}\"."},{"name":"app:web-surface","text":"Current DeepSeek Harness Web GUI URL: \"{{webUrl}}\"."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n\n- `dsh-doc`: Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile.\n- `office`: Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n- `official-plugins`: Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers.\n- `personalized-pages`: Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers.\n\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n"}],"source":{"kind":"skill-catalog","form":"catalog","entries":[{"name":"dsh-doc","description":"Use when a task needs facts about DeepSeek Harness (DSH) itself, such as how a feature, setting, plugin, agent preset, tool, or Cordis API of the running installation works; when the user asks to design, review, build, install, enable, or debug a DSH plugin, bundle, MCP connection, agent preset, plugin icon or detail page, or a DSH tool definition or skill; and when upgrading a plugin or profile to a newer DSH release. Loading it grants no permission to change files or the profile."},{"name":"office","description":"Create or edit Office files; inspect Office files and PDFs. Load before rendering, conversion, or recalculation to enable office_render, office_convert, and office_recalculate next step."},{"name":"office-docx","description":"Create, read, edit, and validate Word documents (.docx)."},{"name":"office-pptx","description":"Create, read, edit, and validate PowerPoint presentations (.pptx)."},{"name":"office-xlsx","description":"Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx)."},{"name":"official-plugins","description":"Check DSH’s optional plugins when the user asks how to do or use something in this app, whether it can, or says a capability is missing or should change: tools, input, thinking or title display, session search, terminals, worktrees, agent teams, desktop control, automation, access, approvals, badges or signatures, plugins or plugin sources. Not a request to develop DSH, even in its own repository: load before reading files or source. Not for ordinary tasks, quoted wishes or declined offers."},{"name":"personalized-pages","description":"Plan an optional page or small tool when the user asks for a page, tab, panel, tool or interface in this app (even for one-off use), wants something to keep, revisit or update later, will keep changing data in your answer, or wants a live view of this app’s own data (Sessions, tasks, logs, workspace). Load this before reading any files or source; it says how to submit the proposal. Not for requested files or code, ordinary answers, existing-feature questions, quoted wishes or declined offers."}]},"role":"user","id":"{{message:4}}"},"surfaceOp":"append"} {"type":"user/message","data":{"content":[{"type":"text","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}],"source":{"kind":"time-context","form":"snapshot","sections":[{"name":"time-context","text":"Time sampled while preparing turn 1, step 1: {{timeContextTimestamp}}\nBrowser time zone for this request: {{clientTimeZone}}. Interpret otherwise-unqualified dates and times in this zone.\nElapsed since the preceding model-visible message: {{elapsed}}"}]},"role":"user","id":"{{message:5}}"},"surfaceOp":"append"} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"initial"}} {"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":128000}} {"type":"session/title","data":{"title":"I want to dictate long","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_plugin_skill","name":"skill","arguments":"{\"name\":\"official-plugins\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792678188343,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792678188343,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_plugin_skill","name":"skill","arguments":"{\"name\":\"official-plugins\"}"}}},{"type":"chunk","time":1792678188344,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} @@ -19,7 +19,7 @@ {"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_plugin_skill"},"toolCallId":"call_plugin_skill","content":[{"type":"text","text":"\n\nResources for this skill are managed by provider \"dsh-official-plugins\".\nLoad referenced resources only as needed.\n\n\n\n# Official plugins\n\nUse this workflow in the main conversation when the user wants DSH itself to work differently or gain an ability. The catalog at the end lists DSH's built-in optional plugins and whether each is enabled. A `propose_action` call shows an Enable card below your answer; nothing changes until the user clicks Enable. Match from the catalog descriptions alone: do not read files, configuration or source, call plugin management tools, or change settings yourself.\n\n## When to offer\n\nOffer one disabled plugin when the user's own words ask for an outcome its description provides. Match the outcome, not keywords. When a plugin covers only part of the wish, say the limit in one sentence: thinking translation translates the displayed thinking and does not change the language the model reasons in.\n\nOffer no card in these cases:\n\n- The plugin is already enabled: say that it is on and how to use it.\n- The wish appears inside quoted text, pasted content, a translation request, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks you not to recommend anything, or has declined: stay silent on plugins for the rest of this conversation.\n- No entry fits, or the need is too vague to match: answer normally or ask one question; do not stretch a description.\n- Something DSH already shows covers it, such as the sidebar search for finding a session by keyword yourself. Letting the agent search and read past sessions is a different need.\n\n## One card per turn\n\nA turn shows at most one card across every card skill. When the user asks for several things, follow an explicit priority; otherwise prefer an existing plugin over building a new page. Mention the other needs in one sentence, without promising a later card.\n\n## Offer without enabling\n\nTo offer, call `propose_action` once, in the same turn as loading this skill, with `action: \"enable_official_plugin\"`, `title` set to the plugin's catalog title in the user's language, `brief` set to one sentence in the user's language that ties the plugin to their need, and `details` holding `name`, the exact catalog name. The call is the submission: the card appears below your answer; a refused call creates no card, and its error says why. Then write your final answer: answer any direct question; the call's result says how to end the answer. The card shows only the plugin's catalog title and description, so the answer says in one sentence, in the user's language, how the plugin meets their need; `brief` is that same sentence. Do not narrate the call, repeat the catalog description, add setup steps the catalog does not state, claim the plugin is enabled, or ask the user to report back. The card opens the plugin's details; enabling applies to every conversation and can be undone there. The user's choice reaches you later as a status notice; enabling a plugin authorizes nothing beyond it.\n\n## Official plugins\n\n[{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\",\"title\":{\"en\":\"Voice input\",\"de\":\"Spracheingabe\",\"es\":\"Entrada de voz\",\"fr\":\"Saisie vocale\",\"ja\":\"音声入力\",\"pt\":\"Entrada de voz\",\"ru\":\"Голосовой ввод\",\"zh\":\"语音输入\"},\"description\":{\"en\":\"Transcribe recordings locally with SenseVoice; first use requires installing dependencies.\",\"de\":\"Transkribieren Sie Aufnahmen lokal mit SenseVoice; Für die erste Verwendung müssen Abhängigkeiten installiert werden.\",\"es\":\"Transcribe grabaciones localmente con SenseVoice; El primer uso requiere instalar dependencias.\",\"fr\":\"Transcrivez les enregistrements localement avec SenseVoice ; la première utilisation nécessite l'installation de dépendances.\",\"ja\":\"ローカルの SenseVoice で録音を文字に起こします。初回利用時には依存関係のインストールが必要です。\",\"pt\":\"Transcreva gravações localmente com SenseVoice; o primeiro uso requer a instalação de dependências.\",\"ru\":\"Транскрибируйте записи локально с помощью SenseVoice; при первом использовании требуется установка зависимостей.\",\"zh\":\"在本机使用 SenseVoice 转写录音,首次使用需安装依赖。\"},\"enabled\":false}]\n\n"}],"isError":false,"id":"{{message:7}}"}},"sourceEventSeqs":[16],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} -{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","interrupt_agent","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}} {"type":"developer/message","data":{"turn":1,"step":2,"message":{"source":{"kind":"tool-registry"},"content":[{"type":"tool-addition","toolName":"propose_action"}],"role":"developer","id":"{{message:8}}"},"headerSeq":20},"surfaceOp":"append"} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_plugin_card","name":"propose_action","arguments":"{\"action\":\"enable_official_plugin\",\"title\":\"Voice input\",\"brief\":\"Speak long requests instead of typing them; transcription runs on this computer.\",\"details\":{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:9}}"},"stream":[{"type":"chunk","time":1792678188573,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792678188573,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_plugin_card","name":"propose_action","arguments":"{\"action\":\"enable_official_plugin\",\"title\":\"Voice input\",\"brief\":\"Speak long requests instead of typing them; transcription runs on this computer.\",\"details\":{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\"}}"}}},{"type":"chunk","time":1792678188573,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":2,"callId":"call_plugin_card","name":"propose_action","arguments":"{\"action\":\"enable_official_plugin\",\"title\":\"Voice input\",\"brief\":\"Speak long requests instead of typing them; transcription runs on this computer.\",\"details\":{\"name\":\"@deepseek-ai/dsh-experimental-voice-input-bundle\"}}"}} diff --git a/snapshots/web/plugin-recommendations/tool-schemas.expected.json b/snapshots/web/plugin-recommendations/tool-schemas.expected.json index c2a0dcee64..3c82da7581 100644 --- a/snapshots/web/plugin-recommendations/tool-schemas.expected.json +++ b/snapshots/web/plugin-recommendations/tool-schemas.expected.json @@ -250,22 +250,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", @@ -1220,22 +1204,6 @@ ] } }, - { - "name": "interrupt_agent", - "description": "Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running.", - "parameters": { - "type": "object", - "properties": { - "agent": { - "type": "string", - "description": "The name of an agent created under you: your direct child or a deeper descendant." - } - }, - "required": [ - "agent" - ] - } - }, { "name": "job_kill", "description": "Request cancellation of a running background job.", diff --git a/snapshots/web/ptc-round/system-prompt.expected.md b/snapshots/web/ptc-round/system-prompt.expected.md index 2453375147..9e8a34b7e5 100644 --- a/snapshots/web/ptc-round/system-prompt.expected.md +++ b/snapshots/web/ptc-round/system-prompt.expected.md @@ -129,11 +129,6 @@ interface ToolArgsMap { /** One glob filter for which files to search (e.g. "*.ts", "*.{js,jsx}"). Not a list; negation is not supported. */ include?: string; } & Record; - /** Ask a subagent to stop its current work. This call returns without waiting for it to stop. You can continue a local subagent's conversation later with send_message. External executions stop permanently and cannot receive follow-ups. Subagents it started will keep running. */ - interrupt_agent: { - /** The name of an agent created under you: your direct child or a deeper descendant. */ - agent: string; - } & Record; /** Request cancellation of a running background job. */ job_kill: { /** Job id returned by the tool that started the background work. */ @@ -422,9 +417,6 @@ interface ToolOutputMap { line: string; }[]; }; - interrupt_agent: { - accepted: boolean; - }; job_kill: { outcome: "cancellation-requested" | "already-finished"; job: { From e426855e0359491b42915d07e0f98105e5cf387a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 15:01:16 +0800 Subject: [PATCH 096/103] test(cua-macos): distinguish process delivery from AppKit repeat handling --- packages/experimental/cua-macos/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/README.md | 4 ++-- packages/experimental/cua-macos/README.zh.md | 4 ++-- packages/experimental/cua-macos/native/README.i18n.yaml | 4 ++-- packages/experimental/cua-macos/native/README.md | 2 +- packages/experimental/cua-macos/native/README.zh.md | 2 +- .../cua-macos/native/Sources/CuaNative/HeldKeys.swift | 2 +- .../cua-macos/native/tests/capabilities_e2e.py | 9 ++++++--- packages/experimental/cua-macos/src/guidance.ts | 2 +- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- .../ptc-script-retained/system-prompt.expected.md | 2 +- 12 files changed, 21 insertions(+), 18 deletions(-) diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 1be5a7abd9..7220e21ad2 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 83d4eb62d0d0db2f - zh: 3afde1c3b8c25211 + en: 30fefafc1915db8a + zh: e819f1e722c0d614 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: b734a0907747580e zh: 8110c5951b70e100 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 26a218c40d..34975631af 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -81,7 +81,7 @@ The [configuration catalog](../../../docs/config-catalog.md#deepseek-aidsh-exper `pressKey(key, modifiers?)` presses and releases one key. For shortcuts, pass held modifiers separately, as in `pressKey('a', ['command'])`. Pressing a modifier itself, as in `pressKey('shift')`, sets its flag on press and clears it on release. A single `+` or `plus` sends Shift+=. The macOS helper accepts `command`/`cmd`, `shift`, `option`/`alt`, `control`/`ctrl`, and `fn`, and maps them to their physical keys. Key names are platform-defined; keypad names (`KP_0` through `KP_9`, `KP_Enter`, and keypad operators) retain their physical key codes. `typeText` sends literal text, including its line breaks and tabs. Use the App object's `pressKey` for a short press. -For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. The first down holds the key across subsequent tool calls. For an ordinary key already held by this execution, each additional down sends one key-down marked as a repeat to the original process. Choose the interval between calls. One up releases the key. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. +For a long press, call `app.sendKeyEvent('w', 'down')` inside `run_code`. The first down holds the key across subsequent tool calls. For an ordinary key already held by this execution, each additional down sends one key-down marked as a repeat to the original process. Choose the interval between calls. A control can filter synthetic repeats, so check its response. One up releases the key. Choose when to send each up: after W down, D down and D up, W stays down. When the program returns, exits with an error, or the user pauses it, the helper releases the remaining keys at the processes that received their downs. A later execution cannot release an earlier execution's keys. Agent disposal and plugin unload cancel and await the complete tool call, including image admission and attachment storage. An image write already in progress must settle before disposal returns; a canceled call cannot return a successful screenshot. @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index a40be5399b..e6a0ff313f 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -81,7 +81,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. `pressKey(key, modifiers?)` 按下并松开一个键。使用快捷键时单独传入修饰键,例如 `pressKey('a', ['command'])`。单独调用 `pressKey('shift')` 时,按下事件带有 Shift 标志,释放事件清除该标志。`+` 和 `plus` 都会发送 Shift 和等号。macOS helper 接受 `command`/`cmd`、`shift`、`option`/`alt`、`control`/`ctrl` 和 `fn`,并映射到对应物理键。按键名由平台定义;数字键盘名称(`KP_0` 到 `KP_9`、`KP_Enter` 和数字键盘运算键)保留独立的物理键码。`typeText` 发送字面文本,包括其中的换行和制表符。短按使用 App 对象上的 `pressKey`。 -长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久,松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 +长按时,在 `run_code` 中调用 `app.sendKeyEvent('w', 'down')`。首次按下后,该键在同一次执行的后续工具调用中保持按下。对自己已按住的普通键再发一次 `down`,原接收进程会收到一次带重复标志的按下事件。调用方决定是否重复和间隔多久。控件可能过滤模拟的重复事件,可通过控件的实际变化确认效果。松键只需一次 `up`。每个键可分别松开。例如先按 W,再按 D,松开 D 后 W 仍按着。程序正常返回、出错退出或用户暂停时,helper 为本次执行仍按着的键逐一发送松开事件,每个事件都发回原接收进程。后续执行不能释放前一次执行的键。 Agent 销毁和插件卸载会取消并等待完整工具调用,包括图像接入检查和附件存储。已经开始的图像写入必须结束后,销毁才会返回;已取消的调用不会返回成功截图。 @@ -224,7 +224,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. ``` diff --git a/packages/experimental/cua-macos/native/README.i18n.yaml b/packages/experimental/cua-macos/native/README.i18n.yaml index 57420b0348..d4cfe23155 100644 --- a/packages/experimental/cua-macos/native/README.i18n.yaml +++ b/packages/experimental/cua-macos/native/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2a69d89b7fc95998 zh: 084575bb31fb40dd /dsh-cua-native-helper/observation-and-input: - en: c6787eda94ba4833 - zh: 855e3c6432918775 + en: 0808c25f70ce6eff + zh: 820864a2b18b8a24 /dsh-cua-native-helper/verification: en: c87945aeec587bf5 zh: e5d69e4927e2fed3 diff --git a/packages/experimental/cua-macos/native/README.md b/packages/experimental/cua-macos/native/README.md index 51d0a7b131..4f2283e654 100644 --- a/packages/experimental/cua-macos/native/README.md +++ b/packages/experimental/cua-macos/native/README.md @@ -105,7 +105,7 @@ Capture and pointer delivery read CG bounds before and after an exact-window AX `typeText` and `pressKey` target the selected process's current focused control, not an exact window. `pressKey` presses the listed modifiers followed by one key, then releases all pressed keys in reverse order, including on cancellation. Keyboard events go directly to the target PID and bypass the global HID queue. Key names are platform-defined; keypad names such as `KP_0` and `KP_Enter` preserve their physical key codes. Background pointer actions may change that keyboard focus. Text injection sends Unicode characters individually and does not use the clipboard. LF, CR and CRLF send one Return; tabs send Tab. Applications apply their normal editing behavior, including indentation and focus navigation. Each `typeText` down/up event is followed by the configured text interval; `pressKey` keeps its own press and release timing, and dispatch completion does not confirm that the receiving application consumed every event. Cancellation can interrupt text or a gesture after partial input; it cannot undo received events. Very long text can exceed the host's operation deadline. Validate observed application state before deciding how to continue. -The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. A repeated down from the owner posts one key-down with `keyboardEventAutorepeat` set and reuses the existing record. Repeats, explicit up and cleanup verify the original process identity. A conflicting down or up reports the key and whether another session or another run holds it. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. +The Host associates directional key events with one `run_code` execution. On down, the helper retains the selected application, recipient PID and process start time, physical key code, and matching up event. A repeated down from the owner posts one key-down with `keyboardEventAutorepeat` set and reuses the existing record. The event is posted to the recipient PID. An AppKit view can receive the initial down and final up while filtering the marked repeat. Repeats, explicit up and cleanup verify the original process identity. A conflicting down or up reports the key and whether another session or another run holds it. On return, error, or user pause, the Host waits for any in-flight native request and asks the helper to release only that execution’s remaining keys. Disconnect cleanup also releases keys owned by the closed connection. The selected helper application needs macOS Accessibility permission for AX state and input, and Screen Recording permission for screenshots. Capability preflight and permission errors do not grant permissions. Capture refuses a window that moves or resizes while the image is being read. Unassociated system panels and accessory-only applications are not selectable. diff --git a/packages/experimental/cua-macos/native/README.zh.md b/packages/experimental/cua-macos/native/README.zh.md index eef79a770f..e010295168 100644 --- a/packages/experimental/cua-macos/native/README.zh.md +++ b/packages/experimental/cua-macos/native/README.zh.md @@ -105,7 +105,7 @@ AppKit 在主事件循环上运行。阻塞式 socket 接收与握手使用后 `typeText` 和 `pressKey` 面向所选进程当前获得焦点的控件,不指定窗口。`pressKey` 向目标 PID 依次发送修饰键和一个主键的按下事件,再逆序释放。操作中途取消也会逆序释放已按下的键。键盘事件直接发给目标进程,绕过全局 HID 队列。按键名由平台定义;KP_0 和 KP_Enter 等数字键盘名称保留物理键码。后台鼠标操作可能改变键盘焦点。文本逐个 Unicode 字符输入,不使用剪贴板。LF、CR 和 CRLF 发送一次 Return,制表符发送 Tab。应用保留缩进和焦点导航等正常编辑行为。`typeText` 的每次按下和抬起后等待配置的文本事件间隔;`pressKey` 使用自己的按下与释放节奏,分派完成不证明应用已消费全部事件。取消可能中断部分文本或手势,无法撤销已接收事件。很长的文本可能超过 Host 操作期限。继续输入前应核实应用状态。 -宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,发送一次带 `keyboardEventAutorepeat` 标志的按下事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 +宿主为每次 `run_code` 的 `sendKeyEvent` 附上执行标识。按下时,helper 保存已选应用、接收进程的 PID 与启动时间、物理键码及对应的松开事件。持有方再次按下普通键时,helper 复用原记录,向接收进程发送一次带 `keyboardEventAutorepeat` 标志的按下事件。AppKit 视图可能只收到首次按下和最终松开,过滤中间的重复事件。重复、显式松键和执行结束时都会核对原进程身份。其他执行尝试按下或松开同一个键时,错误会指出键名,并区分其他会话和同一连接内的其他执行。正常返回、异常退出或用户暂停时,宿主等待在途原生请求结束,再通知 helper 释放该执行持有的其余按键。连接断开时,helper 也会清理该连接持有的按键。 所选 helper 应用需要 macOS 辅助功能权限以读取 AX 和输入,需要屏幕录制权限以截图。能力预检和权限错误不授予权限。截图会拒绝在读取图片期间移动或缩放的窗口。无法确认归属的系统面板及仅后台辅助类型的应用不可选择。 diff --git a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift index 06f47981d2..3d29795127 100644 --- a/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift +++ b/packages/experimental/cua-macos/native/Sources/CuaNative/HeldKeys.swift @@ -38,7 +38,7 @@ final class HeldKeys: @unchecked Sendable { func repeatIfHeld(owner: Owner, name: String, code: CGKeyCode, down: CGEvent, post: (CGEvent, Int32) -> Void) throws -> Bool { try lock.withLock { guard let key = pressed.first(where: { $0.owner == owner && $0.code == code }) else { return false } - guard down.type == .keyDown else { + guard key.flag.isEmpty, down.type == .keyDown else { throw RequestParameters.invalid("Modifier '\(name)' is already held. Send 'up' to release it.") } try NativePlatform.verify(key.recipient) diff --git a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py index 66dd004700..fb7a022a83 100644 --- a/packages/experimental/cua-macos/native/tests/capabilities_e2e.py +++ b/packages/experimental/cua-macos/native/tests/capabilities_e2e.py @@ -157,9 +157,12 @@ def check_keyboard(call, owner, state_file, state): if explicit_up: key("w", "up") call("releaseHeldKeys", {"runId": "held-input"}) - state = wait_for_state(state_file, lambda value: len(value["events"]) >= count + 3) - repeat = [(e["type"], e["keyCode"], e["repeat"]) for e in state["events"][count:]] - assert repeat == [(10, 13, False), (10, 13, True), (11, 13, False)], repeat + state = wait_for_state(state_file, lambda value: any( + e["type"] == 11 and e.get("keyCode") == 13 for e in value["events"][count:])) + view_events = [(e["type"], e["keyCode"], e["repeat"]) for e in state["events"][count:]] + # AppKit can filter a synthetic repeat before NSView.keyDown receives it. + down, repeat, up = (10, 13, False), (10, 13, True), (11, 13, False) + assert view_events in ([down, up], [down, repeat, up]), view_events def main(): diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index 839eb56a3c..47d2eb8f5c 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -14,7 +14,7 @@ export const GUIDANCE = `${PLATFORM_GUIDANCE} ${COMMON_GUIDANCE.replace(/^- ([\w.]+)\(.*$/gm, (entry, method: string) => { if (method === 'pressKey') return `${entry} -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients.` const detail = methodDetails.get(method) return detail ? `${entry} ${detail}` : entry })}` diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index a01916dbe2..8a8938c6ab 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -79,7 +79,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index ef5ce31b6d..4276485cd5 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index 9c072b94ea..b83ccdc8f3 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -81,7 +81,7 @@ Available at app or window level depending on the platform. - typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call sends one event. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. +- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send 'down' to hold a key across tool calls in one run_code, for example W down, D down, D up, W up. Holding a key on a physical keyboard can produce repeated key-down events after a delay. To send one such repeat for a non-modifier key this run already holds, send 'down' again. Each call posts one event. A control can filter repeats. Use the app's response to decide whether and when to repeat or release the key. When this run_code returns, throws, or the user pauses it, macOS releases only its remaining keys at their original recipients. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. From 29ceb385e69fbd1720f1280a773b7e13574a39b2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 15:02:33 +0800 Subject: [PATCH 097/103] docs(cua-macos): document caller-requested key repeats in the upgrade guide --- .../v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml | 4 ++-- docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md | 2 +- .../upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml index 09553adc47..a017e7f82b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.i18n.yaml @@ -12,5 +12,5 @@ en: e5d1027faa55adba zh: 4b88ad6a70977fb3 /native-cua-application-and-window-api/migration: - en: a0640d4cd1f2e84e - zh: be8d5b5f9d14caf8 + en: a63e88dce467d6ee + zh: fc25bb283ca0eaff diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md index 8f5b092012..2675699a71 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.md @@ -18,6 +18,6 @@ Providers supply startup capabilities alongside their platform guidance. The nat 1. After `cua.getApp(selector)`, select the target from `app.getWindows()` with `app.getWindow(windowId)`. Use `window.getScreenshot()`, `window.click()`, `window.scroll()`, and `window.drag()`. Replace `hover` with `window.mouseMove()`. On macOS, `window.click(id)` sends mouse events at the element center. Switch to `invoke(id)` for the default accessibility action, or `performAction(id, "AXShowMenu")` to request an advertised menu action. 2. Replace `getAXState()` with `getAccessibilityTree()`. Replace `getAXStateAndScreenshot()` with separate tree and screenshot reads. Selection reads the initial tree silently for a window, and for an app when `appLevelAccessibility` is true. Read the tree explicitly to display it. 3. Pass the opaque string ID from the latest tree wherever you passed a numeric element index. In raw requests use `elementId` with `snapshotId`. Replace `performSecondaryAction` with `listActions(id)` and `performAction(id, exactName, argument?)`, or use `invoke(id)` for the default action. `setValue` accepts the provider’s supported JSON values. On macOS, `performAction(id, 'AXRaise')` performs the advertised raise action. Call `app.activate()` first when the application must become active. -4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. +4. Replace a packed chord such as `pressKey('shift+Tab')` with `pressKey('Tab', ['shift'])`. Check `(await cua.getCapabilities()).methods` before using `sendKeyEvent`. On macOS, call it inside one `run_code` to hold a key across tool calls. To request one repeat, send another down for a non-modifier key held by that execution. Returning, throwing or pausing releases any remaining keys. If your script handles unknown macOS key names as `NATIVE_ERROR`, handle `INVALID_ARGUMENT` instead. Correct the key name before retrying. 5. Read `dispatched` from action results, then observe the application to verify the outcome. `invoke` returns `dispatched: false` when the element has no default action. Remove reads of the old `verified` field and of `pid` on selected objects or window records. Use `listApps()` or running `findApps()` matches when you need a PID. 6. For a custom provider, replace `CuaBackend.description` with `capabilities` and pass `guidance` and `permissionParameters` to `installCua`. Rebuild any custom `helperPath` against the [operation schema](../../../../packages/experimental/cua/src/protocol.ts) and [tagged permission response](../../../../packages/experimental/cua/src/access-types.ts). Restart the provider, inspect its advertised methods and keyboard scopes, and open the Computer Use permission page to verify its platform controls. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md index 7580de0836..b4551f624b 100644 --- a/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md +++ b/docs/upgrade-guide/v0.2.2-rc.1/cua-native-platform/guide.zh.md @@ -18,6 +18,6 @@ CUA 脚本在指定窗口上截图和操作鼠标。App 和 Window 对象共享 1. 调用 `cua.getApp(selector)` 后,从 `app.getWindows()` 返回的列表选定目标,再调用 `app.getWindow(windowId)`。在窗口上调用 `getScreenshot()`、`click()`、`scroll()` 和 `drag()`,将原有的 `hover` 调用改为 `window.mouseMove()`。在 macOS 上,`window.click(id)` 在元素中心发送鼠标事件。需要执行默认辅助功能动作时,改用 `invoke(id)`。需要打开控件菜单且控件声明了 `AXShowMenu` 时,调用 `performAction(id, "AXShowMenu")`。 2. 将 `getAXState()` 改为 `getAccessibilityTree()`,将 `getAXStateAndScreenshot()` 拆成读取树和截图两次调用。选择窗口时会静默读取初始树。选择应用时,只有 `appLevelAccessibility` 为真才读取。要显示树,请显式读取。 3. 将数字元素索引改为从最新树中取得的字符串 ID。直接发送请求时使用 `elementId` 和 `snapshotId`。原先调用 `performSecondaryAction` 的地方,先用 `listActions(id)` 取得完整动作名,再调用 `performAction(id, exactName, argument?)`。要执行默认动作,可调用 `invoke(id)`。`setValue` 接受提供方支持的 JSON 值。 在 macOS 上,`performAction(id, 'AXRaise')` 只执行元素声明的抬起窗口动作。需要把应用切到前台时先调用 `app.activate()`。 -4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 +4. 将 `pressKey('shift+Tab')` 之类的组合键写法改为 `pressKey('Tab', ['shift'])`。调用 `sendKeyEvent` 前检查 `(await cua.getCapabilities()).methods`。在 macOS 上,同一次 `run_code` 中可调用此方法跨工具调用保持按键。如果需要一次重复按下,可在这次执行中对已按住的普通键再发一次 `down`。执行返回、异常退出或用户暂停时会释放仍按着的键。如果脚本用 `NATIVE_ERROR` 识别 macOS 上的未知键名,请改为处理 `INVALID_ARGUMENT`,并在重试前修正键名。 5. 从动作结果读取 `dispatched`,再观察应用确认效果。元素没有默认动作时,`invoke` 返回 `dispatched: false`。移除读取旧字段 `verified` 的代码,以及对已选对象和窗口记录中 `pid` 的读取。需要 PID 时,使用 `listApps()` 或 `findApps()` 返回的运行中应用记录。 6. 自定义提供方需将 `CuaBackend.description` 改为 `capabilities`,并向 `installCua` 传入 `guidance` 和 `permissionParameters`。如配置了 `helperPath`,请按[操作协议](../../../../packages/experimental/cua/src/protocol.ts)和[带平台标记的权限响应](../../../../packages/experimental/cua/src/access-types.ts)重新构建 helper。重启提供方,检查它声明的方法和键盘输入范围,再打开 Computer Use 权限页确认平台控件。 From 77abacb4d2508f62eb0ee0f05a2d18e5c500d5ea Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 15:12:17 +0800 Subject: [PATCH 098/103] docs(cua): guide large accessibility tree searches in PTC --- packages/experimental/cua-macos/README.md | 2 +- packages/experimental/cua-macos/README.zh.md | 2 +- packages/experimental/cua-macos/src/guidance.ts | 1 + packages/experimental/cua/src/guidance.ts | 2 +- snapshots/session/cua-native/system-prompt.expected.md | 2 +- snapshots/session/cua-ptc/system-prompt.expected.md | 2 +- snapshots/session/ptc-script-retained/system-prompt.expected.md | 2 +- 7 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 46b035112e..f3d84f587e 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -200,7 +200,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index 341796b8c4..48c85aeeac 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -200,7 +200,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. diff --git a/packages/experimental/cua-macos/src/guidance.ts b/packages/experimental/cua-macos/src/guidance.ts index f8779651a9..8c481017ef 100644 --- a/packages/experimental/cua-macos/src/guidance.ts +++ b/packages/experimental/cua-macos/src/guidance.ts @@ -5,6 +5,7 @@ import { COMMON_GUIDANCE } from '@deepseek-ai/dsh-cua/guidance' export const PLATFORM_GUIDANCE = 'macOS: accessibility tree operations are available at app or window level. Simulated keyboard input is available at app level. Simulated mouse input is available at window level. For pointer input on a sheet, select its window ID with app.getWindow(id). For menu items outside a window, use app.invoke(id). findApps searches /Applications, /System/Applications, and ~/Applications. Use the Computer Use permission page to grant the helper application Accessibility and Screen Recording permissions in System Settings. Native window and AX bounds use macOS points, while delivered screenshots carry their own pixel dimensions. show does not switch Spaces, and Stage Manager can present reduced window geometry; explain any required foreground step before calling app.activate() or performing an advertised AXRaise action.' const methodDetails = new Map([ + ['getAccessibilityTree', 'If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current.'], ['mouseMove', 'Default hover requires both AXShowAlternateUI and AXShowDefaultUI on an enabled element or ancestor. Without an AX route it returns HOVER_UNAVAILABLE before sending input. Prefer click on a visible control or performAction with an advertised action. For web content without an AX hover action, use browser tools. Only systemPointerHover: true permits moving the visible cursor. If this returns FOREGROUND_REQUIRED, activate the app and check that the point is unobscured.'], ['click', 'click is a Window method: select a window with const win = await app.getWindow(windowId), then call win.click(target). For a background control’s default action, use app.invoke(id). For a mouse click on a background app, call app.activate() first and re-read the target. Both target forms send mouse-down and mouse-up events. click(id) uses the center of the full element bounds. If that center is outside the window, take a fresh win.getScreenshot() and use click([x, y]) on a visible part of the control in screenshot pixels. A background app can ignore the events even when dispatched is true. Verify the expected effect, such as a changed selection, before typing or retrying.'], ]) diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 745ccfe9be..d8d7d46660 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -22,7 +22,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. diff --git a/snapshots/session/cua-native/system-prompt.expected.md b/snapshots/session/cua-native/system-prompt.expected.md index 0b9c1b29f6..9866c3cb6d 100644 --- a/snapshots/session/cua-native/system-prompt.expected.md +++ b/snapshots/session/cua-native/system-prompt.expected.md @@ -57,7 +57,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. diff --git a/snapshots/session/cua-ptc/system-prompt.expected.md b/snapshots/session/cua-ptc/system-prompt.expected.md index b0af17e860..155edfc13e 100644 --- a/snapshots/session/cua-ptc/system-prompt.expected.md +++ b/snapshots/session/cua-ptc/system-prompt.expected.md @@ -59,7 +59,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. diff --git a/snapshots/session/ptc-script-retained/system-prompt.expected.md b/snapshots/session/ptc-script-retained/system-prompt.expected.md index fe5f42348b..0041a1a6f7 100644 --- a/snapshots/session/ptc-script-retained/system-prompt.expected.md +++ b/snapshots/session/ptc-script-retained/system-prompt.expected.md @@ -59,7 +59,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the full tree text; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. If the tree reports maxElements or maxDepth truncation, select a narrower window or ask the user to raise the named macOS provider setting and read again. In persistent PTC, capture a large tree with const tree = await win.getAccessibilityTree({ emit: false }). Filter its lines in memory, or save it with await tools.write({ file_path: path, content: tree }) to a new workspace file. Search its contents with tools.grep({ path, pattern }) and use tools.read around a matching line. Print only the matches you need. Use element ids from the file only while that observation is current. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. From fa993abc5ae3789339e160dcb9417812dc970631 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Sat, 7 Nov 2026 15:14:59 +0800 Subject: [PATCH 099/103] test(cua-macos): cover runs that only use keyboard shortcuts --- .../cua-macos/tests/provider-lifecycle.spec.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index f65e1a6a61..86bf7b9ba5 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -161,6 +161,20 @@ it('requires an enclosing run_code before sending a directional key', async () = expect(native.request).not.toHaveBeenCalled() }) +it('finishes a shortcut-only run_code without requesting held-key cleanup', async () => { + const f = await setup(undefined, true) + await selectApplication(f) + native.request.mockClear().mockResolvedValue({ dispatched: true }) + const result = await executeModelToolFixture(f.ctx, { agent: f.handle.agent, callId: ToolCallId('shortcut-run'), + name: 'run_code', signal: new AbortController().signal, arguments: { + code: "return await tools.cua({ method: 'pressKey', params: { appHandle: 'app-one', key: 'a', modifiers: ['command'] } });", + description: 'Press Command+A', + } }) + expect(result.isError).toBe(false) + expect(native.request.mock.calls.map(([method]) => method)).toEqual(['pressKey']) + expect(native.cleanup).not.toHaveBeenCalled() +}) + it.each(['return', 'throw', 'pause', 'pause with cleanup error'])('cleans up only the held W when run_code ends by %s', async (ending) => { const f = await setup(undefined, true) await selectApplication(f) From 63e00f87ec8eda5bfc4fa201af524db850917cfa Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Sat, 7 Nov 2026 15:46:36 +0800 Subject: [PATCH 100/103] fix(forge): keep narrow file header actions inside the card The card's overflow clip cut off the viewed mark and the file menu when a narrow header also held a long path, the changed tag, and a rename badge; before the cards, the list could still scroll sideways to them. The icon, path, changed tag, and badge now share one box that shrinks to any width, so the counts, the viewed mark, and the menu after it stay whole. The path and badge shorten in proportion to their widths, the changed tag is capped at 30% of the box with an ellipsis, and the path keeps its full-path tooltip. A 390px e2e renames a long file, changes it after it is marked viewed, and checks that the mark and menu stay inside the card, the mark still toggles, and hovering the name shows both paths. --- apps/web/tests/forge-panel.e2e.ts | 48 +++++++++++++++++++ .../client-ui-forge/README.i18n.yaml | 4 +- .../experimental/client-ui-forge/README.md | 2 +- .../experimental/client-ui-forge/README.zh.md | 2 +- .../src/client/ChangesTab.module.css | 24 +++++++++- .../client-ui-forge/src/client/DiffFile.tsx | 16 ++++--- 6 files changed, 85 insertions(+), 11 deletions(-) diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index f66c449b52..53d58e3493 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -1844,3 +1844,51 @@ it.skipIf(MODE === 'record')('keeps local viewed marks across reloads, clears a await page.keyboard.press('Escape') expect(tripwire.pageErrors).toEqual([]) }) + +it.skipIf(MODE === 'record')('keeps a narrow file header\'s viewed mark and menu inside its card and its name under the pointer', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-narrow-header', 'normal', { branch: 'feat' }) + const from = 'src/original-review-module-with-a-long-name.ts' + const to = 'src/renamed-review-module-with-an-even-longer-name.ts' + const body = Array.from({ length: 20 }, (_, index) => `export const value${index} = ${index}\n`).join('') + await mkdir(join(project, 'src')) + await writeFile(join(project, from), body) + await git(project, 'add', from) + await git(project, 'commit', '--quiet', '-m', 'Add the module') + // The base holds the old path, so the branch shows a rename. + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await git(project, 'mv', from, to) + await writeFile(join(project, to), `${body}export const extra = 1\n`) + await git(project, 'commit', '--quiet', '-am', 'Rename the module') + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.getByRole('button', { name: '打开右侧边栏', exact: true }).click() + await page.locator('[data-sidebar-right-guide]').getByRole('button', { name: /^代码审查和变更/ }).click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + await page.locator('[data-forge-local]').getByRole('button', { name: /^查看本会话的变更/ }).click({ timeout: 20_000 }) + const local = page.locator('[data-forge-changes="local"]') + const name = 'renamed-review-module-with-an-even-longer-name.ts' + const file = local.locator(`[data-forge-diff-file="${to}"]`) + const viewed = file.getByRole('checkbox', { name: `将 ${name} 标记为已审阅`, exact: true }) + await viewed.check({ timeout: 20_000 }) + await writeFile(join(project, to), `${body}export const extra = 2\n`) + await local.getByRole('button', { name: '刷新变更', exact: true }).click() + await expect.poll(() => file.getAttribute('data-viewed'), { timeout: 20_000 }).toBe('changed') + await file.getByText('由 original-review-module-with-a-long-name.ts 重命名', { exact: true }).waitFor() + + // The changed tag, the rename badge, and the long path compete for one narrow header with the counts and actions. + await page.setViewportSize({ width: 390, height: 780 }) + const label = file.locator('[data-forge-file-label]') + const [card, mark, menu, labelBox] = await Promise.all([ + file.boundingBox(), viewed.boundingBox(), file.getByRole('button', { name: `${name} 的更多操作`, exact: true }).boundingBox(), label.boundingBox(), + ]) + if (card === null || mark === null || menu === null || labelBox === null) throw new Error('The header controls must be rendered') + expect(mark.x + mark.width).toBeLessThanOrEqual(card.x + card.width) + expect(menu.x + menu.width).toBeLessThanOrEqual(card.x + card.width) + expect(labelBox.width).toBeGreaterThan(40) + await label.hover() + await page.getByRole('tooltip').filter({ hasText: `${from} → ${to}` }).waitFor() + await viewed.check() + await expect.poll(() => file.getAttribute('data-viewed')).toBe('viewed') + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index d8c84dfd57..c85baa23fe 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 8d017c771840d6de - zh: 0705332c947f825a + en: c7e1b7d87ccccd2e + zh: 42d864b918a6175c /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: en: 7495fe1e0d0ee643 zh: f820a5790ae6e2a7 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index 67966cf983..3986c9bffc 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -38,7 +38,7 @@ Panel text follows the application language: Chinese, English, Japanese, Spanish - **Session list** — after a Session row's time, a branch glyph shows while the Session works in the worktree the panel created for it, and a glyph shows the state of its most urgent change request: one needing attention first, then open, draft, not yet polled, merged, and closed. The glyph of an open change request keeps the row's subdued color, with its head branch end filled in the color of running, passed, or failed checks; merged and closed ones keep their state colors. The row's hover card names the worktree branch and what it started from, then up to three change requests with their number, title, state, and checks, and how many more there are. A restart shows the states known before it until the next poll. - **Tab** — the first row names the checked-out branch, or the abbreviated commit on a detached HEAD, after a folder glyph for the project directory or a branch glyph for a worktree, and the kind of checkout, which is the worktree the Session created with its base, another worktree, or the project directory; its tooltip adds the path with the Host home shortened to `~`, its button copies the full path, and for a removed worktree it offers Restore. Below it, each change request card shows a glyph for its state, its title, which opens it in the browser, and its number; the glyph tells open, draft, merged, and closed apart, and marks an open one that is not a draft with failed checks, requested changes, or conflicts as needing attention, as the header button's red dot does. The card's header also offers Open in browser, Copy change request link, and Remove from this Session, whose toast offers Undo. Cancelled checks have a separate count; a collapsed card names cancellations when no listed check failed. A collapsed card adds the checks of an open change request and the most urgent of requested changes, conflicts, or draft, or when a merged or closed one ended. An expanded card shows the head and base branches, then one row per fact: for an open change request the checks, whose row opens the list of checks with failed ones first and their durations and links, the review decision with unresolved threads, whose count ends in `+` when the provider counted only some threads, and the merge state, or when a merged or closed one ended; and the changed lines, formatted in the selected UI language, whose row opens the changes view. An open draft also offers Ready for review; a change request the host would merge now offers Merge, whose menu lists the methods the repository allows with the user's usual one chosen and pins the displayed head when opened. Confirm merge uses that head; a polled head change disables confirmation until the menu is reopened after review. A toast reports each outcome, and new commits since that head stop the merge. When exactly one bound change request is open, its card starts expanded. Refresh inspects the checkout, checks sign-in, and polls every change request again; its icon turns until the inspection and the sign-in check end. A banner shows the `gh auth login` command when sign-in is missing. - **Local changes card** — whenever the `branch` scope changes files, independently of bound change requests, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, which is always the default base below, and shows the added and deleted lines and the number of files, which open the changes view; its file list, which names files as the changes view does, opens the view at one file. Create change request, offered when the code host repository is recognized and no open change request (including drafts) has the checked-out branch as its head, sends the Session a user message in the UI language that asks the Agent to create a change request for these changes, and a toast reports whether it was sent. -- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. +- **Changes view** — The Changes row of an expanded change request card and the local changes card open a right-sidebar tab that lists the changed files. The local tab is named Local changes and shows Branch by default: the working tree and untracked files against the fork point. Its header names the checked-out branch, or the abbreviated commit on a detached HEAD, and the base branch, which opens a searchable menu: first Default, the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote, then remote-tracking and then local branches, each most recently committed first, without the checked-out branch and, outside a created worktree, without the remote-tracking branch Default already names. Typing filters the listed rows at once and lists the branches whose names contain the text, ignoring case, after a short pause; Enter chooses the first row. Choosing another branch compares with the merge base of HEAD and that branch. The tab keeps the choice while other scopes show; closing the tab or reloading the application returns it to Default. When the chosen branch is gone, its name is struck through, and when it shares no history with HEAD, the view says so as well; both offer Use the default base branch instead of Retry. A narrow view hides the note that uncommitted changes count, then the checked-out branch. Uncommitted compares them with HEAD, Unstaged with the index, and Staged compares the index with HEAD. A change request view shows the host's diff at its head and says how many commits the checked-out branch has beyond that head when it is the change request's head branch. The toolbar jumps to a file, totals the changed lines, refreshes, and switches between two columns and one and between wrapped and cut long lines. Visited changes tabs stay mounted across tab and Session switches, hiding the sidebar, and docking changes, preserving file folds, revealed large files, expanded context, layout, and scroll position while the diff is unchanged. Hidden changes views release their panel subscription and defer diff reads; returning reads again only when the latest head or local summary differs. A refresh that replaces the diff discards expanded context, and changed content may move the reading position. Temporary menus close when the view is hidden. Closing the tab or reloading the application discards this progress. Each file is a separate card, with a tinted header that stays at the top while its lines scroll. Files are named before their directories, which use smaller subdued type and shorten first; hovering one shows its complete path, and both paths for a renamed file. Each file shows badges for a new, deleted, or renamed file, the last naming the old file name, or the old path when only the directory changed, and, in the Branch scope, an untracked one, and a menu that copies its path and opens the whole file in the sidebar for local changes or its page at the head in the browser for a change request. When the header is narrow, the path, the badges, and Changed since viewed shorten, so the line counts, Viewed, and the menu stay whole. Unchanged lines between hunks collapse into rows that expand from the file's new side: the working tree, the index for Staged, or the head commit through the code host; a file that changed after the diff was read stays collapsed until the view reads again. A binary file and an untracked file over `maxDiffBytes` show a note instead of their lines, a file whose hunks draw more than 1,000 lines starts as one collapsed strip that names its changed lines and draws them when opened, and a file below files that change more than 5,000 lines starts collapsed. The view reads again on Refresh and the page refresh shortcut, on each navigation, when the change request's head moves, and when the Branch scope's summary changes; a change request's view first waits for the status that names its head, unless no provider serves it or that poll failed. When the head moved past the latest status, the view keeps loading and reads again at the head of a status later than the one the read started with, at once when that status arrived during the read. While a read replaces changes already shown, the Refresh icon turns. A change request whose diff the code host or its provider refuses over a size limit, such as a GitHub diff whose output exceeds the provider's `maxOutputBytes`, says its changes are too large to show here and offers View in browser; another failed read offers Retry and, for a change request, View in browser. A change request's diff is downloaded once per head commit and base branch while it stays cached, so reopening, refreshing, and navigating at the same head read nothing from the host. - **Review layers, test files, viewed files, and commits** — Above the file tree, the lens keeps All files or the files of one layer, Interface, Implementation, or Tests, each with its count; where no tree shows, the toolbar offers the lens as a menu. The repository decides first: a file whose root `.gitattributes` sets `dsh-review-layer=test`, `interface`, or `implementation` is in that layer, and one it marks `linguist-generated` is in Tests. Next come the optional `testPaths` and `interfacePaths` globs, which add to the built-in rules and are empty by default. The built-in rules then follow common conventions: test directories and files of Jest, Vitest, `go test`, pytest, RSpec, XCTest, and .NET, snapshots, locale catalogs, and lockfiles are Tests; package manifests, type declarations, headers, stubs, and interface definitions such as Protocol Buffers, GraphQL, and OpenAPI are Interface. Every other file is in Implementation. For example, `*_test.go dsh-review-layer=test` or `api/**/*.yaml dsh-review-layer=interface` in `.gitattributes` records a repository's own convention. Hide test files leaves Tests out of the file tree and the diff without listing them, and disables the Tests lens. Viewed on a file header marks that change of the file viewed and collapses it; the toolbar shows how many of the shown files are viewed, and `V` marks or clears the file being read: the file holding the focus or the text cursor, else the file at the top of the view. A file whose change differs from the change it was marked at shows Changed since viewed and expands again. Marks are kept in this browser per Session, source, path, and change digest, so they survive closing the tab and reloading, and the tabs of one Session share them: a mark in one tab appears in the others and keeps their marks. A change of the file mode alone, such as `chmod +x`, also counts as a new change. All commits beside Submit review, and beside the base branch in the Branch scope, lists the commits oldest first, read once until the head, the local branch or base, or a refresh changes them; a click shows one commit and a Shift click the commits from the last one clicked, which must follow each other as first parents: a run that leaves that line, such as one across a merged branch, keeps the menu open and says why; the view then shows those commits' changes, reads unchanged lines at the last of them, and offers Add to input but no GitHub comment or review. Branch commits exclude uncommitted and untracked files. Another base or scope returns to all commits, and chosen commits that are gone or no longer one run offer Show all commits. diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 0bdfdea790..d5bdf45e9d 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -38,7 +38,7 @@ kind: "package-reference" - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,head 分支端点填充为检查进行中、已通过或失败对应的颜色;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 - **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。已取消的检查单独计数;列出的检查没有失败项时,折叠卡片显示取消数量。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数(提供方只统计了部分讨论时数字后带 `+`)、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 - **本地变更卡片**——`branch` 范围有文件变更时始终显示,不受已关联变更请求影响。变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`,始终是下文的默认基准)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库、且没有以当前检出分支为源分支的打开中变更请求(含草稿)时,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更。它的标题栏写出当前检出的分支(分离 HEAD 时为缩写提交)与基准分支;点击基准分支打开可搜索的菜单:最前面是“默认”,即 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准;其后依次是远程跟踪分支与本地分支,各按最近提交排序,不含当前检出的分支,不在所创建的 worktree 中时也不含“默认”已经指向的远程跟踪分支。输入文字会立即筛选已列出的行,短暂停顿后列出名称包含该文字(不区分大小写)的分支;按 Enter 选择第一行。选择其他分支后,与 HEAD 和该分支的合并基准比较。标签页切换到其他范围时仍保留这个选择;关闭标签页或重新加载应用后回到“默认”。所选分支已不存在时,它的名称显示删除线;它与 HEAD 没有共同历史时,视图同样给出说明;两种情况都提供“使用默认基准分支”而不是“重试”。视图较窄时,先隐藏“包含未提交的修改”,再隐藏当前分支。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。每个文件是一张独立的卡片,带浅色底的标题在滚动时停在顶部。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。标题变窄时,路径、标记和“有新改动”会缩短,行数、“已审阅”和文件菜单始终完整显示。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。head 已越过最新状态时,视图保持加载,等到比读取开始时更新的状态后按其 head 重新读取;该状态在读取期间已到达时立即重读。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上输出超过提供方 `maxOutputBytes` 的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 - **分层、测试文件、已审阅与提交**——文件树上方的分层透镜保留全部文件,或“接口”“实现”“测试”中一层的文件,并显示各自的数量;不显示文件树时,工具栏以菜单提供透镜。仓库的声明优先:根目录 `.gitattributes` 把文件设为 `dsh-review-layer=test`、`interface` 或 `implementation` 时,文件属于对应的层;标为 `linguist-generated` 的文件属于“测试”。其次是可选的 `testPaths` 与 `interfacePaths`,它们追加在内置规则之前,默认为空。最后是按常见约定写的内置规则:Jest、Vitest、`go test`、pytest、RSpec、XCTest 与 .NET 的测试目录和文件、快照、本地化目录与 lockfile 属于“测试”;包清单、类型声明、头文件、类型存根与 Protocol Buffers、GraphQL、OpenAPI 等接口定义属于“接口”。其余文件属于“实现”。例如在 `.gitattributes` 中写 `*_test.go dsh-review-layer=test` 或 `api/**/*.yaml dsh-review-layer=interface`,即可记录仓库自己的约定。“隐藏测试文件”让文件树与 diff 都不显示“测试”层,也不列出被隐藏的文件,同时停用“测试”透镜。文件标题上的“已审阅”把该文件的这次改动标为已审阅并折叠它;工具栏显示已显示文件中已审阅的数量,按 `V` 标记或取消当前阅读的文件:焦点或文本光标所在的文件,否则是视图顶部的文件。改动与标记时不同的文件显示“有新改动”并重新展开。标记按 Session、变更来源、路径与改动摘要保存在本浏览器中,关闭标签页或重新加载后仍在;同一 Session 的多个标签页共用这些标记:在一个标签页中标记,其他标签页随之更新,且不会覆盖它们的标记。只改文件模式(例如 `chmod +x`)也算新改动。“提交评审”左侧,以及“分支”范围中基准分支右侧的“全部提交”按从旧到新列出提交,读取一次后保留到 head、本地分支或基准变化或刷新为止;单击只看一个提交,按住 Shift 单击看从上次单击的提交到这个提交的连续多个提交,这些提交必须依次是后一个的第一父提交:离开这条链的范围(例如跨越已合并分支的范围)会让菜单保持打开并说明原因;此时视图显示这些提交的改动,在最后一个提交读取未变更的行,提供“添加到输入框”,但不提供 GitHub 评论或评审。“分支”的提交不含未提交与未跟踪的文件。换基准分支或范围后回到全部提交;所选提交已不存在或不再是一条链时提供“查看全部提交”。 diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css index ae8a40f3f8..f1603a01d4 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -446,10 +446,23 @@ border-bottom: 0; } +/* The file's own information gives way inside this box, so the counts, the viewed mark, and the menu after it stay + whole at any width. */ +.fileTitle { + display: flex; + flex: 1 1 0; + align-items: center; + gap: 6px; + min-width: 0; + overflow: hidden; +} + .fileIcon { flex: none; } +/* The path shares the shortage with the badge in proportion to their widths, so the longer path keeps the larger part + and stays under the pointer for its full-path tooltip. */ .filePath { display: flex; flex: 0 1 auto; @@ -469,8 +482,16 @@ transform: rotate(-90deg); } +/* Capped rather than shrunk, so a long path never truncates the tag; a longer translation ends in an ellipsis. */ .changedTag { flex: none; + max-width: 30%; +} + +.changedText { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; } /* The viewed mark: a native checkbox with its label as one bordered chip, peer to the file menu button. */ @@ -526,7 +547,8 @@ } .badge { - flex: none; + flex: 0 1 auto; + min-width: 0; max-width: 50%; overflow: hidden; padding: 0 6px; diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index ad46c66132..a66175afb4 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -458,13 +458,17 @@ export function DiffFile(props: DiffFileProps): ReactNode { > - - - + + + + + + {viewed === 'changed' && ( + {t('viewed.changed')} + )} + + {badge !== '' && {badge}} - {viewed === 'changed' && {t('viewed.changed')}} - - {badge !== '' && {badge}} {!file.binary && }