diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml b/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml index f50ce14bc9..96e5042c3e 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.i18n.yaml @@ -15,8 +15,8 @@ en: db0a2deb9193a00d zh: dab5a65b88957464 /agent-note-experimental-auto-review-before-each-tool-call/decision/one-complete-reviewer-request: - en: 7bd9fef90e8639b9 - zh: e2a096885c9c1e83 + en: 45ac7b4e759b29ad + zh: 5374cc89e587f076 /agent-note-experimental-auto-review-before-each-tool-call/decision/result-and-cancellation: en: 647fe68c52b907e0 zh: 267a739bad44ad65 diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.md b/.agents/notes/implemented/feature/2026-08-28-auto-review.md index 9434c92f41..547dd3a2cf 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.md +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.md @@ -41,6 +41,8 @@ The integration uses only the latest `request/header.config` provider/model and Each item is its own message and keeps the same text in later reviews: the pending call becomes a historical call, and the integration remembers, for each live Session, the schema each reviewed call showed so that it reappears at the same position. A review's messages therefore begin with all messages of the previous review. Providers that cache only at message ends, such as OpenAI implicit breakpoints on GPT-5.6 and later, or at a final marker with lookback, such as Anthropic `cache_control`, reuse the previous review; one growing user message let them reuse only the policy. The schema memory is process-local, so the first review after a restart omits earlier schemas and misses the cache once. +The request also carries the reviewed Session's `sessionId` and `purpose: 'auto-review'`. Routes that require a per-conversation identity or key prompt caching on one, such as the `x-opencode-session` header OpenCode requires and OpenAI `prompt_cache_key`, derive it from that id; without it OpenCode rejects every review, and Auto fails every call. The [DeepSeek Session-log upload](../../../../packages/session/session-log-deepseek/README.md#request-field) applies the same eligibility and registered exclusions to reviews as to other requests. The uploaded data is the canonical Session log; review prompts and decisions remain outside that log. + The reviewer builds the history and the pending call from the Session's complete action history: an authorization is the earlier call the `REVIEW_POLICY` source rules make eligible, and a duplicate or conflicting identity has to be visible anywhere in the log rather than inside a recent window, so neither the Session projections nor a bounded read serves the decision. The read is the deprecated synchronous `snapshotEvents()` under a line-scoped `typescript/no-deprecated` waiver. The main agent's V3 `system/message` nodes, assistant text/reasoning, and tool results are excluded. The current call must belong to the open step recorded by `step/start`; missing step ownership fails closed. It appears only as the final message; an unstarted sibling has no historical call fact. Native schema comes from the latest request header. PTC captures a frozen schema at binding construction and passes it through the scheduler into `ToolExecution`; descriptions and parameter schemas never enter start/settle events or the Session/SDK wire. Missing, inconsistent, or ambiguous action facts reject the call without consulting the live registry. An oversized request fails closed without summarization, truncation, another compaction pass, or a small output-token budget. diff --git a/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md b/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md index 5ba7a8b39c..bc833d3fc3 100644 --- a/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md +++ b/.agents/notes/implemented/feature/2026-08-28-auto-review.zh.md @@ -41,6 +41,8 @@ Integration 只使用最新 `request/header.config` 的 provider/model 与 shi 每个条目各占一条消息,并在后续评审中保持相同文本:待审调用会变成历史调用,integration 为每个存活 Session 记住每次已审调用展示的 schema,使其在同一位置再次出现。因此一次评审的消息以上一次评审的全部消息开头。只在消息结尾缓存的 provider(如 GPT-5.6 及以后的 OpenAI 隐式断点),或在末尾标记处向前回溯的 provider(如 Anthropic `cache_control`),都能复用上一次评审;单条不断增长的 user 消息只能让它们复用策略。Schema 记忆只在进程内,因此重启后的第一次评审会缺少先前的 schema,并有一次缓存未命中。 +请求还携带被评审 Session 的 `sessionId` 与 `purpose: 'auto-review'`。需要按对话标识路由或以其为 prompt 缓存键的路由(例如 OpenCode 要求的 `x-opencode-session` header 与 OpenAI 的 `prompt_cache_key`)由该 id 派生;缺少它时 OpenCode 会拒绝每次评审,Auto 会让每个调用失败。[DeepSeek session-log 上传](../../../../packages/session/session-log-deepseek/README.zh.md#request-field)对评审和其他请求应用相同的上传资格与注册排除条件。上传的是权威 Session 日志;评审提示词和决策仍不进入该日志。 + reviewer 从 Session 的完整动作历史构建历史与待审调用:授权是符合 `REVIEW_POLICY` 来源规则的那个更早调用,而重复或冲突的身份必须在整份日志的任何位置都可见,而不是只在近期窗口内可见,因此 Session 投影与有界读取都无法支撑该判定。这次读取使用已废弃的同步 `snapshotEvents()`,并带有行级 `typescript/no-deprecated` 豁免。 主 agent 的 V3 `system/message` 节点、assistant 正文/reasoning 与 tool results 全部排除。当前调用必须属于 `step/start` 记录的开放 step;缺少 step 归属时拒绝执行。该调用只作为最后一条消息出现;尚未开始的 sibling 没有历史调用事实。原生 schema 来自最新 request header。PTC 在 binding 构造时捕获冻结 schema,经由调度器传入 `ToolExecution`;描述与参数 schema 不进入开始/结算事件或 Session/SDK wire。动作事实缺失、不一致或有歧义时拒绝调用,不查询 live registry。超窗请求直接拒绝,不做摘要、截断、额外 compaction 或设置小型输出 token 预算。 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml index 7d202e9987..6f3f674ec6 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.i18n.yaml @@ -9,14 +9,14 @@ en: 344bcc7e9825bbc8 zh: c1d0f4b54f5b3786 /agent-note-change-request-panel-and-worktree-sessions/decision: - en: b18b287b701aef93 - zh: 462c0f561f1a0c18 + en: 0b159e4e33409515 + zh: 2bf1eafd644f2d26 /agent-note-change-request-panel-and-worktree-sessions/deferred: en: 32ef8af85f4d2f66 zh: b82b67f94346399e /agent-note-change-request-panel-and-worktree-sessions/alternatives-considered: - en: 91b3338f958ad0e9 - zh: b64f30d333280084 + en: e471e16b6b6450ca + zh: 5fbc9242edc8d112 /agent-note-change-request-panel-and-worktree-sessions/consequences: en: 97976f073b9f65e0 zh: 95be3f7f375b0876 diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md index 20b9231fce..7792f8caf9 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.md @@ -26,6 +26,8 @@ The panel does not move a Session between existing worktrees. Removing a change The panel also shows the changes behind a Session's work in a changes view, a resource tab type of this package. The Remote parses every diff on the Host into files and hunks, so the browser draws them without a patch parser, and bounds each read with `maxDiffBytes` and `maxUntrackedFiles`. Local changes come from confined `git diff` in the Session's execution world, in a scope the user picks: the branch against its fork point by default, or the uncommitted, unstaged, or staged changes; untracked files are read through the Session's filesystem and shown as new files. A change request's changes come from its code host at the head of the binding's latest status, through two provider reads the forge seam gained, `diff` and `fileText`. The Host keeps the patch it read last for each change request, keyed by the head commit and base branch and bounded by `maxCachedDiffBytes`, so reopening, refreshing, and navigating at the same head download nothing again; a host or provider that refuses an answer over its size limit reports the forge failure `too-large`, and the view then offers the change request's web page instead of a retry. Unchanged lines between hunks expand from the file's new side, which is the working tree, the index, or the head commit, and only while that text still matches the hunks. Each inspection also sizes the branch's changes for a local changes card, shown while no open change request carries the checked-out branch; its Create change request sends the Session a user message, so the Agent creates the change request with its own tools and the binding follows from `gh pr create` as for any other. +Review comments capture the file, side, range, complete hunk, and reviewed head when the user selects code. Agent references enter the existing composer quote mechanism, so the user controls batching and the sent message records exactly what the model receives. GitHub writes belong to the optional forge provider operation: preflight checks the current head, the write addresses that commit, and an ambiguous outcome blocks another write until the user reconciles it. Review drafts and inline records belong to a browser tab occurrence, not to the Session log or a GitHub pending review. Switching Sessions retains that occurrence; closing it discards the local state and rejects late write completions. Published GitHub comments remain external records. + ## Deferred A left-navigation review page next to Plugins and Scheduled tasks, listing the user's pull requests or merge requests on the selected provider, is deferred. It attaches without changing this package's Session surfaces: @@ -79,6 +81,12 @@ The changes view offers no scope for one commit or for the last turn yet; both w **Creating the change request from the card.** The panel would need to push the branch and compose the title and description; a message lets the Agent do both with its tools and the user's instructions, and keeps one way to bind change requests. +**Sending each line comment immediately to the Agent.** It starts a turn before the user can collect related comments or add a shared instruction; composer references preserve that choice. + +**Keeping review drafts after their tab closes.** Reopening the same PR would restore abandoned review state. A tab occurrence gives closing a clear discard meaning while preserving Session switching. + +**Automatically retrying a review write.** A lost response does not mean that GitHub rejected the request. Retaining the outgoing request and requiring reconciliation prevents a transport failure from silently duplicating comments. + ## Consequences The panel shows current status only while it is open; checks that finish while nothing is mounted produce no notification. Changes made outside the Session appear after Refresh or the next tool result. Every inspection spawns up to eleven short Git processes in the Session's execution world with one remote, and two more for each further remote it tries for a fork point. A worktree exists only for a Session that requested it before its first step, and a failed or cancelled attempt can leave its branch or checkout behind. A message that enters while the Agent runs a turn or other maintenance gets no hold, so its worktree is created within the first turn and a removed worktree is not checked. While a message waits, the Agent stays idle in maintenance: the composer offers no stop, and callers waiting for the Agent to become idle wait as well. Restoring loses changes that were never committed. A base branch that requires a merge queue cannot merge from the panel. With Git Worktrees also enabled, two independent worktree services exist; the model's tool never sees the panel's service. A local or change request diff over `maxDiffBytes`, or one the host refuses, shows no files. Expanding unchanged lines of a change request reads each file from the code host once. diff --git a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md index 9ea88f5ec6..ea7847b96e 100644 --- a/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md +++ b/.agents/notes/implemented/feature/2026-10-09-forge-panel.zh.md @@ -26,6 +26,8 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 面板还通过变更视图展示 Session 工作背后的变更;变更视图是本包的一个资源标签页类型。Remote 在宿主上把每个 diff 解析成文件与 hunk,因此浏览器无需补丁解析器即可绘制,每次读取都受 `maxDiffBytes` 与 `maxUntrackedFiles` 约束。本地变更来自 Session 执行环境中受限的 `git diff`,范围由用户选择:默认是分支相对于分叉点的变更,也可以是未提交、未暂存或已暂存的变更;未跟踪文件经 Session 的文件系统读取,显示为新文件。变更请求的变更来自代码托管平台,取自绑定最新状态中的 head,经 forge seam 新增的两个提供方读取操作 `diff` 与 `fileText` 获得。Host 为每个变更请求保留最近读到的补丁,按 head 提交与目标分支区分,总量受 `maxCachedDiffBytes` 约束,因此在同一 head 下重新打开、刷新与导航都不会再次下载;托管平台或提供方因结果超过其大小上限而拒绝时报告 forge 失败 `too-large`,视图随之提供变更请求的网页而不是重试。hunk 之间未变更的行从文件的新版本展开,即工作树、暂存区或 head 提交,并且只在该文本仍与 hunk 吻合时展开。每次检查还会为变更卡片统计分支的变更规模;没有打开中的变更请求以当前检出分支为源分支时才显示该卡片。卡片上的“创建变更请求”向 Session 发送一条用户消息,由 Agent 用自己的工具创建变更请求,绑定像其他变更请求一样来自 `gh pr create`。 +评审评论在用户选择代码时固定文件、侧、行范围、完整 hunk 与所评审的 head。Agent 引用进入既有输入框引用机制,由用户决定批量发送,发送后的消息记录模型实际收到的内容。GitHub 写入属于 forge 提供方的可选操作:预检核对当前 head,写入明确指向该提交;结果不明时阻止再次写入,直到用户核对。评审草稿与行内记录归浏览器页签实例所有,不进入 Session 日志,也不创建 GitHub 待提交评审。切换 Session 保留该实例;关闭时丢弃本地状态并拒绝迟到的写入结果。已发布的 GitHub 评论仍保留在外部平台。 + ## Deferred 在左侧导航“插件”“自动化任务”旁边新增代码审查页、列出用户在所选提供方上的 pull request 或 merge request,这项工作推迟。它的接入不需要改动本包面向 Session 的界面: @@ -79,6 +81,12 @@ Session 所在的 worktree 可能在 Session 之外被删除。每次检查都 **直接在卡片上创建变更请求。** 面板需要推送分支并撰写标题与描述;发送消息让 Agent 用自己的工具和用户的指示完成这两件事,绑定变更请求的方式也只保留一种。 +**把每条行内评论立即发送给 Agent。** 用户还没来得及收集相关评论或补充共同指令,就会开始一轮;输入框引用保留用户的选择。 + +**关闭页签后仍保留评审草稿。** 重新打开同一个 PR 会恢复已放弃的评审状态。页签实例让关闭明确表示丢弃,同时保留切换 Session 的状态。 + +**自动重试评审写入。** 丢失响应不代表 GitHub 拒绝了请求。保留发出的请求并要求核对,可以避免传输失败悄悄产生重复评论。 + ## Consequences 面板只在打开时显示当前状态;没有任何界面挂载时检查结束不会有通知。Session 之外的改动要等到刷新或下一个工具结果才会出现。只有一个远端时,每次检查最多在 Session 的执行环境中启动十一个短暂的 Git 进程;为寻找分叉点每多尝试一个远端,就多启动两个。只有在第一步之前提出请求的 Session 才会有 worktree,失败或被取消的尝试可能留下它的分支或检出。Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留,因此它的 worktree 在第一轮之内创建,已删除的 worktree 也不会被检查。消息等待期间,Agent 以空闲状态处于维护任务中:输入框不提供停止,等待 Agent 空闲的调用方也会一并等待。恢复会丢失从未提交的修改。要求合并队列的基准分支无法从面板合并。同时启用 Git Worktrees 时会存在两个互不影响的 worktree 服务;模型的工具看不到面板的服务。本地或变更请求的 diff 超过 `maxDiffBytes`,或被托管平台拒绝时,不显示任何文件。展开变更请求中未变更的行时,每个文件只从托管平台读取一次。 diff --git a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.i18n.yaml b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.i18n.yaml index 4a98c2f555..c8b3188032 100644 --- a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.i18n.yaml +++ b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.i18n.yaml @@ -18,11 +18,11 @@ en: 1310a89c351e5bfe zh: e6386ae10b893c2d /agent-note-performance-baselines-for-large-session-corpora/decision/measured-endpoints: - en: 11937dfa4a349a19 - zh: b91a136890fe92e8 + en: add81088ce51033f + zh: c7065dc3052648fa /agent-note-performance-baselines-for-large-session-corpora/calibration-evidence: - en: f934c95748dcbfe0 - zh: df6a68286c21510f + en: adb815c213373d8e + zh: 44d4c6752a4df51f /agent-note-performance-baselines-for-large-session-corpora/alternatives-considered: en: 4eaa4666262a1aee zh: 7e2eb44b94bad05d diff --git a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.md b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.md index 2efe66ead2..7890b73070 100644 --- a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.md +++ b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.md @@ -47,6 +47,8 @@ The shared corpus and projection-list controller fixture awaits controller activ The file must finish within five minutes on standard hosted CI, including seeding, and its last case asserts that limit. Search over 1,000 Sessions and one fork of the longest Session take about 170 s of it, so each has one sample. The list corpus is the largest that fits the remainder. Budgets enforce medians of list boot, first, and repeat, and of the fork median over strata and rank 990; search and the longest fork enforce their single samples. Search and fork use separate 1,000-Session roots, so fork children never reach the search index. Rank 988 is the highest top-level rank at the measured p99 (7,229 events); forking a subagent child adds a lineage lookup, and rank 990 already falls in the 99.3% anchor. Peak RSS of the list, search, and fork processes has a budget with the shared 1.25 headroom and no time scale. Each child's deadline equals the file limit, and each test's deadline outlasts its sequential children, so a failed case reaps every child before the scratch root is removed. +Fork workers use a 512 MiB V8 old-space limit so every runner measures the same heap constraint. The corpus, timed endpoints, and whole-process peak RSS budget stay unchanged; native buffers still count toward RSS. The longest fork retains about 193 MiB after collection, so the limit leaves room for live objects while forcing collection before a larger host-selected heap delays it. This measures a bounded-heap workload, not the default-heap peak of every deployment. + ## Calibration evidence Budgets use standard two-CPU hosted CI expectations (Linux x64, Node 24.21, PR #5403), rounded above the higher recorded median across the AMD EPYC 7763 and EPYC 9V74 runners and multiplied by the shared 1.25 headroom. Samples varied by up to 15% within one run; the runner models differed by up to 25% per endpoint. The hosted-to-reference ratio is 2.4 to 3.4, above the shared reference scale of 2, so reference-machine scaling would reject ordinary hosted runs. @@ -67,6 +69,8 @@ With seeding in one process, the complete file took 294.5 s on the EPYC 7763 run On Apple M5 Pro with Node 26.5, isolated runs measured list 1,000 at 311–358 ms first, list 5,000 at 1,364–1,603 ms first, search at 57 s first, and fork of the longest Session at 6.0–6.4 s. A 10,000-Session list took 3.2–5.4 s for the first call with 1.9 GB peak RSS. +Node 24.22 hosted runs of the unchanged longest-fork workload recorded 696 MiB peak RSS on EPYC 9V74 and 1,077.7 MiB on EPYC 7763, against the same 938 MiB budget. On Apple M5 Pro with Node 24.19, two default-heap runs retained 192.8–193.4 MiB and peaked at 770.7–812.6 MiB in 2.416–2.447 s; two 512 MiB old-space runs retained the same range and peaked at 764.2–764.7 MiB in 2.487–2.528 s. The fixed limit controls the heap policy without raising the RSS or timing budgets. + ## Alternatives considered - **Sanitized copies of real Sessions.** Rejected: benchmarks never use recorded user material. diff --git a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.zh.md b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.zh.md index f964d640b8..132619b19d 100644 --- a/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.zh.md +++ b/.agents/notes/implemented/testing/2026-09-28-session-corpus-performance.zh.md @@ -47,6 +47,8 @@ worker 是编译后的纯 Node 进程,每次都针对已播种根目录全新 此文件(包括播种)必须在标准托管 CI 上五分钟内完成,其最后一个用例断言该上限。1,000 个 Session 的搜索和最长 Session 的一次 fork 约占其中 170 s,因此两者各取一个样本。列表语料是剩余时间内能容纳的最大规模。预算约束列表启动、首次和重复的中位数,以及 fork 分层中位数和排名 990 的中位数;搜索和最长 fork 约束各自的单个样本。搜索和 fork 使用各自独立的 1,000 个 Session 根目录,因此 fork 子会话不会进入搜索索引。排名 988 是实测 p99(7,229 个事件)上最高的顶层排名;fork subagent 子会话会增加一次谱系查找,而排名 990 已落入 99.3% 锚点。列表、搜索和 fork 进程的峰值 RSS 设有预算,使用共享的 1.25 余量,不做时间缩放。每个子进程的截止时间等于文件上限,每个测试的截止时间长于其顺序子进程之和,因此失败的用例会在删除临时根目录之前回收所有子进程。 +Fork worker 使用 512 MiB 的 V8 old-space 上限,让各运行器在相同的堆约束下测量。语料、计时终点和整个进程的峰值 RSS 预算保持不变,原生缓冲区仍计入 RSS。最长 fork 回收后保留约 193 MiB,因此该上限为存活对象保留空间,同时避免较大的宿主默认堆延迟回收。该用例测量受限堆下的工作负载,不代表每种部署默认堆下的峰值。 + ## 校准证据 预算使用标准双 CPU 托管 CI 的期望值(Linux x64、Node 24.21、PR #5403),取高于 AMD EPYC 7763 与 EPYC 9V74 运行器中较高记录中位数的整数,再乘以共享的 1.25 余量。同一次运行内的样本差异最多 15%;两种运行器型号在单个端点上最多相差 25%。托管与参考机器的比值为 2.4 到 3.4,高于共享的参考缩放系数 2,因此按参考机器缩放会拒绝正常的托管运行。 @@ -67,6 +69,8 @@ worker 是编译后的纯 Node 进程,每次都针对已播种根目录全新 在 Apple M5 Pro 和 Node 26.5 上的隔离运行中,1,000 个 Session 的首次列表为 311–358 ms,5,000 个 Session 的首次列表为 1,364–1,603 ms,首次搜索为 57 s,fork 最长 Session 为 6.0–6.4 s。10,000 个 Session 的首次列表耗时 3.2–5.4 s,峰值 RSS 为 1.9 GB。 +未改动的最长 fork 工作负载在 Node 24.22 托管运行中,EPYC 9V74 的峰值 RSS 为 696 MiB,EPYC 7763 为 1,077.7 MiB,使用的预算均为 938 MiB。在 Apple M5 Pro、Node 24.19 上,两次默认堆运行回收后保留 192.8–193.4 MiB,峰值为 770.7–812.6 MiB,耗时 2.416–2.447 s;两次 512 MiB old-space 运行保留量相同,峰值为 764.2–764.7 MiB,耗时 2.487–2.528 s。固定上限用于控制堆策略,没有提高 RSS 或耗时预算。 + ## 考虑过的替代方案 - **脱敏复制真实 Session。** 已否决:基准从不使用录制的用户材料。 diff --git a/.agents/skills/record-browser-gif/SKILL.md b/.agents/skills/record-browser-gif/SKILL.md index a16f8294e9..1fa60fcb4f 100644 --- a/.agents/skills/record-browser-gif/SKILL.md +++ b/.agents/skills/record-browser-gif/SKILL.md @@ -1,6 +1,6 @@ --- name: record-browser-gif -description: Record browser or Web UI interaction demos as optimized GIFs using the available browser-control workflow, optional Playwright Videos for higher capture frame rates, and deterministic encoding, then attach the GIF to a pull request with `gh --attach`, falling back to a dedicated assets branch where attach cannot apply. Use when asked to make, record, or generate a GIF that demonstrates a browser workflow, and for every pull request that changes product-user-visible GUI behavior, which MUST include a GIF recorded from the pull request's real server and model flow. +description: Record browser or Web UI interaction demos as optimized GIFs using the available browser-control workflow, optional Playwright Videos for higher capture frame rates, and deterministic encoding, then attach the GIF to a pull request with `gh --attach`; publication requires gh v2.99.0 or later, and a GIF over 5 MiB is split into parts. Use when asked to make, record, or generate a GIF that demonstrates a browser workflow, and for every pull request that changes product-user-visible GUI behavior, which MUST include a GIF recorded from the pull request's real server and model flow. --- # Record Browser GIF @@ -17,8 +17,8 @@ The recording itself is part of the evidence: use a real server booted from that ## Keep recording separate from publication -- Recording produces local video or screenshots and one `.gif` artifact only; it never mutates remote state. -- Publication — attaching the GIF to a pull request body with `gh --attach`, or pushing it to an assets branch and embedding its URL where attach cannot apply — is the separate final step, performed only when the task includes attaching the GIF to a pull request. It never touches the pull request's own branch. +- Recording produces local video or screenshots; encoding produces one `.gif` artifact, or its [numbered parts](#attach-with-gh) when it exceeds the 5 MiB limit. Neither mutates remote state. +- Publication — attaching the GIF to a pull request body with `gh --attach` — is the separate final step, performed only when the task includes attaching the GIF to a pull request. It never commits to any branch. - Preserve the requested recording conditions. A real-server or real-API demo must not use fixture queries, mock transports, synthetic event injection, or test-only hooks. If credentials or the server are unavailable, report that limitation instead of substituting a fixture. - Never read or expose credential values. Use the application's normal configuration path and a benign demonstration prompt. @@ -117,13 +117,15 @@ Encoder maintenance: run `python3 -m unittest discover -s "$GIF_SKILL_DIR/script Perform this step only when the task includes attaching the GIF to a pull request. -Never commit a GIF to the pull request's own branch or any branch that merges into a long-lived branch: binary media committed there bloats the repository history for every future clone. Prefer `gh --attach`, which uploads the GIF to GitHub and rewrites the body reference in one command, so no branch carries the media. +Never commit a GIF to the pull request's own branch or any other branch: every default clone and full-history fetch of the repository downloads media committed to any branch. Publish only with `gh --attach`, which uploads the GIF to GitHub and rewrites the body reference in one command, so no branch carries the media. ### Attach with gh -`gh --attach` requires `gh` v2.99.0 or later (`gh --version`), a repository on github.com — GitHub Enterprise Server is not supported — write access to the repository, and a GIF at or below 10 MB. Confirm the verified artifact fits that limit; when it does not, shrink it with `--max-width`, then `--colors` or `--fps`, before attaching. +Before attaching, check `gh --version`. `gh --attach` requires `gh` v2.99.0 or later, a repository on github.com — GitHub Enterprise Server is not supported — and write access to the repository. When `gh` is older than v2.99.0, stop and tell the developer to upgrade `gh` to v2.99.0 or later; keep the verified GIF for the retry, and do not install or upgrade `gh` without authorization. When any other requirement is unmet or the attach fails — authentication, write access, a repository outside github.com, or an upload error — stop and report it to the developer. Never publish the GIF any other way. -Write the GIF into the body file as an ordinary local-path reference, using the same path passed to `--attach`; `gh` rewrites the reference in place to the uploaded URL, keeping its position and alt text: +Publish GIFs at or below 5 MiB, the encoder's default `--max-bytes`. When the encoder rejects the output for size, shrink it with `--max-width`, then `--colors` or `--fps`. When the GIF still exceeds 5 MiB at readable text quality, split it instead: encode consecutive, non-overlapping intervals of the same evidence run into numbered parts that each pass the encoder's size check — `--start` and `--end` over the one video, or consecutive screenshot subsets selected with `--pattern` — and verify every part as an artifact. Beside each embed, state its position (such as `2/3`) and its source interval or frames. + +Write each GIF into the body file as an ordinary local-path reference, using the same path passed to `--attach`; `gh` rewrites each reference in place to its uploaded URL, keeping its position and alt text, so the order of references in the body sets the display order of split parts: ```markdown ![]() @@ -138,35 +140,8 @@ gh pr create --body-file --attach # new pull re gh pr edit --body-file --attach # existing pull request ``` -`--attach` is repeatable but refuses the same file twice. A GIF the body does not reference is appended at the end, where alt text set on the flag (`--attach '#'`) applies; a rewritten reference keeps the body's alt text. After attaching, re-read the demonstrated live head and require it to remain at that recorded commit. Re-read the live body and confirm the reference now points at the uploaded URL, render the body through GitHub's Markdown API and confirm the expected ``, and fetch the uploaded URL once to confirm `200` and `image/gif`. +`--attach` is repeatable but refuses the same file twice. Publish split parts in one `gh pr create` or `gh pr edit` with one `--attach` per part, so a single pair of live-head checks covers every part. A GIF the body does not reference is appended at the end, where alt text set on the flag (`--attach '#'`) applies; a rewritten reference keeps the body's alt text. After attaching, re-read the demonstrated live head and require it to remain at that recorded commit. Re-read the live body and confirm the reference now points at the uploaded URL, render the body through GitHub's Markdown API and confirm the expected ``, and fetch the uploaded URL once to confirm `200` and `image/gif`. -### Fall back to an assets branch +### Existing assets branches -Use the assets-branch workflow only when `gh --attach` cannot apply: the GIF still exceeds 10 MB, `gh` is older than v2.99.0, or the repository is not on github.com. GIFs then live on a dedicated orphan assets branch — a branch with no parent commit and nothing but media — and one assets branch serves a whole pull request series (named `-assets`; list existing ones with `git ls-remote --heads origin '*assets*'`). - -Before either workflow below pushes, verify that the assets branch contains media only and that the staged GIF's checksum matches the verified local artifact. - -For an existing assets branch, work in a shallow single-branch scratch clone so the publication cannot touch your working tree: - -```sh -git clone --branch --single-branch --depth 1 /tmp/assets-checkout -cp /absolute/path/to/demo.gif /tmp/assets-checkout/.gif -cd /tmp/assets-checkout -git add .gif -git commit -m "assets: gif (#)" -git push origin -``` - -For a new series, make a fresh shallow scratch clone (`git clone --depth 1 /tmp/assets-checkout`), create the orphan branch with `git switch --orphan `, then add the GIF, commit, and push the same way. - -After pushing, use authenticated GitHub API or raw requests to confirm the remote path, byte size, checksum, `200` response, and `image/gif` content type. An anonymous `404` does not disprove a private-repository asset; authenticate the verification instead. This proves the repository-member review path, not public availability. - -Immediately before editing the pull-request body, re-read the demonstrated pull request's live head and compare it with the commit recorded next to the GIF. Stop and re-record when it moved. After the edit, re-read the demonstrated live head and require it to remain at that recorded commit. Separately, render the body through GitHub's Markdown API and confirm that the expected `` is present. - -Embed the GIF in the pull request body with the raw blob URL; the `?raw=true` suffix is required, because the plain blob URL renders GitHub's file page instead of the image: - -```markdown -![](https://github.com///blob//.gif?raw=true) -``` - -Never delete or rewrite an assets branch, and never force-push it: merged pull request bodies reference its URLs forever. Append new commits only. +Earlier pull request bodies embed GIFs from orphan `*-assets` branches in this repository. Never add to, delete, rewrite, or force-push them: merged pull request bodies reference their URLs. diff --git a/.github/workflows/ci-master.yml b/.github/workflows/ci-master.yml index 5620e6af63..d69a860098 100644 --- a/.github/workflows/ci-master.yml +++ b/.github/workflows/ci-master.yml @@ -14,6 +14,7 @@ on: - larger-runner-benchmark - consolidated-runner-benchmark - ssh-helper + - wine # New master pushes and manual runs replace obsolete checks in this workflow/ref. # Standby drills share cancellation; use completed runs as readiness evidence. @@ -49,9 +50,9 @@ jobs: secrets: DEEPSEEK_API_KEY_EXTERNAL: ${{ secrets.DEEPSEEK_API_KEY_EXTERNAL }} - # Wine runs once here, independently of the native serial standby aggregates. + # Wine runs on master pushes or an explicit suite=wine dispatch, independently of native standbys. windows: - if: github.event_name == 'push' && github.ref == 'refs/heads/master' + if: (github.event_name == 'push' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && inputs.suite == 'wine') runs-on: ubuntu-latest name: windows node 24 / wine timeout-minutes: 15 diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 1574ec9e2f..c30d75af0d 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -24,18 +24,7 @@ env: jobs: pack: name: Pack npm tarballs - runs-on: >- - ${{ vars.DSH_CI_FAILOVER_LINUX == 'selfhosted' - && github.repository == 'deepseek-harness/deepseek-harness' - && github.actor != 'dependabot[bot]' - && (github.event_name == 'workflow_dispatch' - || (github.event_name == 'push' && github.ref == 'refs/heads/master') - || (github.event_name == 'pull_request' - && github.event.pull_request.head.repo.full_name == github.repository - && github.event.pull_request.head.repo.fork == false - && github.event.pull_request.user.login != 'dependabot[bot]')) - && fromJSON('["self-hosted", "linux", "x64", "vm-backup"]') - || 'ubuntu-24.04' }} + runs-on: ubuntu-24.04 steps: # Complete history: the release scripts read tags. - uses: actions/checkout@v7.0.1 diff --git a/.github/workflows/windows-package.yml b/.github/workflows/windows-package.yml index cbb4fd2642..29229605de 100644 --- a/.github/workflows/windows-package.yml +++ b/.github/workflows/windows-package.yml @@ -53,11 +53,6 @@ on: type: string default: '' required: false - build_root: - description: '独立构建根目录:填写绝对路径,每次任务创建独立源码副本;留空使用 runner 工作区' - type: string - default: '' - required: false permissions: contents: read @@ -82,7 +77,6 @@ jobs: PACKAGE_TEST_RELEASE_ID: ${{ inputs.test_release_id }} PACKAGE_SIGNING: ${{ inputs.signing }} PACKAGE_CACHE_NAMESPACE: ${{ inputs.cache_namespace }} - PACKAGE_BUILD_ROOT: ${{ inputs.build_root }} PACKAGE_WINDOWS_COMPRESSION_LEVEL: ${{ inputs.compression_level }} steps: - name: Reset packaging checkout @@ -106,7 +100,7 @@ jobs: run: | $helpers = Join-Path $env:RUNNER_TEMP "packaging-helpers-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT" New-Item -ItemType Directory -Path $helpers -ErrorAction Stop | Out-Null - foreach ($name in @('windows-packaging-priority.ps1', 'windows-build-workspace.mjs')) { + foreach ($name in @('windows-packaging-priority.ps1')) { Copy-Item -LiteralPath (Join-Path 'apps/desktop/scripts' $name) -Destination $helpers -ErrorAction Stop } "PACKAGE_CI_HELPERS=$helpers" >> $env:GITHUB_ENV @@ -140,17 +134,6 @@ jobs: - uses: actions/setup-node@v7.0.0 with: node-version: '24' - - name: Select packaging workspace - id: build_workspace - env: - PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} - run: | - if (!$env:PACKAGE_BUILD_ROOT) { - "directory=$env:GITHUB_WORKSPACE" >> $env:GITHUB_OUTPUT - } else { - node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" - exit $LASTEXITCODE - } - name: Configure persistent pnpm store # PNPM_HOME belongs to this run; keep downloaded packages outside its temporary directory. env: @@ -167,7 +150,6 @@ jobs: "DSH_DESKTOP_PACKAGE_CACHE_DIR=$env:DSH_DESKTOP_PACKAGE_CACHE_DIR" >> $env:GITHUB_ENV "PNPM_CONFIG_STORE_DIR=$storeRoot" >> $env:GITHUB_ENV - name: Install locked dependencies - working-directory: ${{ steps.build_workspace.outputs.directory }} run: | & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort node -e "const os=require('node:os'); console.log(JSON.stringify({node:process.version,availableParallelism:os.availableParallelism(),logicalCpus:os.cpus().length,totalMemoryBytes:os.totalmem(),freeMemoryBytes:os.freemem()}))" @@ -178,12 +160,10 @@ jobs: exit $LASTEXITCODE - name: Validate preset and resolve build version id: settings - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_BUILD_VERSION: ${{ inputs.build_version }} run: node apps/desktop/scripts/prepare-windows-ci.mjs - name: Check packaging configuration and toolchain - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} run: | @@ -192,23 +172,16 @@ jobs: pnpm @packageArgs exit $LASTEXITCODE - name: Build installer and verify packaged runtime - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_VERSION: ${{ steps.settings.outputs.version }} - PACKAGE_BUILD_TEMP: ${{ steps.build_workspace.outputs.temporaryDirectory }} run: | & "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort - if ($env:PACKAGE_BUILD_TEMP) { - $env:TEMP = $env:PACKAGE_BUILD_TEMP - $env:TMP = $env:PACKAGE_BUILD_TEMP - } $packageArgs = @('run', 'package:desktop:win:x64', '--build-version', $env:PACKAGE_VERSION) if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' } pnpm @packageArgs exit $LASTEXITCODE - name: Retain complete package outside the checkout id: retained - working-directory: ${{ steps.build_workspace.outputs.directory }} env: PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} PACKAGE_VERSION: ${{ steps.settings.outputs.version }} @@ -219,7 +192,7 @@ jobs: with: name: windows-package-logs-${{ github.run_id }}-${{ github.run_attempt }} include-hidden-files: true - path: ${{ steps.build_workspace.outputs.directory || github.workspace }}/apps/desktop/.desktop-build/packaging-runs/ + path: ${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/ if-no-files-found: warn retention-days: 14 - name: Retain verified unsigned installer @@ -242,8 +215,3 @@ jobs: path: ${{ steps.retained.outputs.directory }}/* if-no-files-found: error retention-days: 14 - - name: Remove isolated packaging workspace - if: success() && inputs.build_root != '' - env: - PACKAGE_SOURCE_SHA: ${{ steps.checkout.outputs.commit }} - run: node "$env:PACKAGE_CI_HELPERS/windows-build-workspace.mjs" --remove diff --git a/apps/desktop/packaging/README.i18n.yaml b/apps/desktop/packaging/README.i18n.yaml index b98c3d075f..c39bb71bc3 100644 --- a/apps/desktop/packaging/README.i18n.yaml +++ b/apps/desktop/packaging/README.i18n.yaml @@ -24,11 +24,11 @@ en: 5b4f0f80a117f202 zh: ff05be196c181087 /desktop-packaging/windows-actions-packaging: - en: 9dd2227f2878519e - zh: cd95dd6efd48298f + en: 253e17998951931c + zh: b582b377391d2ec2 /desktop-packaging/macos-self-hosted-packaging: - en: ee628e830d849ae9 - zh: 44313f5fb842f042 + en: f4cc5209bdaeefba + zh: 1db959d1ed345fcc /desktop-packaging/unsigned-windows-test-installer: en: f429bc0c280e2dfa zh: 4adbcc9e906bdf80 diff --git a/apps/desktop/packaging/README.md b/apps/desktop/packaging/README.md index 83a0e5a77b..28aa9ff9c7 100644 --- a/apps/desktop/packaging/README.md +++ b/apps/desktop/packaging/README.md @@ -115,11 +115,9 @@ Select the workflow in Actions, choose the source branch, preset, signing mode a Open the completed run in Actions and download its Artifacts. `windows-x64-signed---` and `windows-x64-unsigned---` contain the corresponding EXE; `windows-package-logs--` contains packaging diagnostics. The upload steps are `Retain verified signed installer`, `Retain verified unsigned installer`, and `Retain packaging diagnostics`; their step durations and timestamped logs show upload time. These artifacts are not a Release or download-site publication. -For path-sensitive Windows build measurements, `build_root` optionally selects an absolute directory outside existing Git checkouts. Each run clones the validated source commit into a new `windows-package--/source` directory; ignored files and previous build outputs are not copied. Only the packaging process uses a sibling run-owned `temp` directory through `TEMP` and `TMP`; Actions steps and post-job hooks retain their original temporary directories. Dependency and signing caches retain their existing locations. Successful runs remove only their owned checkout after artifact uploads, retrying transient filesystem failures up to three times with 100 ms increasing delays; persistent cleanup errors fail the Job and may leave a partially removed directory. Failed builds retain their checkout for inspection. Leave the input empty to build in the original Actions checkout. Include checkout creation and cleanup in the complete Job timing. - For cache measurements, `cache_namespace` selects a retained subdirectory for both dependency stores and upstream downloads; leave it empty for normal shared caches. Use a new name for a cold sample and repeat that name for warm samples. Names contain 1–64 lowercase letters, digits or hyphens, start with a letter or digit, and cannot be Windows device names. This does not reset the separate signature cache or OS file cache; report those states and Job start-to-completion time alongside phase timings and artifact size. Before dependency installation, the workflow records the Node version, available CPU parallelism, logical CPU count, and total/free memory. -The dependency-install and packaging steps normalize their own shell to normal CPU, I/O and memory priority before launching children. Priority and isolated-workspace helpers are copied from the exact workflow commit into a run-specific temporary directory, independently of the selected product source. Missing helpers stop CI setup; unavailable priority adjustment emits a warning and marks scheduling unsuitable for performance comparison, but does not stop packaging. This does not modify the runner task or other processes. Version, preset and retained-artifact adapters remain tied to product source and its formats. +The dependency-install and packaging steps normalize their own shell to normal CPU, I/O and memory priority before launching children. The priority helper is copied from the exact workflow commit into a run-specific temporary directory, independently of the selected product source. A missing helper stops CI setup; unavailable priority adjustment emits a warning and marks scheduling unsuitable for performance comparison, but does not stop packaging. This does not modify the runner task or other processes. Version, preset and retained-artifact adapters remain tied to product source and its formats. Installer uploads store the already-compressed release files without ZIP recompression; this preserves installer bytes and signatures. Diagnostic uploads retain their ordinary compression. @@ -129,13 +127,12 @@ Installer uploads store the already-compressed release files without ZIP recompr The [Apple Silicon workflow](../../../.github/workflows/macos-package.yml) and [Intel workflow](../../../.github/workflows/macos-intel-package.yml) produce separate arm64 and x64 packages on the Apple Silicon runner labeled `dsh-mac-package-trial`. Both share one concurrency group. The Intel workflow checks Rosetta execution before dependency installation; its selected source must include the target-aware macOS CI adapter. Both select `test` or `production` and use the existing signing, notarization and packaged-runtime checks. Successful DMG/ZIP files and diagnostic logs are retained for 14 days without publishing a release. Installer uploads disable redundant ZIP compression. The operator must verify a complete Actions run and installation on the target architecture before release qualification. The `compression_level` dropdown defaults to `3` and also offers `7`; it overrides the machine preset for this run and affects only ZIP and automatic-update downloads, not DMG. -All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing, cache measurement and isolated-workspace options follow these common fields. +All three platform forms put source, environment, update channel, version mode, manual version, test release ID and compression level first, with matching defaults. macOS notarization and Windows signing and cache measurement options follow these common fields. Run `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` to prepare private `runner/`, `packaging/{presets,secrets,certificates}` and `cache/macos-signatures` directories without overwriting existing files; append `--check` to inspect them. Fill the [preset](../config/macos-packaging/test.env.example) and [signing](../config/macos-packaging/macos-signing.env.example) templates outside the checkout. Set secret and certificate files to mode `0600`. `DSH_PACKAGING_CONFIG_DIR` selects the absolute `packaging` directory and `DSH_PACKAGING_PRESET` selects its preset; missing files fail without falling back to `.env.macos`. Signed and preparation-only Mac builds read `secrets/macos-signing.env`; relative credential paths resolve beside that file. Public presets reject signing credentials, and signing files cannot override public settings. Local unsigned Mac builds retain their configuration-free behavior. Run `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` to check the host tools and configuration files. The script selects the active Xcode and its macOS SDK together and compiles a small linker probe. After registration, omit `--check` to run in the foreground with a cleared inherited environment and prevent idle sleep while the runner is alive. Stop it with Ctrl-C before installing the service below. The runner owns its `_work` checkout, separate from daily development. The account can read its signing files, so run only trusted code. The existing notarization proxy restoration rules apply; after forced termination, inspect retained recovery records before another build. New setup templates set `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` to the absolute `cache/macos-signatures` directory outside checkout. For existing installations, rerun setup and add that field to each preset; existing files are preserved. This retains signatures across clean checkouts; cache verification and limits are described under [macOS signing](#macos-release-signing). - ZIP compression uses the same configured level with or without notarization; the App is assembled once, then DMG and ZIP are built separately so the ZIP setting does not change DMG compression. The `skip_notarization` workflow option defaults to `false`; the equivalent CLI flag is `--skip-notarization`. It retains Developer ID signing, DMG signature verification and packaged-runtime verification, but omits Apple notarization and stapling and does not require Apple notarization credentials. DMG/ZIP filenames carry `-unnotarized`, are stored under `.desktop-build/targets//unnotarized-artifacts/`, and are uploaded with an `unnotarized-debug` label. These artifacts are for internal debugging only: Gatekeeper may block downloaded copies, and they are not qualified for distribution or update publishing. No release completion record is written. The flag rejects unsigned, Windows and preparation-only builds. Install the user service from the checkout as the same account that registered the runner, without `sudo`: diff --git a/apps/desktop/packaging/README.zh.md b/apps/desktop/packaging/README.zh.md index 3868508c9e..2e87933826 100644 --- a/apps/desktop/packaging/README.zh.md +++ b/apps/desktop/packaging/README.zh.md @@ -115,11 +115,9 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s 在 Actions 打开完成的运行并下载 Artifacts。`windows-x64-signed---` 与 `windows-x64-unsigned---` 包含对应 EXE;`windows-package-logs--` 包含打包诊断。上传步骤名为 `Retain verified signed installer`、`Retain verified unsigned installer` 和 `Retain packaging diagnostics`;步骤耗时与带时间戳的日志显示上传用时。这些产物不等于发布 Release 或下载站内容。 -测量 Windows 构建路径对性能的影响时,可用 `build_root` 指定现有 Git checkout 之外的绝对目录。每轮任务将已验证的源码提交克隆到新的 `windows-package--/source` 目录;不会复制忽略文件或此前的构建输出。仅打包进程通过 `TEMP` 和 `TMP` 使用同轮所属的同级 `temp` 目录;Actions 步骤及 Job 后置钩子保留原临时目录。依赖缓存和签名缓存沿用原有位置。成功任务在产物上传后仅删除本轮所属的 checkout,临时文件系统错误最多重试三次,等待时间按 100 ms 递增;持续清理失败会使 Job 失败,并可能留下部分删除的目录。构建失败时保留 checkout 供检查。输入留空时使用原 Actions checkout。完整 Job 耗时须包含 checkout 创建和清理。 - 测量缓存时,`cache_namespace` 为两个依赖 store 和上游下载选择保留的子目录;留空使用正常共享缓存。新名称用于冷缓存采样,再次使用同名用于热缓存采样。名称由 1–64 个小写字母、数字或连字符组成,以字母或数字开头,且不能为 Windows 设备名。这不会重置独立的签名缓存或操作系统文件缓存;应将其状态、Job 开始至完成的总耗时与阶段耗时和产物体积一并报告。workflow 在依赖安装前记录 Node 版本、可用 CPU 并行数、逻辑 CPU 数及总内存和空闲内存。 -依赖安装和打包步骤在启动子进程前,将自身 shell 的 CPU、I/O 和内存优先级调整为普通值。优先级及独立构建目录辅助脚本从 workflow 的精确提交复制到本轮临时目录,与选中的产品源码分离。缺失辅助脚本会终止 CI 准备;无法调整优先级时明确告警并标记调度条件不适合性能对比,但继续打包。这不会修改 runner 任务或其他进程。版本、preset 和产物留存适配器仍跟随产品源码及其格式。 +依赖安装和打包步骤在启动子进程前,将自身 shell 的 CPU、I/O 和内存优先级调整为普通值。优先级辅助脚本从 workflow 的精确提交复制到本轮临时目录,与选中的产品源码分离。缺失辅助脚本会终止 CI 准备;无法调整优先级时明确告警并标记调度条件不适合性能对比,但继续打包。这不会修改 runner 任务或其他进程。版本、preset 和产物留存适配器仍跟随产品源码及其格式。 安装器上传直接存储已经压缩的发布文件,不再进行 ZIP 二次压缩;安装器字节和签名保持不变。诊断日志上传保留通常的压缩方式。 @@ -129,13 +127,12 @@ runner 的受监督启动和恢复见 [Windows runner 机器准备](../windows-s [Apple Silicon 工作流](../../../.github/workflows/macos-package.yml)与 [Intel 工作流](../../../.github/workflows/macos-intel-package.yml)在带有 `dsh-mac-package-trial` 标签的 Apple Silicon runner 上分别生成 arm64 和 x64 安装包,两者共用一个并发组。Intel 工作流在安装依赖前检查 Rosetta 能否执行;所选源码必须包含按目标架构校验的 macOS CI 适配脚本。两者均选择 `test` 或 `production`,并复用现有签名、公证和打包运行时检查。成功的 DMG/ZIP 与诊断日志保留 14 天,不发布 release;安装包上传关闭重复 ZIP 压缩。操作人员须验收完整 Actions 运行及目标架构上的安装,才能确认可交付。`compression_level` 下拉选项默认为 `3`,也可选择 `7`;本次运行以该选项覆盖机器预设,只影响 ZIP 和自动升级下载,不影响 DMG。 -三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量、独立构建目录选项位于公共字段之后。 +三个平台的表单均依次展示源码、环境、升级通道、版本模式、手动版本号、测试 release ID 和压缩等级,默认值一致。macOS 公证选项和 Windows 签名、缓存测量选项位于公共字段之后。 运行 `node apps/desktop/scripts/setup-macos-packaging.mjs "$HOME/dsh-ci"` 创建私有 `runner/`、`packaging/{presets,secrets,certificates}` 和 `cache/macos-signatures` 目录,不覆盖已有文件;追加 `--check` 仅检查。在 checkout 外填写 [preset](../config/macos-packaging/test.env.example) 和[签名](../config/macos-packaging/macos-signing.env.example)模板,将秘密和证书文件权限设为 `0600`。`DSH_PACKAGING_CONFIG_DIR` 指定 `packaging` 的绝对目录,`DSH_PACKAGING_PRESET` 选择其中的 preset;缺少文件立即失败,不回退到 `.env.macos`。Mac 签名和仅准备构建读取 `secrets/macos-signing.env`,相对凭据路径以该文件所在目录为基准。公开 preset 拒绝签名凭据,签名文件不能覆盖公开配置。本地未签名 Mac 构建保留无需配置的行为。 运行 `bash apps/desktop/scripts/start-macos-packaging-runner.sh "$HOME/dsh-ci/runner" "$HOME/dsh-ci/packaging" --check` 检查宿主工具和配置文件。脚本同时选择当前 Xcode 及其 macOS SDK,并编译小型链接探针。注册后省略 `--check`,清理继承环境并在前台启动 runner,存活期间阻止空闲睡眠。安装下方服务前,先用 Ctrl-C 停止。runner 拥有 `_work` 下的源码目录,与日常开发分开。该账户可读取签名文件,因此只执行可信代码。沿用现有公证代理恢复规则;强制终止后,先检查保留的恢复记录再构建。新建模板将 `DSH_DESKTOP_MACOS_SIGNATURE_CACHE_DIR` 设为 checkout 外 `cache/macos-signatures` 的绝对路径。已有部署重新运行 setup 后,在各 preset 中补上该字段;已有文件保持不变。这样可跨干净检出保留签名;缓存验证和容量限制见 [macOS 签名](#macos-release-signing)。 - 无论是否公证,ZIP 都使用同一压缩配置;App 只组装一次,再分别生成 DMG 和 ZIP,确保 ZIP 设置不改变 DMG 压缩。工作流选项 `skip_notarization` 默认为 `false`;对应 CLI 参数是 `--skip-notarization`。该模式保留 Developer ID 签名、DMG 签名验证和打包运行时验证,跳过 Apple 公证和 stapling,不要求 Apple 公证凭据。DMG/ZIP 文件名带 `-unnotarized`,存放于 `.desktop-build/targets//unnotarized-artifacts/`,上传产物标为 `unnotarized-debug`。这些产物仅供内部调试:Gatekeeper 可能阻止下载副本运行,不能视为可分发包或用于更新发布。该模式不写入发布完成记录,不能与未签名、Windows 或仅准备构建组合。 在 checkout 中,以注册 runner 的同一账户安装用户服务,不使用 `sudo`: diff --git a/apps/desktop/scripts/windows-build-workspace.d.mts b/apps/desktop/scripts/windows-build-workspace.d.mts deleted file mode 100644 index 92f3a3c704..0000000000 --- a/apps/desktop/scripts/windows-build-workspace.d.mts +++ /dev/null @@ -1,19 +0,0 @@ -/** Identity of a Windows packaging run and its independent build root. */ -export interface WindowsBuildWorkspaceOptions { - sourceDirectory: string - buildRoot: string - runId: string - runAttempt: string - sourceSha: string -} -/** - * Clone the clean selected commit into a new run-owned directory. - * @param options - Original checkout and Actions run identity. - * @returns Checkout and temporary directory owned by this run. - */ -export function prepareWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): { directory: string; temporaryDirectory: string } -/** - * Remove the directory only when its ownership record matches the run. - * @param options - Original checkout and Actions run identity. - */ -export function removeWindowsBuildWorkspace(options: WindowsBuildWorkspaceOptions): void diff --git a/apps/desktop/scripts/windows-build-workspace.mjs b/apps/desktop/scripts/windows-build-workspace.mjs deleted file mode 100644 index 977dda6618..0000000000 --- a/apps/desktop/scripts/windows-build-workspace.mjs +++ /dev/null @@ -1,96 +0,0 @@ -/** Create and remove a run-owned checkout for Windows packaging. */ -import { execFileSync } from 'node:child_process' -import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { dirname, isAbsolute, join, parse, resolve } from 'node:path' -import { pathToFileURL } from 'node:url' - -function assertUnlinkedAncestors(directory) { - for (let current = directory; ; current = dirname(current)) { - if (existsSync(current) && lstatSync(current).isSymbolicLink()) { - throw new Error('Packaging workspace ancestors must not be links') - } - if (dirname(current) === current) break - } -} - -function locations(options) { - const { buildRoot, runId, runAttempt, sourceSha } = options - if (!buildRoot || !isAbsolute(buildRoot) || /[\r\n\0]/.test(buildRoot)) { - throw new Error('Packaging build root must be a nonempty absolute directory') - } - const root = resolve(buildRoot) - if (root === parse(root).root) throw new Error('Packaging build root must not be a volume root') - if (!/^[1-9]\d*$/.test(runId) || !/^[1-9]\d*$/.test(runAttempt) || !/^[a-f0-9]{40}$/.test(sourceSha)) { - throw new Error('Packaging workspace requires a run identity and exact commit') - } - assertUnlinkedAncestors(root) - for (let current = root; ; current = dirname(current)) { - if (existsSync(join(current, '.git'))) throw new Error('Packaging build root must be outside existing Git checkouts') - if (dirname(current) === current) break - } - const owner = join(root, `windows-package-${runId}-${runAttempt}`) - assertUnlinkedAncestors(owner) - return { root, owner, directory: join(owner, 'source'), temporaryDirectory: join(owner, 'temp') } -} - -function git(directory, args) { - return execFileSync('git', args, { cwd: directory, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim() -} - -function ownership(options, paths) { - return JSON.stringify({ version: 1, root: paths.root, source: resolve(options.sourceDirectory), runId: options.runId, runAttempt: options.runAttempt, sourceSha: options.sourceSha }) -} - -/** - * Clone the validated commit into a new run-owned checkout; failures retain diagnostics. - * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Source and run identity. - * @returns {{directory: string, temporaryDirectory: string}} Checkout and temporary directory owned by this run. - */ -export function prepareWindowsBuildWorkspace(options) { - const paths = locations(options) - if (git(options.sourceDirectory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(options.sourceDirectory, ['status', '--porcelain'])) { - throw new Error('Packaging source must be clean and match the selected commit') - } - mkdirSync(paths.root, { recursive: true }) - mkdirSync(paths.owner) - writeFileSync(join(paths.owner, 'owner.json'), ownership(options, paths), { flag: 'wx' }) - mkdirSync(paths.temporaryDirectory) - git(paths.owner, ['clone', '--no-hardlinks', '--no-checkout', resolve(options.sourceDirectory), paths.directory]) - git(paths.directory, ['checkout', '--detach', options.sourceSha]) - if (git(paths.directory, ['rev-parse', 'HEAD']) !== options.sourceSha || git(paths.directory, ['status', '--porcelain'])) { - throw new Error('Isolated packaging checkout does not match the selected commit') - } - return { directory: paths.directory, temporaryDirectory: paths.temporaryDirectory } -} - -/** - * Remove only the matching run-owned directory after successful artifact upload. - * Transient filesystem failures retry up to three times; persistent failures propagate. - * @param {{sourceDirectory: string, buildRoot: string, runId: string, runAttempt: string, sourceSha: string}} options - Original source and run identity. - * @returns {void} - */ -export function removeWindowsBuildWorkspace(options) { - const paths = locations(options) - const marker = join(paths.owner, 'owner.json') - const stat = lstatSync(marker) - if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 8192 || readFileSync(marker, 'utf8') !== ownership(options, paths)) { - throw new Error('Packaging workspace ownership does not match this run') - } - rmSync(paths.owner, { recursive: true, maxRetries: 3, retryDelay: 100 }) -} - -if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { - const options = { - sourceDirectory: process.env.GITHUB_WORKSPACE ?? '', - buildRoot: process.env.PACKAGE_BUILD_ROOT ?? '', - runId: process.env.GITHUB_RUN_ID ?? '', - runAttempt: process.env.GITHUB_RUN_ATTEMPT ?? '', - sourceSha: process.env.PACKAGE_SOURCE_SHA ?? '', - } - if (process.argv[2] === '--remove') removeWindowsBuildWorkspace(options) - else { - if (process.argv.length !== 2 || !process.env.GITHUB_OUTPUT) throw new Error('Expected Actions output file and no arguments') - const result = prepareWindowsBuildWorkspace(options) - appendFileSync(process.env.GITHUB_OUTPUT, `directory=${result.directory}\ntemporaryDirectory=${result.temporaryDirectory}\n`) - } -} diff --git a/apps/web/tests/caption-overlays.e2e.ts b/apps/web/tests/caption-overlays.e2e.ts index 2a86277843..d336b64950 100644 --- a/apps/web/tests/caption-overlays.e2e.ts +++ b/apps/web/tests/caption-overlays.e2e.ts @@ -21,8 +21,9 @@ it('keeps settings and expanded plugin dialogs clear of the Windows caption acro document.documentElement.setAttribute('data-windows-titlebar', '') document.documentElement.style.setProperty('--dsh-windows-titlebar-height', '40px') }) - const reopenSidebar = page.getByRole('button', { name: '打开侧边栏', exact: true }) - if (await reopenSidebar.isVisible()) await reopenSidebar.click() + await page.setViewportSize({ width: 521, height: 600 }) + await page.locator('[data-sidebar-drawer]').waitFor({ state: 'detached' }) + const reopenSidebar = page.locator('[data-shell-leading]').getByRole('button', { name: '打开侧边栏', exact: true }) await openSettings(page, 'zh') const settings = page.getByRole('dialog', { name: '设置', exact: true }) const settingsMask = settings.locator('..').locator(':scope > [aria-hidden="true"]') @@ -51,7 +52,7 @@ it('keeps settings and expanded plugin dialogs clear of the Windows caption acro await menu.waitFor({ state: 'hidden' }) expect(await settings.isVisible()).toBe(true) await settings.getByRole('button', { name: '关闭', exact: true }).click() - if (await reopenSidebar.isVisible()) await reopenSidebar.click() + if (await page.locator('[data-sidebar-drawer][data-sidebar-collapsed]').count() > 0) await reopenSidebar.click() await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() await page.locator('[data-plugin-panel]').getByRole('button', { name: '添加插件', exact: true }).click() const plugin = page.getByRole('dialog', { name: '添加插件', exact: true }) @@ -88,7 +89,9 @@ it('keeps settings and expanded plugin dialogs clear of the Windows caption acro if (value === 'darwin') document.documentElement.setAttribute('data-platform', value) else document.documentElement.removeAttribute('data-platform') }, platform) - if (await reopenSidebar.isVisible()) await reopenSidebar.click() + // Publish the synthetic platform change through the frame's size observer. + await page.setViewportSize({ width: platform === 'darwin' ? 520 : 521, height: 600 }) + await page.locator('[data-sidebar-drawer]').waitFor() await openSettings(page, 'zh') await expect.poll(async () => (await settings.boundingBox())?.y).toBe(platform === 'darwin' ? 68 : 0) expect((await settingsMask.boundingBox())?.y).toBe(0) diff --git a/apps/web/tests/chat-scroll-contract.e2e.ts b/apps/web/tests/chat-scroll-contract.e2e.ts index 6092eddc02..fd5f778c1e 100644 --- a/apps/web/tests/chat-scroll-contract.e2e.ts +++ b/apps/web/tests/chat-scroll-contract.e2e.ts @@ -309,6 +309,9 @@ async function loadedFlowRows(page: Page): Promise { } async function openSeed(page: Page, fixture: ChatScrollFixture, tailMarker?: string): Promise { + if (await page.locator('[data-sidebar-drawer][data-sidebar-collapsed]').count() > 0) { + await page.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() + } // Search collapsed into a header action; expand it before filling. const searchButton = page.getByRole('button', { name: 'Search sessions' }) if (await searchButton.getAttribute('aria-expanded') !== 'true') await searchButton.click() @@ -1700,9 +1703,6 @@ describe('web e2e: long Chat scroll contract', () => { await world.page.getByRole('tab', { name: 'Trajectory', exact: true }).click() await world.page.getByLabel('Trajectory timeline').waitFor({ timeout: 30_000 }) await world.page.setViewportSize({ width: 700, height: 900 }) - // The narrow breakpoint auto-collapses the sidebar. Re-open it because - // this scenario switches sessions while pinning the narrow Chat scroll owner. - await world.page.getByRole('button', { name: 'Open sidebar', exact: true }).click() await world.page.getByRole('tab', { name: 'Chat', exact: true }).click() await nextPaint(world.page) await expectSameFlowTop(world.page, sessionAnchor, RESPONSIVE_REFLOW_TOLERANCE) diff --git a/apps/web/tests/client-plugin-live.e2e.ts b/apps/web/tests/client-plugin-live.e2e.ts index 21ad5a1182..ecd46f5f5c 100644 --- a/apps/web/tests/client-plugin-live.e2e.ts +++ b/apps/web/tests/client-plugin-live.e2e.ts @@ -113,7 +113,7 @@ it('places dynamic Session menu rows by order among the shipped ones and removes await page.mouse.move(0, 0) await observe('blur', true, false) await page.setViewportSize({ width: 390, height: 844 }) - await page.getByRole('button', { name: 'Open sidebar', exact: true }).first().click() + await page.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() await page.mouse.move(0, 0) await observe('narrow', true, false) const bounds = await row.evaluate((element) => { @@ -133,7 +133,7 @@ it('places dynamic Session menu rows by order among the shipped ones and removes try { const touchConsole = watchConsole(touchPage) await touchPage.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) - await touchPage.getByRole('button', { name: 'Open sidebar', exact: true }).first().click() + await touchPage.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() const touchRow = touchPage.getByRole('treeitem').filter({ has: touchPage.getByText(SESSION_TITLE, { exact: true }) }) const touchTrigger = touchRow.getByRole('button', { name: `Session actions for ${SESSION_TITLE}` }) await touchTrigger.waitFor() diff --git a/apps/web/tests/details-session-lifecycle.e2e.ts b/apps/web/tests/details-session-lifecycle.e2e.ts index 68dd75f3d8..84a34241f8 100644 --- a/apps/web/tests/details-session-lifecycle.e2e.ts +++ b/apps/web/tests/details-session-lifecycle.e2e.ts @@ -188,7 +188,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await blankColumn.locator('[data-sidebar-right-toggle]').click() await blankColumn.locator('[data-dockkit-pane]').first().waitFor({ state: 'hidden' }) await page.setViewportSize({ width: 767, height: blankViewport.height }) - await expect.poll(() => columns(page)).toEqual([56, 711, 0]) + await expect.poll(() => columns(page)).toEqual([0, 767, 0]) await page.locator('[data-sidebar-right-expand]').click() // The fullscreen shell keeps its viewport box while its docked content closes. await expect.poll(() => blankColumn.locator('[data-sidebar-right-open]').count()).toBe(1) @@ -425,7 +425,7 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S await expect.poll(() => columns(page)).toEqual([420, viewport.width - 420 - normalWidth, normalWidth]) await page.setViewportSize({ width: 767, height: viewport.height }) await expect.poll(() => panel.boundingBox()).toEqual({ x: 0, y: 0, width: 767, height: viewport.height }) - await expect.poll(() => columns(page)).toEqual([56, 711, 0]) + await expect.poll(() => columns(page)).toEqual([0, 767, 0]) expect(await sidebarSnapshot(page)).toMatchObject({ mode: 'fullscreen', resizeHandleWidth: 0, coversViewport: true }) await checkpoint('A automatic fullscreen at 767px') await column.locator('[data-sidebar-right-mode="push"]').click() diff --git a/apps/web/tests/expected/forge-panel/branch-details.expected.md b/apps/web/tests/expected/forge-panel/branch-details.expected.md new file mode 100644 index 0000000000..8c348d423a --- /dev/null +++ b/apps/web/tests/expected/forge-panel/branch-details.expected.md @@ -0,0 +1 @@ +- 'tooltip "Current branch: feature/a-long-current-branch-name-for-mobile-review"' 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 f8c94d3817..b6c825a833 100644 --- a/apps/web/tests/expected/forge-panel/changes-view.expected.md +++ b/apps/web/tests/expected/forge-panel/changes-view.expected.md @@ -1,5 +1,6 @@ - img "变更请求状态:需要处理" - text: "Add the pull request panel #7" +- button "提交评审" - button "在浏览器中打开" - button "全部 2 个文件" - text: +4 −2 @@ -7,16 +8,64 @@ - button "全部折叠" - button "左右对比" [pressed] - button "自动换行" [pressed] -- button "收起 panel.ts" [expanded] -- 'button "复制路径: src/panel.ts"': src/panel.ts -- text: +2 −2 -- button "panel.ts 的更多操作" -- text: 1 export const n1 = 1 1 export const n1 = 1 2 export const n2 = 2 2 export const n2 = 'two' 3 export const n3 = 3 3 export const n3 = 3 4 export const n4 = 4 4 export const n4 = 4 5 export const n5 = 5 5 export const n5 = 5 -- button "6 行未变更" -- text: 12 export const n12 = 12 12 export const n12 = 12 13 export const n13 = 13 13 export const n13 = 13 14 export const n14 = 14 14 export const n14 = 14 15 export const n15 = 15 15 export const n15 = 'fifteen' 16 export const n16 = 16 16 export const n16 = 16 17 export const n17 = 17 17 export const n17 = 17 18 export const n18 = 18 18 export const n18 = 18 -- button "其余未变更的行" -- button "收起 panel.md" [expanded] -- 'button "复制路径: docs/panel.md"': docs/panel.md -- text: 新文件 +2 −0 -- button "panel.md 的更多操作" -- text: "1 + # Panel 2 + Shows the change requests of a Session." +- region "全部 2 个文件": + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. 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 new file mode 100644 index 0000000000..b1c29e9f64 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/file-tree-toggle.expected.md @@ -0,0 +1,77 @@ +- img "变更请求状态:需要处理" +- text: "Add the pull request panel #7" +- button "提交评审" +- button "在浏览器中打开" +- button "全部 2 个文件" +- text: +4 −2 +- button "刷新变更" +- button "全部折叠" +- button "左右对比" [pressed] +- button "自动换行" [pressed] +- button "文件树" [expanded] [pressed] +- region "全部 2 个文件": + - button "收起 panel.ts" [expanded] + - text: src/panel.ts +2 −2 + - button "panel.ts 的更多操作" + - button "选择第 L1 行": "1" + - text: export const n1 = 1 + - button "选择第 R1 行": "1" + - text: export const n1 = 1 + - button "选择第 L2 行": "2" + - text: export const n2 = 2 + - button "选择第 R2 行": "2" + - text: export const n2 = 'two' + - button "选择第 L3 行": "3" + - text: export const n3 = 3 + - button "选择第 R3 行": "3" + - text: export const n3 = 3 + - button "选择第 L4 行": "4" + - text: export const n4 = 4 + - button "选择第 R4 行": "4" + - text: export const n4 = 4 + - button "选择第 L5 行": "5" + - text: export const n5 = 5 + - button "选择第 R5 行": "5" + - text: export const n5 = 5 + - button "6 行未变更" + - button "选择第 L12 行": "12" + - text: export const n12 = 12 + - button "选择第 R12 行": "12" + - text: export const n12 = 12 + - button "选择第 L13 行": "13" + - text: export const n13 = 13 + - button "选择第 R13 行": "13" + - text: export const n13 = 13 + - button "选择第 L14 行": "14" + - text: export const n14 = 14 + - button "选择第 R14 行": "14" + - text: export const n14 = 14 + - button "选择第 L15 行": "15" + - text: export const n15 = 15 + - button "选择第 R15 行": "15" + - text: export const n15 = 'fifteen' + - button "选择第 L16 行": "16" + - text: export const n16 = 16 + - button "选择第 R16 行": "16" + - text: export const n16 = 16 + - button "选择第 L17 行": "17" + - text: export const n17 = 17 + - button "选择第 R17 行": "17" + - text: export const n17 = 17 + - button "选择第 L18 行": "18" + - text: export const n18 = 18 + - button "选择第 R18 行": "18" + - text: export const n18 = 18 + - button "其余未变更的行" + - button "收起 panel.md" [expanded] + - text: docs/panel.md 新文件 +2 −0 + - button "panel.md 的更多操作" + - button "选择第 R1 行": "1" + - text: "+ # Panel" + - button "选择第 R2 行": "2" + - text: + Shows the change requests of a Session. +- separator "调整文件树宽度" +- navigation "全部 2 个文件": + - textbox "筛选文件…": src + - button "src" [expanded] + - button "src/panel.ts": panel.ts +2 −2 diff --git a/apps/web/tests/expected/forge-panel/local-card.expected.md b/apps/web/tests/expected/forge-panel/local-card.expected.md new file mode 100644 index 0000000000..24058934d3 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/local-card.expected.md @@ -0,0 +1,4 @@ +- button "Local changes" +- text: HEAD → origin/main +- 'button "View the changes of this Session: 60 files, 60 lines added, 0 lines deleted"': +60 −0 60 files +- button "Create change request" diff --git a/apps/web/tests/expected/forge-panel/review-composer.expected.md b/apps/web/tests/expected/forge-panel/review-composer.expected.md new file mode 100644 index 0000000000..d2c1d4682d --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-composer.expected.md @@ -0,0 +1,7 @@ +- region "评论 R2–4": + - text: 评论 R2–4 + - textbox "留下评论…": 请核对边界条件 + - button "取消" + - button "添加到输入框" + - button "开始评审" + - button "GitHub 评论选项" diff --git a/apps/web/tests/expected/forge-panel/review-message.expected.md b/apps/web/tests/expected/forge-panel/review-message.expected.md new file mode 100644 index 0000000000..c454458d69 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-message.expected.md @@ -0,0 +1,25 @@ +> ## User Comment 2 +> File: src/extra.ts +> Side: R +> Lines: 1 +> Source: Local (branch) +> Diff hunk: +> ```diff +> @@ -0,0 +1,1 @@ +> +export const extra = 1 +> ``` +> Comment: +> 请检查这项修改 + +> ## User Comment 1 +> File: src/app.ts +> Side: R +> Lines: 1 +> Source: Local (branch) +> Diff hunk: +> ```diff +> @@ -0,0 +1,1 @@ +> +export const app = 1 +> ``` +> Comment: +> 请解释这行代码 diff --git a/apps/web/tests/expected/forge-panel/review-quotes.expected.md b/apps/web/tests/expected/forge-panel/review-quotes.expected.md new file mode 100644 index 0000000000..602d647831 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-quotes.expected.md @@ -0,0 +1,6 @@ +- textbox "发消息或创建任务, / 调用指令, @ 文件或对话": + - paragraph: + - button "移除引用" + - text: "## User Comment 2 File: src/extra.ts Side: R Lines: 1 Source: Local (branch) Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const extra = 1 ``` Comment: 请检查这项修改" + - button "移除引用" + - text: "## User Comment 1 File: src/app.ts Side: R Lines: 1 Source: Local (branch) Diff hunk: ```diff @@ -0,0 +1,1 @@ +export const app = 1 ``` Comment: 请解释这行代码" diff --git a/apps/web/tests/expected/forge-panel/review-record.expected.md b/apps/web/tests/expected/forge-panel/review-record.expected.md new file mode 100644 index 0000000000..3e678d6071 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/review-record.expected.md @@ -0,0 +1,4 @@ +- region "评论 R2–4": + - text: 你的评论 R2–4 已发布到 GitHub 请核对边界条件 + - button "添加到输入框" + - button "在 GitHub 查看" diff --git a/apps/web/tests/expected/forge-panel/submit-review.expected.md b/apps/web/tests/expected/forge-panel/submit-review.expected.md new file mode 100644 index 0000000000..c06de70320 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/submit-review.expected.md @@ -0,0 +1,13 @@ +- dialog "提交评审": + - heading "提交评审" [level=2] + - button "关闭" + - text: 待提交评论(1) + - textbox "评审总结…": 需要补充边界检查 + - radio "评论" + - text: 评论 + - radio "批准" + - text: 批准 + - radio "请求更改" [checked] + - text: 请求更改 + - button "取消" + - button "提交评审" diff --git a/apps/web/tests/expected/forge-panel/worktree-option.expected.md b/apps/web/tests/expected/forge-panel/worktree-option.expected.md new file mode 100644 index 0000000000..c9a85b8723 --- /dev/null +++ b/apps/web/tests/expected/forge-panel/worktree-option.expected.md @@ -0,0 +1,3 @@ +- button "当前分支:main": main +- checkbox "新建工作树" +- text: 新建工作树 diff --git a/apps/web/tests/expected/layout-bottom/geometry.expected.md b/apps/web/tests/expected/layout-bottom/geometry.expected.md index 39188ce561..8e53379673 100644 --- a/apps/web/tests/expected/layout-bottom/geometry.expected.md +++ b/apps/web/tests/expected/layout-bottom/geometry.expected.md @@ -4,6 +4,6 @@ grown: {"bottom":{"top":440,"height":360,"bottom":800},"main":{"top":0,"height": darwin: {"bottom":{"top":440,"height":360,"bottom":800},"main":{"top":0,"height":440,"bottom":440},"sidebar":{"top":0,"height":440,"bottom":440},"rightbar":{"top":0,"height":440,"bottom":440},"overlay":{"top":0,"height":800,"bottom":800},"handles":[{"top":0,"height":440,"bottom":440}],"pageHeight":800} windows: {"bottom":{"top":440,"height":360,"bottom":800},"main":{"top":40,"height":400,"bottom":440},"sidebar":{"top":40,"height":400,"bottom":440},"rightbar":{"top":40,"height":400,"bottom":440},"overlay":{"top":0,"height":800,"bottom":800},"handles":[{"top":40,"height":400,"bottom":440}],"pageHeight":800} browser: {"bottom":{"top":440,"height":360,"bottom":800},"main":{"top":0,"height":440,"bottom":440},"sidebar":{"top":0,"height":440,"bottom":440},"rightbar":{"top":0,"height":440,"bottom":440},"overlay":{"top":0,"height":800,"bottom":800},"handles":[{"top":0,"height":440,"bottom":440}],"pageHeight":800} -narrow: {"bottom":{"top":240,"height":360,"bottom":600},"main":{"top":0,"height":240,"bottom":240},"sidebar":{"top":0,"height":240,"bottom":240},"rightbar":{"top":0,"height":240,"bottom":240},"overlay":{"top":0,"height":600,"bottom":600},"handles":[],"pageHeight":600} +narrow: {"bottom":{"top":240,"height":360,"bottom":600},"main":{"top":0,"height":240,"bottom":240},"sidebar":{"top":0,"height":600,"bottom":600},"rightbar":{"top":0,"height":240,"bottom":240},"overlay":{"top":0,"height":600,"bottom":600},"handles":[],"pageHeight":600} unregistered: {"bottom":{"top":600,"height":0,"bottom":600},"main":{"top":0,"height":600,"bottom":600},"sidebar":{"top":0,"height":600,"bottom":600},"rightbar":{"top":0,"height":600,"bottom":600},"overlay":{"top":0,"height":600,"bottom":600},"handles":[],"pageHeight":600} collapsed: {"bottom":{"top":600,"height":0,"bottom":600},"main":{"top":0,"height":600,"bottom":600},"sidebar":{"top":0,"height":600,"bottom":600},"rightbar":{"top":0,"height":600,"bottom":600},"overlay":{"top":0,"height":600,"bottom":600},"handles":[],"pageHeight":600} diff --git a/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md b/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md index e1561e6f7c..6deb4441c6 100644 --- a/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md +++ b/apps/web/tests/expected/plugin-manager/header-natural-motion.expected.md @@ -6,4 +6,5 @@ - Tabs / 1280px: resting title 28, actions 28, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. - Tabs / 600px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. - Tabs / 470px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. -- Tabs / 390px: resting title 28, actions 146, tabs 96; pinned actions 66, tabs 16, bar 114; stable range, reversible coordinates, same controls. +- Tabs / 390px: resting title 28, actions 97, tabs 96; pinned actions 17, tabs 16, bar 66; stable range, reversible coordinates, same controls. +- Tabs / 334px: resting title 28, actions 146, tabs 96; pinned actions 66, tabs 16, bar 114; stable range, reversible coordinates, same controls. diff --git a/apps/web/tests/expected/schedule-header.expected.md b/apps/web/tests/expected/schedule-header.expected.md index 96bff76bee..eb305c44f7 100644 --- a/apps/web/tests/expected/schedule-header.expected.md +++ b/apps/web/tests/expected/schedule-header.expected.md @@ -7,7 +7,7 @@ en 440px: title and New single-line, New beside the title; contained; New retain en 390px: title and New single-line, New beside the title; contained; New retains focus en 430px: title and New single-line, New beside the title; contained; New retains focus en 1024px: title and New single-line, New beside the title; contained; New retains focus -en 509px with sidebar expanded: title single-line; New moves below the title +en 220px page column: title single-line; New moves below the title zh 1680px: title and New single-line, New beside the title; contained; New retains focus zh 800px: title and New single-line, New beside the title; contained; New retains focus zh 520px: title and New single-line, New beside the title; contained; New retains focus diff --git a/apps/web/tests/expected/sidebar-drawer.expected.md b/apps/web/tests/expected/sidebar-drawer.expected.md new file mode 100644 index 0000000000..466c2d6ccf --- /dev/null +++ b/apps/web/tests/expected/sidebar-drawer.expected.md @@ -0,0 +1,22 @@ +390px: closed sidebar has no rail; main width 390px +open: main geometry retained; background inert; no resize handle +close: Session navigation, Plugins navigation, mask and Escape +retained: sidebar DOM and opener focus +768px: 56px rail; main width 712px; drawer focus transfers to the rail toggle +breakpoint motion: collapsed rail hides immediately and returns compact without crossfades; expanded sidebar and explicit toggles retain their slides +767px: hidden drawer; main width 767px; no page overflow +global panels: browser top inset 48px; macOS keeps its existing clearance +tooltips: sidebar and workspace controls escape the drawer and fit the viewport +search input: 16px on touch; 13px with a fine pointer +simulated keyboard: homepage and drawer retain 844px layout height without following the 360px visual viewport; Settings stays within the viewport +keyboard close: layout height stays 844px; sidebar search retained; Settings close remains reachable +shell coverage: drawer backing and mask cover 844px without synthetic safe-area insets +rotation: 844x390 then 390x844 restores shell height and sidebar breakpoint +folded landscape: 951px frame splits at 475.5px without a resize handle; unfolding restores 280px and search focus; portrait retains the drawer +fold transitions: sidebar controls follow the divider in both directions; reduced motion changes width without animation +drawer mask: opacity transitions from 0 to 1 on open and 1 to 0 on close +reduced motion: drawer and mask settle without transitions +touch selected Session: More remains visible; archive and pin stay in its menu; pin marker retained +touch Workspace: actions appear only while expanded, including after folding the focused row +fine pointer: folded Workspace actions remain available on hover +fine pointer: selected Session actions stay hidden until hover, including at 390px diff --git a/apps/web/tests/expected/sidebar-menu-dismissal.expected.md b/apps/web/tests/expected/sidebar-menu-dismissal.expected.md new file mode 100644 index 0000000000..585e3877cd --- /dev/null +++ b/apps/web/tests/expected/sidebar-menu-dismissal.expected.md @@ -0,0 +1,2 @@ +View options and Session menus close when the sidebar becomes an inert drawer. +Focus returns to the visible sidebar opener; retained Session rows keep their DOM identity. diff --git a/apps/web/tests/forge-panel.e2e.ts b/apps/web/tests/forge-panel.e2e.ts index 3422f1c8d7..10e99da527 100644 --- a/apps/web/tests/forge-panel.e2e.ts +++ b/apps/web/tests/forge-panel.e2e.ts @@ -77,13 +77,23 @@ if (args[0] === 'api' && args[5] === 'repos/octo/demo/pulls/9/merge') { process.stdout.write(JSON.stringify({ sha: 'c'.repeat(40), merged: true, message: 'Pull Request successfully merged' })) process.exit(0) } +if (args[0] === 'api' && args[3] === 'repos/octo/demo/pulls/7') { + process.stdout.write(JSON.stringify({ head: { sha: 'a'.repeat(40) }, state: 'open' })) + process.exit(0) +} +if (args[0] === 'api' && args[4] === 'POST' && ['repos/octo/demo/pulls/7/comments', 'repos/octo/demo/pulls/7/reviews'].includes(args[5])) { + const body = JSON.parse(readFileSync(0, 'utf8')) + appendFileSync(join(here, 'reviews.jsonl'), JSON.stringify({ endpoint: args[5], body }) + '\\n') + process.stdout.write(JSON.stringify({ html_url: 'https://github.com/octo/demo/pull/7#pullrequestreview-1' })) + process.exit(0) +} if (args[0] === 'pr' && args[1] === 'diff') { const refused = join(here, 'pr-' + args[2] + '.refused') if (existsSync(refused)) { process.stderr.write(readFileSync(refused, 'utf8')) process.exit(1) } - process.stdout.write(readFileSync(join(here, 'pr-' + args[2] + '.diff'), 'utf8')) + 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.raw+json') { @@ -207,9 +217,12 @@ interface PanelLaunch { * Launch the bundle against a GitHub checkout of `main` and `release` and open the New Session screen of that workspace. * @param failureShot - name of the screenshot saved when the test fails. * @param scenario - normal conversation, a restoration follow-up, or a numbered PR lookup. + * @param options - desktop transport, initial checkout branch, and touch input for the browser. * @returns the scaffold, page, and checkout. */ -async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal', desktop?: 'darwin' | 'win32'): Promise { +async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' | 'reference' = 'normal', + options: { desktop?: 'darwin' | 'win32'; branch?: string; hasTouch?: boolean } = {}): Promise { + const { desktop } = options const resources: { scaffold?: WebScaffold; browser?: Browser } = {} const root = await mkdtemp(join(tmpdir(), 'dsh-forge-panel-')) onTestFinished(async () => { @@ -265,6 +278,7 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' await git(project, 'remote', 'add', 'origin', 'https://github.com/octo/demo.git') await git(project, 'branch', 'release') await git(project, 'commit', '--quiet', '--allow-empty', '-m', 'main only') + if (options.branch !== undefined) await git(project, 'checkout', '--quiet', '-b', options.branch) if (scenario === 'reference') { // The model's confined command must own the CLI double's writable call log. const modelBin = join(project, '.fixture-bin') @@ -275,7 +289,8 @@ async function launchPanel(failureShot: string, scenario: 'normal' | 'follow-up' const browser = await chromium.launch() resources.browser = browser - const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE, timezoneId: 'Asia/Shanghai' }) + const page = await browser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE, timezoneId: 'Asia/Shanghai', + hasTouch: options.hasTouch ?? false }) if (desktop !== undefined) { // Only Electron's keyboard transport is substituted; the product registry and menus remain real. await page.addInitScript(({ device, config }) => { @@ -328,7 +343,7 @@ async function requestReleaseWorktree(failureShot: string, followUp = false): Pr const { page } = launched const option = page.locator('[data-forge-worktree]') await option.waitFor({ timeout: 20_000 }) - await option.getByRole('checkbox', { name: '工作树', exact: true }).check() + await option.getByRole('checkbox', { name: '新建工作树', exact: true }).check() await option.getByRole('button', { name: '基于 main', exact: true }).click() await page.getByRole('menuitem', { name: 'release', exact: true }).click() await option.getByRole('button', { name: '基于 release', exact: true }).waitFor() @@ -427,6 +442,11 @@ it.skipIf(MODE === 'record')('starts a Session in a worktree before its first me const row = page.locator(`[data-row-key="session:${sessionId}"]`) await row.getByRole('img', { name: '在自己的工作树中', exact: true }).waitFor({ timeout: 20_000 }) await row.getByRole('img', { name: '变更请求状态:需要处理 · 检查失败', exact: true }).waitFor({ timeout: 20_000 }) + // A fresh page cannot retain the previous browser source's status values. + await page.goto('about:blank') + await expect.poll(() => scaffold.ctx.storageDomain.get('forge_panel_change_requests')).toBeUndefined() + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await row.getByRole('img', { name: '变更请求状态:需要处理 · 检查失败', exact: true }).waitFor({ timeout: 20_000 }) await row.hover() const rowHover = page.locator('[data-forge-session-hover]') await rowHover.getByText('#7 Add the pull request panel', { exact: true }).waitFor({ timeout: 20_000 }) @@ -590,7 +610,7 @@ it.skipIf(MODE === 'record')('marks a draft change request ready for review and }) it.skipIf(MODE === 'record')('shows the local changes of the Session by scope and the changes of its change requests, expanding unchanged lines', async () => { - const { scaffold, page, root, project, tripwire } = await launchPanel('web-e2e-forge-panel-changes') + const { scaffold, page, root, project, tripwire } = await launchPanel('web-e2e-forge-panel-changes', 'follow-up') // origin/main stops at the twelve-line README; the branch adds a commit, a staged file, an edit, and an untracked file. await writeFile(join(project, 'README.md'), Array.from({ length: 12 }, (_, index) => `line ${index + 1}\n`).join('')) await git(project, 'commit', '--quiet', '-am', 'readme') @@ -626,13 +646,46 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await local.locator('[data-forge-diff-file="notes.md"]').getByText('新文件 · 未提交', { exact: true }).waitFor() const readme = local.locator('[data-forge-diff-file="README.md"]') await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) - await readme.getByRole('button', { name: '复制路径: README.md', exact: true }).click() - await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('README.md') await page.evaluate(() => navigator.clipboard.writeText('unchanged')) + await readme.locator('[data-forge-file-label]').click() + await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('unchanged') await readme.locator('[data-forge-path-spacer]').click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('unchanged') await readme.getByRole('button', { name: '6 行未变更', exact: true }).click() await readme.getByText('line 1', { exact: true }).first().waitFor({ timeout: 20_000 }) + await local.getByRole('button', { name: '全部 4 个文件', exact: true }).click() + const tree = page.getByRole('menu') + await tree.getByRole('textbox', { name: '筛选文件…' }).fill('extra') + await tree.getByRole('menuitem', { name: 'src/extra.ts', exact: true }).click() + for (const [path, comment] of [['src/app.ts', '请解释这行代码'], ['src/extra.ts', '请检查这项修改']] as const) { + const section = local.locator(`[data-forge-diff-file="${path}"]`) + const lineNumber = section.getByRole('button', { name: '选择第 R1 行', exact: true }) + await lineNumber.hover() + expect(await lineNumber.evaluate(element => getComputedStyle(element).backgroundColor)).toBe('rgba(0, 0, 0, 0)') + const content = await section.locator('[data-review-code]').first().boundingBox() + const fileBox = await section.boundingBox() + if (content === null || fileBox === null) throw new Error('Added file must be visible') + expect(content.x - fileBox.x).toBeLessThan(70) + await lineNumber.click() + expect(await section.getByRole('textbox', { name: '留下评论…' }).count()).toBe(0) + await section.getByRole('button', { name: '添加评论', exact: true }).click() + await section.getByRole('textbox', { name: '留下评论…' }).fill(comment) + await section.locator('[data-forge-comment]').getByRole('button', { name: '添加到输入框', exact: true }).click() + await section.locator('[data-forge-review-thread="agent"]').getByText(comment, { exact: true }).waitFor() + } + await compareOrRefreshGolden(join(EXPECTED, 'review-quotes.expected.md'), + await captureStableAria(page, '[data-composer-input]', scaffold.workspaceCwd), MODE) + expect((await readPersistedEvents(scaffold, sessionId)).some(event => event.type === 'user/message' + && event.data.content.some(block => block.type === 'text' && block.text.includes('## User Comment')))).toBe(false) + const reviewed = scaffold.whenTurnSettled() + await page.locator('[data-composer-input]').first().press('Enter') + await reviewed + await page.getByText(FOLLOW_UP_REPLY, { exact: true }).waitFor() + const comments = (await readPersistedEvents(scaffold, sessionId)).flatMap(event => event.type === 'user/message' + ? event.data.content.flatMap(block => block.type === 'text' && block.text.includes('## User Comment') ? [block.text] : []) : []) + expect(comments).toHaveLength(1) + await compareOrRefreshGolden(join(EXPECTED, 'review-message.expected.md'), comments.join('').trimEnd(), MODE) + await local.getByRole('button', { name: '分支', exact: true }).click() await page.getByRole('menuitem', { name: '已暂存', exact: true }).click() await local.getByText('暂存区与 HEAD 比较', { exact: true }).waitFor() @@ -648,20 +701,139 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() const view = page.locator('[data-forge-changes="change"]') const panelFile = view.locator('[data-forge-diff-file="src/panel.ts"]') + const title = await view.getByText('Add the pull request panel', { exact: true }).boundingBox() + const submit = await view.getByRole('button', { name: '提交评审', exact: true }).boundingBox() + if (title === null || submit === null) throw new Error('PR title and submit action must be visible') + expect(Math.abs(title.y + title.height / 2 - submit.y - submit.height / 2)).toBeLessThan(1) + await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).waitFor({ timeout: 20_000 }) await compareOrRefreshGolden(join(EXPECTED, 'changes-view.expected.md'), await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + await page.getByRole('button', { name: '全屏', exact: true }).click() + await view.getByRole('navigation').getByRole('button', { name: 'src/panel.ts', exact: true }).waitFor() + const fileTree = view.getByRole('navigation') + const directoryName = await fileTree.getByText('src', { exact: true }).boundingBox() + const fileName = await fileTree.getByText('panel.ts', { exact: true }).boundingBox() + if (directoryName === null || fileName === null) throw new Error('Tree entries must be visible') + expect(fileName.x).toBeGreaterThan(directoryName.x) + await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('src') + await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('') + await fileTree.getByRole('button', { name: 'src', exact: true }).click() + await view.getByRole('button', { name: '文件树', exact: true }).click() + expect(await fileTree.isVisible()).toBe(false) + await view.getByRole('button', { name: '文件树', exact: true }).click() + expect(await fileTree.getByRole('button', { name: 'src', exact: true }).getAttribute('aria-expanded')).toBe('false') + await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('src') + await view.getByRole('button', { name: '文件树', exact: true }).click() + await view.getByRole('button', { name: '文件树', exact: true }).click() + expect(await fileTree.getByRole('textbox', { name: '筛选文件…' }).inputValue()).toBe('src') + await compareOrRefreshGolden(join(EXPECTED, 'file-tree-toggle.expected.md'), + await captureStableAria(page, '[data-forge-changes="change"]', scaffold.workspaceCwd), MODE) + await fileTree.getByRole('textbox', { name: '筛选文件…' }).fill('') + await fileTree.getByRole('button', { name: 'src', exact: true }).click() + const resizeTree = view.getByRole('separator', { name: '调整文件树宽度', exact: true }) + const originalWidth = Number(await resizeTree.getAttribute('aria-valuenow')) + const handle = await resizeTree.boundingBox() + if (handle === null) throw new Error('Tree resize handle must be visible') + await page.mouse.move(handle.x + handle.width / 2, handle.y + 100) + await page.mouse.down() + await page.mouse.move(handle.x - 80, handle.y + 100, { steps: 5 }) + await page.mouse.up() + expect(Number(await resizeTree.getAttribute('aria-valuenow'))).toBeGreaterThan(originalWidth) + await resizeTree.press('Home') + expect(await fileTree.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const searchBounds = await fileTree.getByRole('textbox').boundingBox() + const treeBounds = await fileTree.boundingBox() + if (searchBounds === null || treeBounds === null) throw new Error('Tree search must be visible') + expect(searchBounds.x + searchBounds.width).toBeLessThanOrEqual(treeBounds.x + treeBounds.width) + await resizeTree.press('ArrowLeft') + const resizedWidth = await resizeTree.getAttribute('aria-valuenow') + await view.getByRole('button', { name: '文件树', exact: true }).click() + await view.getByRole('button', { name: '文件树', exact: true }).click() + expect(await resizeTree.getAttribute('aria-valuenow')).toBe(resizedWidth) + for (const side of ['old', 'new'] as const) { + const firstLine = await panelFile.locator(`[data-review-code][data-${side}-line="2"]`).boundingBox() + const lastLine = await panelFile.locator(`[data-review-code][data-${side}-line="4"]`).boundingBox() + if (firstLine === null || lastLine === null) throw new Error('Review text must be visible') + await page.mouse.move(firstLine.x + 7, firstLine.y + firstLine.height / 2) + await page.mouse.down() + await page.mouse.move(lastLine.x + 120, lastLine.y + lastLine.height / 2, { steps: 5 }) + await page.mouse.up() + await panelFile.getByRole('button', { name: '添加评论', exact: true }).waitFor() + expect(await panelFile.getByRole('textbox', { name: '留下评论…' }).count()).toBe(0) + const opposite = panelFile.locator(`[data-diff-side="${side === 'old' ? 'R' : 'L'}"]`).first() + expect(await opposite.evaluate(element => getComputedStyle(element).userSelect)).toBe('none') + await page.keyboard.press('ControlOrMeta+c') + const copied = await page.evaluate(() => navigator.clipboard.readText()) + expect(copied).toContain(side === 'old' ? 'n2 = 2' : "n2 = 'two'") + expect(copied).not.toContain(side === 'old' ? "n2 = 'two'" : 'n2 = 2') + expect(copied.match(/n3 = 3/g)).toHaveLength(1) + } + await panelFile.getByRole('button', { name: '添加评论', exact: true }).click() + await panelFile.getByRole('region', { name: '评论 R2–4', exact: true }).waitFor() + await panelFile.getByRole('textbox', { name: '留下评论…' }).fill('请核对边界条件') + await panelFile.getByRole('button', { name: 'GitHub 评论选项', exact: true }).click() + await page.getByRole('menuitem', { name: '发布单条评论', exact: true }).waitFor() + await page.keyboard.press('Escape') + await compareOrRefreshGolden(join(EXPECTED, 'review-composer.expected.md'), + await captureStableAria(page, '[data-forge-comment]', scaffold.workspaceCwd), MODE) + await page.getByRole('button', { name: '退出全屏', exact: true }).click() + const commentForm = panelFile.locator('[data-forge-comment]') + expect(await commentForm.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await page.getByRole('button', { name: '全屏', exact: true }).click() + await page.setViewportSize({ width: 390, height: 780 }) + await commentForm.getByRole('textbox').focus() + expect(await commentForm.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const narrowComment = await commentForm.boundingBox() + if (narrowComment === null) throw new Error('Comment form must remain visible') + expect(narrowComment.x + narrowComment.width).toBeLessThanOrEqual(390) + await page.setViewportSize({ width: 1680, height: 1000 }) + await panelFile.getByRole('button', { name: '开始评审', exact: true }).click() + await panelFile.locator('[data-forge-review-thread="pending"]').getByText('请核对边界条件', { exact: true }).waitFor() + await page.setViewportSize({ width: 1680, height: 500 }) + const changesScroll = view.locator('[data-forge-changes-scroll]') + await changesScroll.evaluate((element) => { element.scrollTop = element.scrollHeight }) + const reviewScroll = await changesScroll.evaluate(element => element.scrollTop) + expect(reviewScroll).toBeGreaterThan(0) + await view.getByRole('button', { name: '提交评审 (1)', exact: true }).click() + const reviewDialog = page.getByRole('dialog', { name: '提交评审', exact: true }) + await reviewDialog.waitFor() + expect(await reviewDialog.getByRole('textbox').count()).toBe(1) + expect(await reviewDialog.getByText('请核对边界条件', { exact: true }).count()).toBe(0) + expect(await changesScroll.evaluate(element => element.scrollTop)).toBe(reviewScroll) + await page.setViewportSize({ width: 390, height: 780 }) + expect(await reviewDialog.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + const narrowDialog = await reviewDialog.boundingBox() + if (narrowDialog === null) throw new Error('Review dialog must remain visible') + expect(narrowDialog.x + narrowDialog.width).toBeLessThanOrEqual(390) + await page.setViewportSize({ width: 1680, height: 500 }) + await page.keyboard.press('Escape') + expect(await reviewDialog.count()).toBe(0) + await view.getByRole('button', { name: '提交评审 (1)', exact: true }).click() + await reviewDialog.getByRole('textbox', { name: '评审总结…', exact: true }).fill('需要补充边界检查') + await reviewDialog.getByRole('radio', { name: '请求更改', exact: true }).check() + await compareOrRefreshGolden(join(EXPECTED, 'submit-review.expected.md'), + await captureStableAria(page, '[role="dialog"][aria-label="提交评审"]', scaffold.workspaceCwd), MODE) + await reviewDialog.getByRole('button', { name: '提交评审', exact: true }).click() + await page.getByRole('alert').filter({ hasText: '已提交评审' }).waitFor() + await panelFile.locator('[data-forge-review-thread="published"]').getByText('请核对边界条件', { exact: true }).waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'review-record.expected.md'), await captureStableAria(page, '[data-forge-review-thread="published"]', scaffold.workspaceCwd), MODE) + const published: unknown = JSON.parse((await readFile(join(root, 'reviews.jsonl'), 'utf8')).trim()) + expect(published).toEqual({ endpoint: 'repos/octo/demo/pulls/7/reviews', body: { commit_id: HEAD7, event: 'REQUEST_CHANGES', body: '需要补充边界检查', + comments: [{ path: 'src/panel.ts', side: 'RIGHT', line: 4, start_line: 2, start_side: 'RIGHT', body: '请核对边界条件' }] } }) + await page.getByRole('button', { name: '退出全屏', exact: true }).click() await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).click() await panelFile.getByText('export const n6 = 6', { exact: true }).first().waitFor({ timeout: 20_000 }) await panelFile.getByRole('button', { name: '2 行未变更', exact: true }).waitFor() - await panelFile.getByRole('button', { name: '复制路径: src/panel.ts', exact: true }).click() + await panelFile.getByRole('button', { name: 'panel.ts 的更多操作', exact: true }).click() + await page.getByRole('menuitem', { name: '复制路径', exact: true }).click() await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe('src/panel.ts') const docsFile = view.locator('[data-forge-diff-file="docs/panel.md"]') await docsFile.getByRole('button', { name: '收起 panel.md', exact: true }).click() await page.setViewportSize({ width: 1280, height: 500 }) const scrollport = view.locator('[data-forge-changes-scroll]') await scrollport.evaluate((element) => { element.scrollTop = 100; element.dispatchEvent(new Event('scroll')) }) - await panelFile.getByRole('button', { name: '复制路径: src/panel.ts', exact: true }).click() + await panelFile.locator('[data-forge-file-label]').click() const position = await scrollport.evaluate(element => element.scrollTop) expect(position).toBeGreaterThan(0) const originalFile = await panelFile.elementHandle() @@ -672,7 +844,19 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an expect(await panelFile.evaluate((element, original) => element === original, originalFile)).toBe(true) await expect.poll(() => docsFile.getAttribute('data-expanded')).toBe(null) await expect.poll(() => scrollport.evaluate(element => element.scrollTop)).toBe(position) + expect(await panelFile.locator('[data-forge-review-thread="published"]').count()).toBe(1) await page.setViewportSize({ width: 1680, height: 1000 }) + await page.locator('[data-dockkit-tab]').filter({ hasText: '#7 的变更' }).locator('[data-dockkit-tab-close]').click() + await expect.poll(() => view.count()).toBe(0) + if (await header.getAttribute('aria-pressed') !== 'true') await header.click() + await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() + await panelFile.getByRole('button', { name: '6 行未变更', exact: true }).waitFor() + expect(await panelFile.locator('[data-forge-review-thread]').count()).toBe(0) + await view.getByRole('button', { name: '提交评审', exact: true }).click() + await reviewDialog.waitFor() + expect(await reviewDialog.getByRole('textbox').inputValue()).toBe('') + expect(await reviewDialog.getByRole('radio', { name: '评论', exact: true }).isChecked()).toBe(true) + await page.keyboard.press('Escape') // GitHub refuses the diff of pull request 9 as too large, so its view offers the web page instead of a retry. scaffold.ctx.forgeSession.track(session, DRAFT) @@ -697,8 +881,300 @@ it.skipIf(MODE === 'record')('shows the local changes of the Session by scope an }) +it.skipIf(MODE === 'record')('retains a wrapped code line and tree width across tab and Session switches', async () => { + const { page, scaffold, root, tripwire } = await launchPanel('web-e2e-forge-reading-position') + const paths = ['src/before-0.ts', 'src/before-1.ts', 'src/before-2.ts', 'src/server.ts', 'src/after.ts'] + const patch = paths.map(path => [ + `diff --git a/${path} b/${path}`, 'index 1111111..2222222 100644', `--- a/${path}`, `+++ b/${path}`, + '@@ -1,650 +1,650 @@', '-const oldValue = true;', '+const newValue = true;', + ...Array.from({ length: 649 }, (_, index) => ` const value_${index + 2} = "${'x'.repeat(24 + (index + 2) % 70)}";`), '', + ].join('\n')).join('\n') + await writeFile(join(root, 'pr-7.diff'), patch) + 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) + // Keep the file tree and the Session sidebar visible together on every platform. + await page.setViewportSize({ width: 2400, height: 700 }) + await page.locator('[data-forge-header]').click() + await page.locator(`[data-forge-change="${PULL}"]`).getByRole('button', { name: /查看 #7 的变更/ }).click() + const view = page.locator('[data-forge-changes="change"]') + const scroll = view.locator('[data-forge-changes-scroll]') + const file = view.locator('[data-forge-diff-file="src/server.ts"]') + const code = file.locator('[data-review-code][data-new-line="300"]') + const separator = view.getByRole('separator', { name: '调整文件树宽度', exact: true }) + const beforeFile = view.locator('[data-forge-diff-file="src/before-0.ts"]') + // ResizeObserver runs between rendering frames, including when an ancestor becomes hidden. + const layout = () => page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + })) + const reading = () => file.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + const top = Math.max(viewport.getBoundingClientRect().top, element.firstElementChild!.getBoundingClientRect().bottom) + const line = [...element.querySelectorAll('[data-review-code][data-new-line]')] + .find(row => row.getBoundingClientRect().bottom > top + 1)! + return { path: element.getAttribute('data-forge-diff-file'), line: line.dataset.newLine, + offset: line.getBoundingClientRect().top - top, scrollTop: viewport.scrollTop } + }) + await code.waitFor() + for (const width of [240, 320]) { + if (width === 320) { + for (let step = 0; step < 4; step += 1) await separator.press('ArrowLeft') + await beforeFile.getByRole('button', { name: '收起 before-0.ts', exact: true }).click() + } + await layout() + await code.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + const header = element.closest('[data-forge-diff-file]')!.firstElementChild! + const top = viewport.getBoundingClientRect().top + header.getBoundingClientRect().height + viewport.scrollTop += element.getBoundingClientRect().top - top + 7 + }) + await layout() + const position = await reading() + expect(position.line).toBe('300') + expect(position.offset).toBe(-7) + for (const destination of ['tab', 'session', 'tab', 'session']) { + if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '变更请求' }).click() + else await page.getByRole('button', { name: '新建会话', exact: true }).last().click() + await expect.poll(() => view.isVisible()).toBe(false) + await layout() + expect(await scroll.evaluate(element => element.clientWidth)).toBe(0) + if (destination === 'tab') await page.getByRole('tab').filter({ hasText: '#7 的变更' }).click() + else await page.locator(`[data-row-key="session:${sessionId}"]`).click() + await view.waitFor() + await layout() + expect(await separator.getAttribute('aria-valuenow')).toBe(String(width)) + expect(await reading()).toEqual(position) + expect(await beforeFile.getAttribute('data-expanded')).toBe(width === 240 ? '' : null) + } + } + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('uses horizontal arrows to navigate files while preserving vertical scrolling and comment editing', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-file-keys') + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + for (const path of ['a.txt', 'b.txt', 'c.txt']) { + await writeFile(join(project, path), Array.from({ length: path === 'c.txt' ? 1 : 80 }, (_, line) => `line ${line + 1}\n`).join('')) + } + const { settled } = await sendPrompt(page, scaffold) + await settled + await page.locator('[data-forge-header]').click() + await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() + await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:3 个文件/ }).click() + const view = page.locator('[data-forge-changes="local"]') + const scroll = view.getByRole('region', { name: '全部 3 个文件', exact: true }) + await scroll.waitFor() + await page.getByRole('button', { name: '全屏', exact: true }).click() + await page.setViewportSize({ width: 1280, height: 500 }) + const tree = view.getByRole('navigation') + const a = view.locator('[data-forge-diff-file="a.txt"]') + const b = view.locator('[data-forge-diff-file="b.txt"]') + const c = view.locator('[data-forge-diff-file="c.txt"]') + await b.getByRole('button', { name: '收起 b.txt', exact: true }).click() + await scroll.evaluate((element) => { element.scrollTop = 0 }) + await scroll.focus() + await page.keyboard.press('ArrowLeft') + expect(await scroll.evaluate(element => element.scrollTop)).toBe(0) + expect(await scroll.evaluate(element => getComputedStyle(element).outlineStyle)).toBe('none') + await page.keyboard.press('ArrowDown') + await expect.poll(() => scroll.evaluate(element => element.scrollTop)).toBeGreaterThan(0) + await scroll.evaluate((element) => { element.scrollTop = 0 }) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + expect(await b.getAttribute('data-expanded')).toBe('') + expect(await scroll.evaluate(element => document.activeElement === element)).toBe(true) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') + const lastPosition = await scroll.evaluate(element => element.scrollTop) + const lastBox = await c.boundingBox(), viewport = await scroll.boundingBox() + if (lastBox === null || viewport === null) throw new Error('The last file and scroll viewport must be rendered') + expect(lastBox.y).toBeGreaterThan(viewport.y) + expect(lastBox.y).toBeLessThan(viewport.y + viewport.height) + await page.keyboard.press('ArrowRight') + expect(await scroll.evaluate(element => element.scrollTop)).toBe(lastPosition) + await page.keyboard.press('ArrowLeft') + await expect.poll(() => tree.getByRole('button', { name: 'b.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await page.keyboard.press('ArrowLeft') + await expect.poll(() => tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await b.evaluate((element) => { + const viewport = element.closest('[data-forge-changes-scroll]')! + viewport.scrollTop += element.getBoundingClientRect().top - viewport.getBoundingClientRect().top + 100 + }) + await page.keyboard.press('ArrowRight') + await expect.poll(() => tree.getByRole('button', { name: 'c.txt', exact: true }).getAttribute('aria-current')).toBe('true') + await tree.getByRole('button', { name: 'a.txt', exact: true }).click() + await a.getByRole('button', { name: '选择第 R1 行', exact: true }).click() + await a.getByRole('button', { name: '添加评论', exact: true }).click() + const input = a.getByRole('textbox', { name: '留下评论…', exact: true }) + await input.fill('keep editing') + await input.press('ArrowLeft') + expect(await input.evaluate(element => (element as HTMLTextAreaElement).selectionStart)).toBe(11) + await input.press('ArrowRight') + expect(await input.inputValue()).toBe('keep editing') + expect(await tree.getByRole('button', { name: 'a.txt', exact: true }).getAttribute('aria-current')).toBe('true') + expect(await input.evaluate(element => document.activeElement === element)).toBe(true) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps localized status columns separate and long file lists inside one vertical scroller', async () => { + const { scaffold, page, project, tripwire } = await launchPanel('web-e2e-forge-layout') + await page.locator('[data-forge-current-branch]').waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'worktree-option.expected.md'), + await captureStableAria(page, '[data-forge-worktree]', scaffold.workspaceCwd), MODE) + await page.getByRole('button', { name: '收起侧边栏', exact: true }).click() + await page.setViewportSize({ width: 390, height: 844 }) + await expect.poll(() => page.locator('[data-forge-worktree]') + .evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(390) + await page.setViewportSize({ width: 1680, height: 1000 }) + await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') + await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') + await mkdir(join(project, 'src')) + await Promise.all(Array.from({ length: 60 }, (_, index) => writeFile(join(project, 'src', `file-${index}.ts`), `export const value = ${index}\n`))) + const { settled } = await sendPrompt(page, scaffold) + const session = scaffold.ctx.sessions.get(await settled) + if (session === undefined) throw new Error('The Session must stay loaded') + scaffold.ctx.forgeSession.track(session, PULL) + await page.locator('[data-forge-header]').click() + const panel = page.locator('[data-forge-panel]') + await panel.getByRole('button', { name: '刷新状态', exact: true }).click() + const local = panel.locator('[data-forge-local]') + await local.locator('button[aria-expanded]').click() + await expect.poll(() => local.locator('li').count(), { timeout: 20_000 }).toBe(60) + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 700 }) + const outerScrollers = await panel.evaluate((element) => { + const scrollers: string[] = [] + for (let ancestor = element.parentElement; ancestor !== null; ancestor = ancestor.parentElement) { + if (/auto|scroll/.test(getComputedStyle(ancestor).overflowY) && ancestor.scrollHeight > ancestor.clientHeight + 1) { + scrollers.push(ancestor.className) + } + } + return scrollers + }) + expect(outerScrollers).toEqual([]) + expect(await panel.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + await local.locator('li').last().scrollIntoViewIfNeeded() + expect(await local.locator('li').last().isVisible()).toBe(true) + } + await local.locator('button[aria-expanded]').click() + const change = panel.locator(`[data-forge-change="${PULL}"]`) + for (const [locale, labels] of [ + ['zh', ['检查', '评审', '合并', '变更']], + ['en', ['Checks', 'Review', 'Merge', 'Changes']], + ['de', ['Prüfungen', 'Review', 'Zusammenführen', 'Änderungen']], + ] as const) { + await scaffold.ctx.settings.update('locale', { preference: locale }) + await change.getByText(labels[0], { exact: true }).waitFor() + if (locale === 'en') { + await compareOrRefreshGolden(join(EXPECTED, 'local-card.expected.md'), + await captureStableAria(page, '[data-forge-local]', scaffold.workspaceCwd), MODE) + } + for (const width of [1280, 390]) { + await page.setViewportSize({ width, height: 700 }) + await expect.poll(() => change.evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(width) + await change.getByText(labels[3], { exact: true }).hover() + for (const label of labels) { + const geometry = await change.getByText(label, { exact: true }).evaluate((element) => { + const value = element.nextElementSibling + if (value === null) throw new Error('Status label must have a value') + const range = document.createRange() + range.selectNodeContents(element) + const name = range.getBoundingClientRect() + const content = value.getBoundingClientRect() + const row = element.parentElement! + const icon = element.previousElementSibling! + const rowRect = row.getBoundingClientRect() + return { + gap: content.left - name.right, + iconInset: icon.getBoundingClientRect().left - rowRect.left, + rowInset: rowRect.left - row.closest('[data-forge-change]')!.getBoundingClientRect().left, + labelWidth: element.getBoundingClientRect().width, + valueOffset: content.left - rowRect.left, + right: content.right, + width: document.documentElement.clientWidth, + } + }) + expect(geometry.gap).toBeGreaterThanOrEqual(8) + expect(geometry.iconInset).toBe(8) + expect(geometry.rowInset).toBeGreaterThanOrEqual(6) + expect(geometry.rowInset).toBeLessThanOrEqual(7) + if (locale === 'zh') { + expect(geometry.labelWidth).toBe(32) + expect(geometry.valueOffset).toBe(76) + } + expect(geometry.right).toBeLessThanOrEqual(geometry.width) + } + } + } + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + +it.skipIf(MODE === 'record')('keeps long branch details accessible by touch and keyboard across the hero row breakpoints', async () => { + const branch = 'feature/a-long-current-branch-name-for-mobile-review' + const { page, scaffold, tripwire } = await launchPanel('web-e2e-forge-branch-details', 'normal', { branch, hasTouch: true }) + const option = page.locator('[data-forge-worktree]') + const chip = option.locator('[data-forge-current-branch]') + await chip.waitFor() + await page.getByRole('button', { name: '收起侧边栏', exact: true }).click() + for (const [locale, label] of [['zh', `当前分支:${branch}`], ['en', `Current branch: ${branch}`], ['de', `Aktueller Branch: ${branch}`]] as const) { + await scaffold.ctx.settings.update('locale', { preference: locale }) + await option.getByRole('button', { name: label, exact: true }).waitFor() + for (const width of [390, 600, 601, 700, 1280]) { + await page.setViewportSize({ width, height: 844 }) + await chip.scrollIntoViewIfNeeded() + await expect.poll(() => option.evaluate((element) => { + const row = element.closest('[class*="heroWorkspaceRow"]')! + const ancestors: Element[] = [] + for (let node: Element | null = row; node !== null; node = node.parentElement) ancestors.push(node) + return { + fits: element.getBoundingClientRect().right <= innerWidth, + overflow: ancestors.filter(node => node.scrollWidth > node.clientWidth + 1).map(node => node.className), + } + })).toEqual({ fits: true, overflow: [] }) + } + } + await scaffold.ctx.settings.update('locale', { preference: 'en' }) + await option.getByRole('button', { name: `Current branch: ${branch}`, exact: true }).waitFor() + await page.setViewportSize({ width: 390, height: 844 }) + expect(await chip.locator('span').evaluate(element => element.scrollWidth > element.clientWidth)).toBe(true) + const tooltip = page.getByRole('tooltip', { exact: true, name: `Current branch: ${branch}` }) + await chip.tap() + await tooltip.waitFor() + await compareOrRefreshGolden(join(EXPECTED, 'branch-details.expected.md'), await tooltip.ariaSnapshot(), MODE) + await chip.tap() + await tooltip.waitFor({ state: 'hidden' }) + await chip.tap() + await tooltip.waitFor() + await page.locator('[class*="heroWorkspaceRow"]').tap({ position: { x: 1, y: 1 } }) + await tooltip.waitFor({ state: 'hidden' }) + await chip.focus() + await page.keyboard.press('Tab') + await page.keyboard.press('Shift+Tab') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + await page.keyboard.press('Enter') + await tooltip.waitFor() + await page.keyboard.press('Escape') + await tooltip.waitFor({ state: 'hidden' }) + expect(await option.getByRole('checkbox').isChecked()).toBe(false) + expect(await page.getByRole('menu').count()).toBe(0) + await scaffold.ctx.settings.update('locale', { preference: 'zh' }) + await option.getByRole('checkbox', { name: '新建工作树', exact: true }).waitFor() + const { settled } = await sendPrompt(page, scaffold) + await settled + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) +}) + it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff menus when the %s desktop shortcut deactivates a retained tab', async (platform) => { - const { page, scaffold, project, tripwire } = await launchPanel(`web-e2e-forge-menu-${platform}`, 'normal', platform) + const { page, scaffold, project, tripwire } = await launchPanel(`web-e2e-forge-menu-${platform}`, 'normal', { desktop: platform }) await git(project, 'update-ref', 'refs/remotes/origin/main', 'HEAD') await git(project, 'symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main') await writeFile(join(project, 'README.md'), 'review this change\n') @@ -708,7 +1184,7 @@ it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff men await page.locator('[data-forge-panel]').getByRole('button', { name: '刷新状态', exact: true }).click() await page.locator('[data-forge-local]').getByRole('button', { name: /查看本会话的变更:1 个文件/ }).click() const view = page.locator('[data-forge-changes="local"]') - await view.getByRole('button', { name: '复制路径: README.md', exact: true }).waitFor() + await view.locator('[data-forge-diff-file="README.md"]').waitFor() for (const name of ['分支', '全部 1 个文件', 'README.md 的更多操作']) { await view.getByRole('button', { name, exact: true }).click() await page.getByRole('menu').waitFor() @@ -724,3 +1200,59 @@ it.skipIf(MODE === 'record').each(['darwin', 'win32'] as const)('closes diff men } expect(tripwire.warnings).toEqual([]) }) + +it.skipIf(MODE === 'record').each([120, 4000])('types a review comment beside %i changed lines', async (count) => { + const { scaffold, page, root, tripwire } = await launchPanel('web-e2e-forge-review-typing') + const patch = ['diff --git a/src/typing.ts b/src/typing.ts', 'index 1111111..2222222 100644', + '--- a/src/typing.ts', '+++ b/src/typing.ts', `@@ -1,${count} +1,${count} @@`, + ...Array.from({ length: count }, (_, index) => { + const context = index % 80 === 0 ? 'wrapped context '.repeat(600) : index % 5 === 0 ? 'context '.repeat(30) : '' + return `-export const value${index} = [${index}, '${context}']\n+export const value${index} = [${index + 1}, '${context}']` + }), ''].join('\n') + await writeFile(join(root, 'pr-7.diff'), patch) + 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() + const change = page.locator(`[data-forge-change="${PULL}"]`) + await change.getByRole('button', { name: '查看 #7 的变更:新增 128 行,删除 14 行', exact: true }).click() + const file = page.locator('[data-forge-diff-file="src/typing.ts"]') + const collapsed = file.getByRole('button', { name: /^文件较大,/ }) + await file.waitFor() + if (count > 120) await collapsed.click() + await file.getByRole('button', { name: '选择第 R5 行', exact: true }).click() + await file.getByRole('button', { name: '添加评论', exact: true }).click() + const input = file.getByRole('textbox', { name: '留下评论…', exact: true }) + await input.waitFor() + const field = await input.boundingBox() + if (field === null) throw new Error('Comment field must be visible') + await page.mouse.move(field.x + field.width - 3, field.y + field.height - 3) + await page.mouse.down() + await page.mouse.move(field.x + field.width - 3, field.y + field.height + 77, { steps: 5 }) + await page.mouse.up() + const resized = await input.boundingBox() + if (resized === null) throw new Error('Resized comment field must remain visible') + expect(resized.height).toBeGreaterThan(field.height + 50) + await input.fill('Review a wrapped line. '.repeat(80)) + expect(await input.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true) + expect(await input.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true) + await input.fill('') + await page.keyboard.type('Check the boundary') + await page.keyboard.press('Enter') + const cdp = await page.context().newCDPSession(page) + try { + await cdp.send('Input.imeSetComposition', { text: '检查', selectionStart: 2, selectionEnd: 2 }) + expect(await input.inputValue()).toBe('Check the boundary\n检查') + expect(await file.locator('[data-forge-review-thread]').count()).toBe(0) + await cdp.send('Input.insertText', { text: '检查边界条件' }) + } finally { await cdp.detach() } + expect(await input.inputValue()).toBe('Check the boundary\n检查边界条件') + await input.fill(' \n') + expect(await file.getByRole('button', { name: '开始评审', exact: true }).isDisabled()).toBe(true) + await input.fill('检查边界条件') + await file.getByRole('button', { name: '开始评审', exact: true }).click() + await file.locator('[data-forge-review-thread="pending"]').getByText('检查边界条件', { exact: true }).waitFor() + expect(tripwire.pageErrors).toEqual([]) +}) diff --git a/apps/web/tests/hover-input.e2e.ts b/apps/web/tests/hover-input.e2e.ts index cae5220a89..ccba69a0c7 100644 --- a/apps/web/tests/hover-input.e2e.ts +++ b/apps/web/tests/hover-input.e2e.ts @@ -95,18 +95,24 @@ it.each([false, true])('keeps workspace and archived search actions reachable wi expect(await shortcut.count()).toBe(1) expect(await page.evaluate(() => matchMedia('(pointer: coarse)').matches)).toBe(hasTouch) expect(await shortcut.isVisible()).toBe(!hasTouch) + if (hasTouch) { + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 390, height: 900 }) + await page.locator('[data-sidebar-drawer]').waitFor() + await page.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).tap() + await activate(actions) + await archive.waitFor() + } for (const key of ['ArrowDown', 'Tab']) { await page.keyboard.press(key) expect(await page.locator('html').getAttribute('data-input-modality')).toBe('keyboard') expect(await page.getByRole('menu').evaluate(menu => menu.contains(document.activeElement))).toBe(true) expect(await shortcut.isVisible()).toBe(true) if (hasTouch) { - await page.setViewportSize({ width: 390, height: 900 }) await expect.poll(() => shortcut.evaluate((element) => { const bounds = element.getBoundingClientRect() return bounds.left >= 0 && bounds.right <= window.innerWidth })).toBe(true) - await page.setViewportSize({ width: 1280, height: 900 }) } await page.keyboard.press('Escape') if (!hasTouch) await row.hover() @@ -114,6 +120,13 @@ it.each([false, true])('keeps workspace and archived search actions reachable wi await archive.waitFor() expect(await shortcut.isVisible()).toBe(!hasTouch) } + if (hasTouch) { + await page.keyboard.press('Escape') + await page.setViewportSize({ width: 1280, height: 900 }) + await page.locator('[data-sidebar-drawer]').waitFor({ state: 'detached' }) + await activate(actions) + await archive.waitFor() + } await activate(archive) await row.waitFor({ state: 'detached' }) await activate(page.getByRole('button', { name: 'View options', exact: true })) @@ -224,19 +237,23 @@ it.each([false, true])('keeps actions and focus usable with touch=%s across layo await page.getByRole('tooltip').waitFor({ state: 'detached' }) const blockedSplit = panel.locator('[data-dockkit-split-button]').last() expect(await blockedSplit.isDisabled()).toBe(true) - const hit = await blockedSplit.evaluate((button) => { - const bounds = button.getBoundingClientRect() - const x = bounds.x + bounds.width / 2 - const y = bounds.y + bounds.height / 2 - const target = document.elementFromPoint(x, y) - return { x, y, wrapperReceivesInput: target === button.parentElement, cursor: target && getComputedStyle(target).cursor } - }) - expect(hit.wrapperReceivesInput).toBe(true) - expect(['auto', 'default']).toContain(hit.cursor) - // Coordinate input exercises CSS hit testing over the disabled button itself. - if (hasTouch) await page.touchscreen.tap(hit.x, hit.y) - else await page.mouse.click(hit.x, hit.y) - await page.getByRole('tooltip').filter({ hasText: 'Two panes is the limit' }).waitFor() + if (hasTouch) { + expect(await blockedSplit.isVisible()).toBe(false) + expect(await page.getByRole('tooltip').count()).toBe(0) + } else { + const hit = await blockedSplit.evaluate((button) => { + const bounds = button.getBoundingClientRect() + const x = bounds.x + bounds.width / 2 + const y = bounds.y + bounds.height / 2 + const target = document.elementFromPoint(x, y) + return { x, y, wrapperReceivesInput: target === button.parentElement, cursor: target && getComputedStyle(target).cursor } + }) + expect(hit.wrapperReceivesInput).toBe(true) + expect(['auto', 'default']).toContain(hit.cursor) + // Coordinate input exercises CSS hit testing over the disabled button itself. + await page.mouse.click(hit.x, hit.y) + await page.getByRole('tooltip').filter({ hasText: 'Two panes is the limit' }).waitFor() + } expect(await panel.locator('[data-dockkit-pane]').count()).toBe(2) expect(consoleWatch.pageErrors).toEqual([]) }) diff --git a/apps/web/tests/layout-bottom.e2e.ts b/apps/web/tests/layout-bottom.e2e.ts index ee213925b3..61c7f4f405 100644 --- a/apps/web/tests/layout-bottom.e2e.ts +++ b/apps/web/tests/layout-bottom.e2e.ts @@ -42,7 +42,8 @@ it('reserves bottom content height without remounting it on main-panel navigatio const viewportHeight = page.viewportSize()!.height expect(result.bottom).toEqual({ top: viewportHeight - height, height, bottom: viewportHeight }) expect(result.main).toEqual({ top: caption, height: viewportHeight - caption - height, bottom: viewportHeight - height }) - expect(result.sidebar).toEqual(result.main) + expect(result.sidebar).toEqual(page.viewportSize()!.width < 768 + ? { top: 0, height: viewportHeight, bottom: viewportHeight } : result.main) expect(result.rightbar).toEqual(result.main) expect(result.overlay).toEqual({ top: 0, height: viewportHeight, bottom: viewportHeight }) for (const handle of result.handles) expect(handle).toEqual(result.main) diff --git a/apps/web/tests/markdown-wide-table.e2e.ts b/apps/web/tests/markdown-wide-table.e2e.ts index bdd7c5da6f..eba073c473 100644 --- a/apps/web/tests/markdown-wide-table.e2e.ts +++ b/apps/web/tests/markdown-wide-table.e2e.ts @@ -216,8 +216,8 @@ async function awaitTableLayout(target: Page): Promise { if (element === null) return false const tracks = getComputedStyle(element).gridTemplateColumns.split(' ').map(Number.parseFloat) const root = element.querySelector('div[data-phase]') - // Mirrored from ui-layout's SIDEBAR_COLLAPSED; these tests use the Host compiler face. - return tracks[0] === 56 && tracks.at(-1) === 0 + // Desktop retains the rail; the mobile drawer leaves the whole width to the transcript. + return tracks[0] === (element.hasAttribute('data-sidebar-drawer') ? 0 : 56) && tracks.at(-1) === 0 && element.getAnimations().every(animation => animation.playState === 'finished' || animation.playState === 'idle') && root !== null diff --git a/apps/web/tests/model-input-layout.ts b/apps/web/tests/model-input-layout.ts index e911bb3812..5cdacbfabd 100644 --- a/apps/web/tests/model-input-layout.ts +++ b/apps/web/tests/model-input-layout.ts @@ -27,5 +27,11 @@ export async function assertModelInputLayout(page: Page, editor: Locator): Promi } } finally { await page.setViewportSize(original) + // The frame reports its own width to the layout store from a rAF-throttled + // ResizeObserver, so the restored viewport is only in force once the shell + // has left drawer mode; a capture taken in between reads the narrow frame. + if (await page.locator('[data-sidebar-drawer]').count() > 0) { + await expect.poll(async () => page.locator('[data-sidebar-drawer]').count(), { timeout: 5_000 }).toBe(0) + } } } diff --git a/apps/web/tests/plan-control-row.e2e.ts b/apps/web/tests/plan-control-row.e2e.ts index c32960a14e..5d8f5b39ae 100644 --- a/apps/web/tests/plan-control-row.e2e.ts +++ b/apps/web/tests/plan-control-row.e2e.ts @@ -62,7 +62,17 @@ async function controlLayout(page: Page) { /** Wait for the responsive column and control row to finish changing width. */ async function resizeControls(page: Page, width: number): Promise { + const previousWidth = page.viewportSize()!.width await page.setViewportSize({ width, height: VIEWPORT.height }) + if (width >= 768 && width < 1024) { + const frame = page.locator('[data-sidebar-collapsed][data-rightbar-collapsed]') + if (previousWidth >= 1024) await frame.waitFor() + const open = page.getByRole('button', { name: 'Open sidebar', exact: true }) + if (await open.isVisible()) { + await open.click() + await expect.poll(() => frame.count()).toBe(0) + } + } await page.locator('[data-composer-card]').evaluate(async (card) => { let previous = card.getBoundingClientRect().width let stable = 0 @@ -201,7 +211,7 @@ describe('web e2e: plan chip click area at the narrow viewport', () => { // Find the content-dependent transition on this platform's fonts, never a // committed pixel threshold. The old 360px rule cannot satisfy this case. let narrowViewport: number | undefined - for (let width = 1100; width >= 650; width -= 10) { + for (let width = 1100; width >= 770; width -= 10) { await resizeControls(page, width) const layout = await controlLayout(page) if (layout.width > 360 && layout.icon && !layout.text) { @@ -267,7 +277,7 @@ describe('web e2e: plan chip click area at the narrow viewport', () => { await selectModel(page, LONG_MODEL) await expectControlLayout(page, false) - await resizeControls(page, 440) + await resizeControls(page, 384) await expectControlLayout(page, true) const trigger = page.getByRole('button', { name: /Select model/ }) expect(await trigger.getAttribute('title')).toContain(LONG_MODEL) diff --git a/apps/web/tests/plugin-manager.e2e.ts b/apps/web/tests/plugin-manager.e2e.ts index fe2ad02273..61ce911f8c 100644 --- a/apps/web/tests/plugin-manager.e2e.ts +++ b/apps/web/tests/plugin-manager.e2e.ts @@ -268,8 +268,8 @@ describe('web e2e: plugin manager', () => { await bar.getByRole('tablist').waitFor() await add.focus() for (const [width, icons, narrowTabs, wraps] of [ - [1280, false, false, false], [600, true, false, false], - [470, true, true, false], [390, true, true, true], [300, true, true, true], + [1280, false, false, false], [544, true, false, false], + [414, true, true, false], [334, true, true, true], [244, true, true, true], ] as const) { await probe.setViewportSize({ width, height: 480 }) await body.evaluate((element) => { element.scrollTop = 180 }) diff --git a/apps/web/tests/plugin-sticky-motion.e2e.ts b/apps/web/tests/plugin-sticky-motion.e2e.ts index ada88dbe66..d9a549c35f 100644 --- a/apps/web/tests/plugin-sticky-motion.e2e.ts +++ b/apps/web/tests/plugin-sticky-motion.e2e.ts @@ -83,8 +83,8 @@ it('preserves both header layouts and follows the scroll position without changi await page.locator('[data-plugin-bar][data-natural]').waitFor() await page.evaluate(() => document.fonts.ready) // Without tabs, whether the actions fit beside the title at 470px depends on the platform font, - // so that width is pinned only with tabs. - for (const width of hasTabs ? [1280, 600, 470, 390] : [1280, 600, 390]) { + // so that width is pinned only with tabs. At 334px the tabs and actions wrap onto separate rows. + for (const width of hasTabs ? [1280, 600, 470, 390, 334] : [1280, 600, 390]) { await page.setViewportSize({ width, height: 480 }) await scrollTo(page, 0) const resting = await reference(page, false) @@ -95,7 +95,7 @@ it('preserves both header layouts and follows the scroll position without changi expect(initial.tabs).toEqual(resting.tabs) if (hasTabs && width <= 600) { const tabs = initial.tabs! - if (width === 390) { + if (width === 334) { expect(initial.toolbar.y).toBeGreaterThanOrEqual(tabs.y + tabs.height) } else { expect(initial.toolbar.x).toBeGreaterThanOrEqual(tabs.x + tabs.width) diff --git a/apps/web/tests/schedule-after.e2e.ts b/apps/web/tests/schedule-after.e2e.ts index fb45d6c76a..b452ce6c5f 100644 --- a/apps/web/tests/schedule-after.e2e.ts +++ b/apps/web/tests/schedule-after.e2e.ts @@ -868,6 +868,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => { await page.getByRole('menuitem', { name: 'Delete task', exact: true }).click() const confirmation = page.getByRole('dialog', { name: 'Delete this task?' }) await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click() + expect(await moreActions.evaluate(button => button === document.activeElement)).toBe(true) expect((await scaffold.ctx.schedule.catalog()).some(task => task.id === other.id)).toBe(true) await moreActions.click() await page.getByRole('menuitem', { name: 'Delete task', exact: true }).click() diff --git a/apps/web/tests/schedule-header.e2e.ts b/apps/web/tests/schedule-header.e2e.ts index fc79fd571c..631fa3e464 100644 --- a/apps/web/tests/schedule-header.e2e.ts +++ b/apps/web/tests/schedule-header.e2e.ts @@ -58,10 +58,8 @@ it('keeps the automation title intact before moving New to another line', async facts.push(`${language} ${width}px: title and New single-line, New beside the title; contained; New retains focus`) } if (language === 'en') { - // 509px collapses the left sidebar to its rail; expanding it leaves the - // page column narrow enough (measured 172px) to force the wrap. - await page.setViewportSize({ width: 509, height: 1000 }) - await page.getByRole('button', { name: 'Open sidebar', exact: true }).first().click() + // Constrain this page independently of the shell's drawer breakpoint. + await header.evaluate((element) => { element.style.width = '220px' }) await expect.poll(() => header.evaluate((element) => { const title = element.querySelector('h1')! const button = element.querySelector('button')! @@ -76,7 +74,7 @@ it('keeps the automation title intact before moving New to another line', async : buttonRect.top >= titleRect.bottom - 1 ? 'below' as const : 'overlapping' as const, } })).toEqual({ titleSingleLine: true, placement: 'below' }) - facts.push('en 509px with sidebar expanded: title single-line; New moves below the title') + facts.push('en 220px page column: title single-line; New moves below the title') } expect(consoleWatch.pageErrors).toEqual([]) } finally { diff --git a/apps/web/tests/schedule-phone.e2e.ts b/apps/web/tests/schedule-phone.e2e.ts index b28049ba3d..e82104196a 100644 --- a/apps/web/tests/schedule-phone.e2e.ts +++ b/apps/web/tests/schedule-phone.e2e.ts @@ -7,6 +7,7 @@ import { expect, it } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-schedule' import { launchWebScaffold, watchConsole } from './scaffold.ts' +import { revealNavigationDrawer } from './support.ts' const PHONE_TASK_SESSION = SessionId('schedule-phone-web-e2e') const PHONE_TASK_TITLE = 'Review overdue deployment' @@ -25,6 +26,7 @@ interface ViewFacts { /** Open the Automation tasks page and return its panel. */ async function openTaskManager(page: Page, url: string): Promise { await page.goto(url, { waitUntil: 'load' }) + await revealNavigationDrawer(page, 'zh') await page.getByRole('button', { name: '自动化任务', exact: true }).click() const panel = page.getByTestId('task-manager-page') await panel.getByRole('heading', { name: '自动化任务', exact: true }).waitFor({ timeout: 30_000 }) diff --git a/apps/web/tests/sidebar-drawer.e2e.ts b/apps/web/tests/sidebar-drawer.e2e.ts new file mode 100644 index 0000000000..89721edacc --- /dev/null +++ b/apps/web/tests/sidebar-drawer.e2e.ts @@ -0,0 +1,667 @@ +/** Narrow sidebar geometry, navigation, focus and retained content in the shipped profile. */ +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import type { Locator } from 'playwright' +import { chromium } from 'playwright' +import { expect, it } from 'vitest' +import { compareOrRefreshGolden, launchWebScaffold, seedSession, watchConsole, webSnapshotMode } from './scaffold.ts' + +/** A returning rail uses its compact layout without wide-content or icon-entry animations. */ +async function assertCompactRail(sidebar: Locator): Promise { + expect(await sidebar.getByRole('button', { name: 'New session', exact: true }).count()).toBe(1) + expect(await sidebar.evaluate((el) => { + const root = el.firstElementChild! + return { + fits: root.getBoundingClientRect().width <= el.parentElement!.getBoundingClientRect().width, + animations: root.getAnimations({ subtree: true }) + .filter((animation): animation is CSSAnimation => + animation instanceof CSSAnimation && /wide-in|rail-in|rail-fade-in/.test(animation.animationName)) + .map(animation => animation.animationName), + } + })).toEqual({ fits: true, animations: [] }) +} + +it.each(['light', 'dark'] as const)('keeps the macOS drawer opaque and excludes inert content from window drag regions in %s mode', async (colorScheme) => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 520, height: 680 }, colorScheme, locale: 'en-US' }) + await page.goto(scaffold.authenticatedUrl) + const opener = page.getByRole('button', { name: 'Open sidebar', exact: true }) + await opener.waitFor() + await page.evaluate(() => { document.documentElement.dataset.platform = 'darwin' }) + await opener.click() + const drawer = page.getByRole('dialog', { name: 'Navigation', exact: true }) + await drawer.waitFor() + const column = page.locator('[data-slot="sidebar"]').locator('..') + const background = await column.evaluate((el) => { + const style = getComputedStyle(el) + return { color: style.backgroundColor, image: style.backgroundImage } + }) + expect(background.image).toBe('none') + expect(background.color).toMatch(/^rgb\(/) + expect(await drawer.getByRole('button', { name: 'New session', exact: true }).last().evaluate((el) => { + const actual = getComputedStyle(el).backgroundColor + const root = document.documentElement + const platform = root.dataset.platform + delete root.dataset.platform + try { + return actual === getComputedStyle(el).backgroundColor + } finally { + root.dataset.platform = platform + } + })).toBe(true) + const inactiveContent = page.locator('[inert], [inert] *') + expect(await inactiveContent.count()).toBeGreaterThan(0) + expect(await inactiveContent.evaluateAll(elements => elements + .filter(el => getComputedStyle(el).getPropertyValue('app-region') !== 'none') + .map(el => `${el.tagName}.${el.getAttribute('class')}: ${getComputedStyle(el).getPropertyValue('app-region')}`))) + .toEqual([]) + expect(await drawer.locator('[data-window-drag]').first().evaluate(el => getComputedStyle(el).getPropertyValue('app-region'))) + .toBe('drag') + const collapse = drawer.getByRole('button', { name: 'Collapse sidebar', exact: true }) + await collapse.click() + await drawer.waitFor({ state: 'hidden' }) + await page.setViewportSize({ width: 1200, height: 800 }) + const sidebar = page.locator('[data-slot="sidebar"]').locator('..') + await expect.poll(() => sidebar.evaluate(el => getComputedStyle(el).backgroundImage)).not.toBe('none') + const activeDragRows = page.locator('[data-window-drag]:not([inert] [data-window-drag])') + expect(await activeDragRows.count()).toBeGreaterThan(0) + expect(await activeDragRows.evaluateAll(rows => rows.every(row => getComputedStyle(row).getPropertyValue('app-region') === 'drag'))) + .toBe(true) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) + +it('hides a collapsed rail immediately when it becomes a drawer', async () => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 768, height: 844 }, locale: 'en-US' }) + await page.goto(scaffold.authenticatedUrl) + await page.getByRole('button', { name: 'Open sidebar', exact: true }).waitFor() + const sidebar = page.locator('[data-slot="sidebar"]') + const sidebarColumn = sidebar.locator('..') + await expect.poll(async () => (await sidebarColumn.boundingBox())?.width).toBe(56) + await sidebarColumn.evaluate((el) => { + el.parentElement!.style.setProperty('--ds-transition-duration-slow', '100s') + }) + await page.setViewportSize({ width: 767, height: 844 }) + await page.locator('[data-sidebar-drawer]').waitFor() + const state = await sidebarColumn.evaluate(el => ({ + visibility: getComputedStyle(el).visibility, + transitions: el.getAnimations().filter(animation => animation instanceof CSSTransition) + .map(animation => animation.transitionProperty), + })) + expect(state).toEqual({ visibility: 'hidden', transitions: [] }) + await page.setViewportSize({ width: 768, height: 844 }) + await page.locator('[data-sidebar-drawer]').waitFor({ state: 'detached' }) + await assertCompactRail(sidebar) + await page.setViewportSize({ width: 767, height: 844 }) + await page.locator('[data-sidebar-drawer]').waitFor() + await page.getByRole('button', { name: 'Open sidebar', exact: true }).click() + const drawer = page.getByRole('dialog', { name: 'Navigation', exact: true }) + await drawer.waitFor() + expect(await sidebarColumn.evaluate(el => el.getAnimations().some(animation => + animation instanceof CSSTransition && animation.transitionProperty === 'transform'))).toBe(true) + await sidebarColumn.evaluate((el) => { + for (const animation of el.parentElement!.getAnimations({ subtree: true })) animation.finish() + }) + await drawer.getByRole('button', { name: 'Collapse sidebar', exact: true }).click() + expect(await sidebarColumn.evaluate(el => el.getAnimations().some(animation => + animation instanceof CSSTransition && animation.transitionProperty === 'transform'))).toBe(true) + await sidebarColumn.evaluate((el) => { + for (const animation of el.parentElement!.getAnimations({ subtree: true })) animation.finish() + }) + await page.setViewportSize({ width: 768, height: 844 }) + await page.locator('[data-sidebar-drawer]').waitFor({ state: 'detached' }) + await assertCompactRail(sidebar) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) + +it('retains the closing slide when an expanded sidebar becomes a collapsed drawer', async () => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 1024, height: 844 }, locale: 'en-US' }) + await page.goto(scaffold.authenticatedUrl) + await page.getByRole('button', { name: 'Collapse sidebar', exact: true }).waitFor() + const sidebarColumn = page.locator('[data-slot="sidebar"]').locator('..') + await expect.poll(async () => (await sidebarColumn.boundingBox())?.width).toBe(280) + await sidebarColumn.evaluate((el) => { + el.parentElement!.style.setProperty('--ds-transition-duration-slow', '100s') + }) + await page.setViewportSize({ width: 767, height: 844 }) + await page.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor() + expect(await sidebarColumn.evaluate(el => el.getAnimations().some(animation => + animation instanceof CSSTransition && animation.transitionProperty === 'transform'))).toBe(true) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) + +/** Sample the CSS fade at its midpoint without depending on the host's frame rate. */ +async function assertMaskFade(frame: Locator, from: number, to: number): Promise { + const sample = await frame.locator('[data-sidebar-mask]').evaluate((el) => { + const fade = el.getAnimations().find(animation => animation instanceof CSSTransition && animation.transitionProperty === 'opacity') + if (fade === undefined || !(fade.effect instanceof KeyframeEffect)) throw new Error('Drawer mask opacity transition is missing') + fade.pause() + fade.currentTime = Number(fade.effect.getComputedTiming().duration) / 2 + return { + endpoints: fade.effect.getKeyframes().map(keyframe => Number(keyframe.opacity)), + opacity: Number(getComputedStyle(el).opacity), + } + }) + expect(sample.endpoints).toEqual([from, to]) + expect(sample.opacity).toBeGreaterThan(0) + expect(sample.opacity).toBeLessThan(1) + await frame.evaluate((el) => { + for (const animation of el.getAnimations({ subtree: true })) { + if (animation instanceof CSSTransition) animation.finish() + } + el.style.removeProperty('--ds-transition-duration-slow') + }) +} + +/** Sample both width transitions on the same clock to detect detached sidebar controls. */ +async function assertFoldResize(toggle: Locator, from: number, to: number): Promise { + await expect.poll(() => toggle.evaluate((button, target) => { + const frame = button.closest('[data-animating]') + return frame !== null && parseFloat(frame.style.gridTemplateColumns) === target && frame.getAnimations().some(animation => + animation instanceof CSSTransition && animation.transitionProperty === 'grid-template-columns') + }, to)).toBe(true) + const sample = await toggle.evaluate((button) => { + const frame = button.closest('[data-animating]')! + const transitions = frame.getAnimations({ subtree: true }).filter((animation): animation is CSSTransition => + animation instanceof CSSTransition && ['grid-template-columns', 'width'].includes(animation.transitionProperty)) + const grid = transitions.find(animation => animation.transitionProperty === 'grid-template-columns') + if (grid === undefined) throw new Error('Fold width transition is missing') + const at = (progress: number) => { + for (const transition of transitions) { + transition.pause() + transition.currentTime = Number(transition.effect!.getComputedTiming().duration) * progress + } + const width = parseFloat(getComputedStyle(frame).gridTemplateColumns) + return { width, gap: frame.getBoundingClientRect().left + width - button.getBoundingClientRect().right } + } + const start = at(0) + const middle = at(0.5) + const end = at(1) + for (const transition of transitions) transition.finish() + frame.style.removeProperty('--ds-transition-duration-slow') + return { endpoints: [start.width, end.width], start, middle } + }) + expect(sample.endpoints).toEqual([from, to]) + expect(sample.middle.width).toBeGreaterThan(Math.min(from, to)) + expect(sample.middle.width).toBeLessThan(Math.max(from, to)) + expect(sample.middle.gap).toBeCloseTo(sample.start.gap, 1) +} + +it('overlays the conversation and closes after navigation without losing its sidebar content', async () => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) + const seed = await readFile(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url), 'utf8') + const sessionId = await seedSession(scaffold, seed, 'session-c4421b66-252e-44c0-80ed-6e320abeba25') + await workspace.attachSession(sessionId) + await scaffold.ctx.sessionController.rename({ sessionId, title: 'Drawer navigation' }) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true, locale: 'en-US' }) + const console = watchConsole(page) + await page.goto(scaffold.authenticatedUrl) + const opener = page.getByRole('button', { name: 'Open sidebar', exact: true }) + await opener.waitFor() + const frame = page.locator('[data-sidebar-drawer]') + await expect.poll(() => frame.getAttribute('data-sidebar-collapsed')).toBe('true') + const sidebar = page.locator('[data-slot="sidebar"]') + const original = await sidebar.elementHandle() + const main = page.locator('[data-slot="main"]').locator('..') + const closed = await main.boundingBox() + // A long test-owned duration keeps the transition available until its + // animation clock is sampled and finished explicitly. + await frame.evaluate((el) => { el.style.setProperty('--ds-transition-duration-slow', '100s') }) + await opener.tap() + const drawer = page.getByRole('dialog', { name: 'Navigation', exact: true }) + await drawer.waitFor() + await assertMaskFade(frame, 0, 1) + await expect.poll(() => main.boundingBox()).toEqual(closed) + expect(closed?.width).toBe(390) + expect(await main.evaluate(el => el.closest('[inert]') !== null)).toBe(true) + expect(await page.locator('[data-side="sidebar"]').count()).toBe(0) + const workspaceRow = drawer.locator('[data-row-key^="workspace:"]').first() + const workspaceButtons = workspaceRow.getByRole('button', { includeHidden: true }) + expect(await workspaceRow.getAttribute('aria-expanded')).toBe('true') + expect(await workspaceButtons.count()).toBe(2) + for (const button of await workspaceButtons.all()) await button.waitFor() + await workspaceRow.tap() + expect(await workspaceRow.getAttribute('aria-expanded')).toBe('false') + for (const button of await workspaceButtons.all()) expect(await button.isVisible()).toBe(false) + await workspaceRow.tap() + for (const button of await workspaceButtons.all()) await button.waitFor() + await drawer.getByRole('button', { name: 'Search sessions', exact: true }).tap() + const search = drawer.getByPlaceholder('Search session names') + expect(await search.evaluate(el => getComputedStyle(el).fontSize)).toBe('16px') + await drawer.getByRole('button', { name: 'Clear search', exact: true }).tap() + await frame.evaluate((el) => { el.style.setProperty('--ds-transition-duration-slow', '100s') }) + await page.getByRole('treeitem').filter({ has: page.getByText('Drawer navigation', { exact: true }) }).tap() + await assertMaskFade(frame, 1, 0) + await drawer.waitFor({ state: 'hidden' }) + await page.getByRole('navigation', { name: 'Session hierarchy' }).getByText('Drawer navigation', { exact: true }).waitFor() + await opener.click() + const selectedRow = drawer.getByRole('treeitem', { selected: true }) + const more = selectedRow.getByRole('button', { name: 'Session actions for Drawer navigation', exact: true }) + await more.waitFor() + expect(await selectedRow.getByRole('button', { name: 'Archive session', exact: true }).isVisible()).toBe(false) + expect(await selectedRow.getByRole('button', { name: 'Pin session', exact: true }).isVisible()).toBe(false) + expect(await selectedRow.getByRole('button').count()).toBe(1) + await more.tap() + const menu = page.getByRole('menu') + await menu.getByRole('menuitem', { name: 'Archive session', exact: true }).waitFor() + await menu.getByRole('menuitem', { name: 'Pin session', exact: true }).tap() + await menu.waitFor({ state: 'hidden' }) + await selectedRow.getByLabel('Pinned', { exact: true }).waitFor() + await more.tap() + await menu.getByRole('menuitem', { name: 'Unpin session', exact: true }).tap() + await menu.waitFor({ state: 'hidden' }) + await expect.poll(() => selectedRow.getByLabel('Pinned', { exact: true }).count()).toBe(0) + await drawer.getByRole('button', { name: 'Plugins', exact: true }).tap() + await drawer.waitFor({ state: 'hidden' }) + await page.locator('[data-plugin-panel]').waitFor() + await opener.click() + await drawer.waitFor() + await page.touchscreen.tap(370, 420) + await drawer.waitFor({ state: 'hidden' }) + await opener.click() + await page.keyboard.press('Escape') + await drawer.waitFor({ state: 'hidden' }) + expect(await opener.evaluate(el => el === document.activeElement)).toBe(true) + expect(await sidebar.evaluate((el, previous) => el === previous, original)).toBe(true) + await original?.dispose() + + await page.setViewportSize({ width: 768, height: 844 }) + await expect.poll(() => frame.count()).toBe(0) + await expect.poll(async () => Math.round((await main.boundingBox())!.width)).toBe(712) + await page.setViewportSize({ width: 767, height: 844 }) + await expect.poll(() => frame.count()).toBe(1) + + await page.emulateMedia({ reducedMotion: 'reduce' }) + await opener.tap() + const mask = frame.locator('[data-sidebar-mask]') + expect(await mask.evaluate(el => getComputedStyle(el).opacity)).toBe('1') + expect(await mask.evaluate(el => el.getAnimations().length)).toBe(0) + await drawer.getByRole('button', { name: 'Collapse sidebar', exact: true }).tap() + expect(await mask.evaluate(el => getComputedStyle(el).opacity)).toBe('0') + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await expect.poll(async () => Math.round((await main.boundingBox())!.width)).toBe(767) + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(767) + await page.evaluate(() => { document.documentElement.dataset.platform = 'darwin' }) + await expect.poll(() => main.evaluate(el => getComputedStyle(el).paddingTop)).toBe('0px') + await page.evaluate(() => { delete document.documentElement.dataset.platform }) + await expect.poll(() => main.evaluate(el => getComputedStyle(el).paddingTop)).toBe('48px') + + await page.setViewportSize({ width: 390, height: 844 }) + await drawer.waitFor({ state: 'hidden' }) + await opener.tap() + await drawer.getByRole('button', { name: 'New session', exact: true }).last().tap() + await drawer.waitFor({ state: 'hidden' }) + const home = page.locator('[data-phase="hero"]') + await home.waitFor() + const editor = home.locator('[contenteditable="true"]') + await editor.tap() + const homeEditorBox = await editor.boundingBox() + // Chromium cannot raise a phone keyboard; simulate document panning + // before the visual viewport publishes the matching offset. + const restoreViewport = await page.evaluateHandle(() => { + const viewport = window.visualViewport! + const scrollY = Object.getOwnPropertyDescriptor(window, 'scrollY')! + Object.defineProperty(window, 'scrollY', { configurable: true, value: 80 }) + Object.defineProperties(viewport, { + height: { configurable: true, value: 360 }, + offsetTop: { configurable: true, value: 0 }, + }) + viewport.dispatchEvent(new Event('resize')) + viewport.dispatchEvent(new Event('scroll')) + window.dispatchEvent(new Event('scroll')) + return () => { + Object.defineProperty(window, 'scrollY', scrollY) + Reflect.deleteProperty(viewport, 'height') + Reflect.deleteProperty(viewport, 'offsetTop') + window.dispatchEvent(new Event('scroll')) + viewport.dispatchEvent(new Event('resize')) + } + }) + const root = page.locator('#root') + await expect.poll(() => root.boundingBox()).toEqual({ x: 0, y: 0, width: 390, height: 844 }) + expect(await editor.boundingBox()).toEqual(homeEditorBox) + await page.evaluate(() => { + Object.defineProperty(window.visualViewport!, 'offsetTop', { configurable: true, value: 80 }) + window.visualViewport!.dispatchEvent(new Event('scroll')) + }) + await expect.poll(() => root.boundingBox()).toEqual({ x: 0, y: 0, width: 390, height: 844 }) + await expect.poll(async () => (await main.boundingBox())?.height).toBe(844) + await opener.tap() + await expect.poll(async () => (await drawer.boundingBox())?.height).toBe(844) + const searchWithKeyboard = drawer.getByPlaceholder('Search session names') + await drawer.getByRole('button', { name: 'Search sessions', exact: true }).tap() + await searchWithKeyboard.tap() + await searchWithKeyboard.fill('retained search') + await drawer.getByRole('button', { name: 'Account menu', exact: true }).tap() + await page.getByRole('menuitem', { name: 'Settings', exact: true }).tap() + const settings = page.getByRole('dialog', { name: 'Settings', exact: true }) + await settings.waitFor() + const settingsBox = (await settings.boundingBox())! + expect(settingsBox.x).toBeGreaterThanOrEqual(0) + expect(settingsBox.y).toBeGreaterThanOrEqual(0) + expect(settingsBox.x + settingsBox.width).toBeLessThanOrEqual(390) + expect(settingsBox.y + settingsBox.height).toBeLessThanOrEqual(844) + const closeSettings = settings.getByRole('button', { name: 'Close', exact: true }) + const closeBox = (await closeSettings.boundingBox())! + expect(closeBox.y).toBeGreaterThanOrEqual(0) + expect(closeBox.y + closeBox.height).toBeLessThanOrEqual(844) + await closeSettings.tap() + await settings.waitFor({ state: 'hidden' }) + await expect.poll(() => searchWithKeyboard.inputValue()).toBe('retained search') + await restoreViewport.evaluate((restore) => { restore() }) + await restoreViewport.dispose() + await expect.poll(() => root.boundingBox()).toEqual({ x: 0, y: 0, width: 390, height: 844 }) + await expect.poll(async () => (await drawer.boundingBox())?.height).toBe(844) + await frame.evaluate((el) => { el.scrollLeft = 10 }) + expect(await frame.evaluate(el => el.scrollLeft)).toBe(0) + await expect.poll(() => mask.boundingBox()).toEqual({ x: 0, y: 0, width: 390, height: 844 }) + await expect.poll(() => drawer.evaluate((el) => { + const frame = el.closest('[data-sidebar-drawer]')! + let column = el + while (column.parentElement !== frame) column = column.parentElement! + const { y, height } = column.getBoundingClientRect() + return { y, height } + })).toEqual({ y: 0, height: 844 }) + await expect.poll(async () => (await drawer.boundingBox())?.height).toBe(844) + await page.setViewportSize({ width: 844, height: 390 }) + await expect.poll(async () => (await root.boundingBox())?.height).toBe(390) + await expect.poll(() => frame.count()).toBe(0) + await page.setViewportSize({ width: 390, height: 844 }) + await expect.poll(async () => (await root.boundingBox())?.height).toBe(844) + await expect.poll(() => frame.count()).toBe(1) + + const posture = await page.context().newCDPSession(page) + try { + await page.setViewportSize({ width: 951, height: 669 }) + await expect.poll(() => frame.count()).toBe(0) + await posture.send('Emulation.setDevicePostureOverride', { posture: { type: 'folded' } }) + await opener.tap() + await expect.poll(() => main.boundingBox()).toEqual({ x: 475.5, y: 0, width: 475.5, height: 669 }) + expect(await page.locator('[data-side="sidebar"]').count()).toBe(0) + const foldSearch = page.getByPlaceholder('Search session names') + if (!(await foldSearch.isVisible())) await page.getByRole('button', { name: 'Search sessions', exact: true }).tap() + await foldSearch.fill('fold search') + const wideFrame = page.locator('[data-rightbar-collapsed]') + const collapseSidebar = page.getByRole('button', { name: 'Collapse sidebar', exact: true }) + await wideFrame.evaluate((el) => { el.style.setProperty('--ds-transition-duration-slow', '100s') }) + await posture.send('Emulation.clearDevicePostureOverride') + await assertFoldResize(collapseSidebar, 475.5, 280) + await expect.poll(() => main.boundingBox()).toEqual({ x: 280, y: 0, width: 671, height: 669 }) + expect(await page.locator('[data-side="sidebar"]').count()).toBe(1) + expect(await foldSearch.evaluate(el => el === document.activeElement)).toBe(true) + expect(await foldSearch.inputValue()).toBe('fold search') + await wideFrame.evaluate((el) => { el.style.setProperty('--ds-transition-duration-slow', '100s') }) + await posture.send('Emulation.setDevicePostureOverride', { posture: { type: 'folded' } }) + await assertFoldResize(collapseSidebar, 280, 475.5) + await expect.poll(async () => (await main.boundingBox())?.x).toBe(475.5) + expect(await foldSearch.evaluate(el => el === document.activeElement)).toBe(true) + await page.emulateMedia({ reducedMotion: 'reduce' }) + await posture.send('Emulation.clearDevicePostureOverride') + await expect.poll(async () => (await main.boundingBox())?.x).toBe(280) + // Scroll-driven text fades remain registered even with reduced motion. + expect(await wideFrame.evaluate(el => el.getAnimations({ subtree: true }) + .filter(animation => animation.timeline === document.timeline).length)).toBe(0) + await posture.send('Emulation.setDevicePostureOverride', { posture: { type: 'folded' } }) + await expect.poll(async () => (await main.boundingBox())?.x).toBe(475.5) + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await page.setViewportSize({ width: 669, height: 951 }) + await expect.poll(() => frame.getAttribute('data-sidebar-collapsed')).toBe('true') + await drawer.waitFor({ state: 'hidden' }) + await opener.tap() + await expect.poll(async () => (await drawer.boundingBox())?.width).toBe(280) + expect(await main.boundingBox()).toEqual({ x: 0, y: 0, width: 669, height: 951 }) + } finally { + await posture.detach() + } + + const pointerPage = await browser.newPage({ viewport: { width: 390, height: 844 }, locale: 'en-US' }) + try { + await pointerPage.goto(scaffold.authenticatedUrl) + await pointerPage.getByRole('button', { name: 'Open sidebar', exact: true }).click() + expect(await pointerPage.getByPlaceholder('Search session names').evaluate(el => getComputedStyle(el).fontSize)).toBe('13px') + const pointerWorkspace = pointerPage.locator('[data-row-key^="workspace:"]').first() + const pointerWorkspaceButtons = pointerWorkspace.getByRole('button', { includeHidden: true }) + await pointerWorkspace.click() + expect(await pointerWorkspace.getAttribute('aria-expanded')).toBe('false') + const collapseSidebar = pointerPage.getByRole('button', { name: 'Collapse sidebar', exact: true }) + await collapseSidebar.focus() + await collapseSidebar.hover() + for (const button of await pointerWorkspaceButtons.all()) expect(await button.isVisible()).toBe(false) + await pointerWorkspace.hover() + for (const button of await pointerWorkspaceButtons.all()) await button.waitFor() + await pointerWorkspace.click() + for (const label of ['Collapse sidebar', 'View options']) { + await pointerPage.getByRole('button', { name: label, exact: true }).hover() + const tooltip = pointerPage.getByRole('tooltip').filter({ hasText: label }) + await tooltip.waitFor() + expect(await tooltip.evaluate(el => el.closest('[data-slot="sidebar"]'))).toBeNull() + const box = (await tooltip.boundingBox())! + expect(box.x).toBeGreaterThanOrEqual(12) + expect(box.x + box.width).toBeLessThanOrEqual(378) + } + const pointerRow = pointerPage.getByRole('treeitem').filter({ has: pointerPage.getByText('Drawer navigation', { exact: true }) }) + await pointerRow.click() + await pointerPage.getByRole('dialog', { name: 'Navigation', exact: true }).waitFor({ state: 'hidden' }) + await pointerPage.getByRole('button', { name: 'Open sidebar', exact: true }).click() + await pointerPage.getByRole('button', { name: 'Collapse sidebar', exact: true }).hover() + await expect.poll(() => pointerRow.getByRole('button', { name: 'Session actions for Drawer navigation', exact: true }).isVisible()).toBe(false) + await pointerRow.hover() + for (const label of ['Session actions for Drawer navigation', 'Archive session', 'Pin session']) { + await pointerRow.getByRole('button', { name: label, exact: true }).waitFor() + } + await pointerPage.getByRole('button', { name: 'Collapse sidebar', exact: true }).click() + const pointerDrawer = pointerPage.getByRole('dialog', { name: 'Navigation', exact: true }) + await pointerDrawer.waitFor({ state: 'hidden' }) + await pointerPage.setViewportSize({ width: 767, height: 844 }) + await pointerPage.getByRole('button', { name: 'Open sidebar', exact: true }).press('Enter') + await pointerDrawer.waitFor() + expect(await pointerDrawer.evaluate(el => el.contains(document.activeElement))).toBe(true) + await pointerPage.getByRole('button', { name: 'Search sessions', exact: true }).click() + await expect.poll(() => pointerPage.getByPlaceholder('Search session names') + .evaluate(el => el === document.activeElement)).toBe(true) + await pointerPage.setViewportSize({ width: 768, height: 844 }) + await pointerPage.locator('[data-sidebar-drawer]').waitFor({ state: 'detached' }) + const pointerSidebar = pointerPage.locator('[data-slot="sidebar"]') + await expect.poll(() => pointerSidebar.getByRole('button', { name: 'New session', exact: true }).count()).toBe(1) + const railToggle = pointerSidebar.getByRole('button', { name: 'Open sidebar', exact: true }) + expect(await railToggle.evaluate(el => el === document.activeElement)).toBe(true) + } finally { + await pointerPage.close() + } + expect(console.pageErrors).toEqual([]) + expect(console.warnings).toEqual([]) + const result = [ + '390px: closed sidebar has no rail; main width 390px', + 'open: main geometry retained; background inert; no resize handle', + 'close: Session navigation, Plugins navigation, mask and Escape', + 'retained: sidebar DOM and opener focus', + '768px: 56px rail; main width 712px; drawer focus transfers to the rail toggle', + 'breakpoint motion: collapsed rail hides immediately and returns compact without crossfades; expanded sidebar and explicit toggles retain their slides', + '767px: hidden drawer; main width 767px; no page overflow', + 'global panels: browser top inset 48px; macOS keeps its existing clearance', + 'tooltips: sidebar and workspace controls escape the drawer and fit the viewport', + 'search input: 16px on touch; 13px with a fine pointer', + 'simulated keyboard: homepage and drawer retain 844px layout height without following the 360px visual viewport; Settings stays within the viewport', + 'keyboard close: layout height stays 844px; sidebar search retained; Settings close remains reachable', + 'shell coverage: drawer backing and mask cover 844px without synthetic safe-area insets', + 'rotation: 844x390 then 390x844 restores shell height and sidebar breakpoint', + 'folded landscape: 951px frame splits at 475.5px without a resize handle; unfolding restores 280px and search focus; portrait retains the drawer', + 'fold transitions: sidebar controls follow the divider in both directions; reduced motion changes width without animation', + 'drawer mask: opacity transitions from 0 to 1 on open and 1 to 0 on close', + 'reduced motion: drawer and mask settle without transitions', + 'touch selected Session: More remains visible; archive and pin stay in its menu; pin marker retained', + 'touch Workspace: actions appear only while expanded, including after folding the focused row', + 'fine pointer: folded Workspace actions remain available on hover', + 'fine pointer: selected Session actions stay hidden until hover, including at 390px', + ].join('\n') + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/sidebar-drawer.expected.md', import.meta.url)), result, webSnapshotMode()) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) + +it('dismisses retained sidebar menus at the drawer breakpoint and preserves their rows', async () => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) + const seed = await readFile(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url), 'utf8') + const sessionId = await seedSession(scaffold, seed, 'session-c4421b66-252e-44c0-80ed-6e320abeba25') + await workspace.attachSession(sessionId) + await scaffold.ctx.sessionController.rename({ sessionId, title: 'Menu regression' }) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 1024, height: 844 }, locale: 'en-US' }) + await page.goto(scaffold.authenticatedUrl) + const row = page.locator(`[data-row-key="session:${sessionId}"]`) + await row.waitFor() + const original = await row.elementHandle() + for (const label of ['View options', 'Session actions for Menu regression']) { + await page.setViewportSize({ width: 1024, height: 844 }) + await page.getByRole('button', { name: 'Collapse sidebar', exact: true }).waitFor() + if (label.startsWith('Session')) await row.hover() + await page.getByRole('button', { name: label, exact: true }).click() + await page.getByRole('menu').waitFor() + await page.setViewportSize({ width: 767, height: 844 }) + await page.getByRole('menu').waitFor({ state: 'hidden' }) + const opener = page.getByRole('button', { name: 'Open sidebar', exact: true }) + await expect.poll(() => opener.evaluate(element => element === document.activeElement)).toBe(true) + await opener.click() + await row.waitFor() + expect(await row.evaluate((element, before) => element === before, original)).toBe(true) + } + await original?.dispose() + await compareOrRefreshGolden(fileURLToPath(new URL('./expected/sidebar-menu-dismissal.expected.md', import.meta.url)), [ + 'View options and Session menus close when the sidebar becomes an inert drawer.', + 'Focus returns to the visible sidebar opener; retained Session rows keep their DOM identity.', + ].join('\n'), webSnapshotMode()) + } finally { await browser.close() } + } finally { await scaffold.close() } +}) + +it('keeps drawer shortcuts and hit targets above fullscreen and floating right panels', async () => { + const scaffold = await launchWebScaffold({ + extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)), + }) + try { + const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd) + const seed = await readFile(new URL('../../../snapshots/web/seeded-history/session.v3.jsonl', import.meta.url), 'utf8') + const sessionId = await seedSession(scaffold, seed, 'session-c4421b66-252e-44c0-80ed-6e320abeba25') + await workspace.attachSession(sessionId) + await scaffold.ctx.sessionController.rename({ sessionId, title: 'Drawer overlay checks' }) + const browser = await chromium.launch() + try { + const page = await browser.newPage({ viewport: { width: 1280, height: 844 }, locale: 'en-US' }) + await page.addInitScript(() => { Object.defineProperty(navigator, 'platform', { value: 'MacIntel' }) }) + await page.goto(scaffold.authenticatedUrl) + const row = page.getByRole('treeitem').filter({ has: page.getByText('Drawer overlay checks', { exact: true }) }) + await row.click() + await page.locator('[data-sidebar-right-expand]').click() + await page.locator('[data-sidebar-right-guide-entry="files"]').click() + const panel = page.locator('[data-sidebar-right-open]') + const primary = await page.evaluate(() => /mac/i.test(navigator.platform) ? 'Meta' : 'Control') + const toggle = `${primary}+Alt+b` + await row.hover() + const card = page.getByRole('button', { name: 'Copy: Drawer overlay checks', exact: true }) + await card.waitFor() + await page.setViewportSize({ width: 390, height: 844 }) + await card.waitFor({ state: 'hidden' }) + expect(await row.count()).toBe(1) + const drawer = page.getByRole('dialog', { name: 'Navigation', exact: true }) + await expect.poll(() => panel.getAttribute('data-sidebar-right-panel')).toBe('fullscreen') + const assertAboveRightPanel = async (coveredPoint?: { x: number; y: number }) => { + await page.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor() + await page.keyboard.press(toggle) + await drawer.waitFor() + const collapse = drawer.getByRole('button', { name: 'Collapse sidebar', exact: true }) + await expect.poll(() => collapse.evaluate(el => document.activeElement === el)).toBe(true) + await expect.poll(() => drawer.evaluate((el) => { + const box = el.getBoundingClientRect() + return el.contains(document.elementFromPoint(box.left + 140, 30)) + })).toBe(true) + expect(await page.evaluate(() => document.elementFromPoint(380, 420)?.hasAttribute('data-sidebar-mask'))).toBe(true) + if (coveredPoint !== undefined) { + expect(await drawer.evaluate((el, point) => { + const hit = document.elementFromPoint(point.x, point.y) + return el.contains(hit) || hit?.hasAttribute('data-sidebar-mask') + }, coveredPoint)).toBe(true) + } + await page.keyboard.press(`${primary}+Alt+k`) + await expect.poll(() => drawer.getByPlaceholder('Search session names').evaluate(el => document.activeElement === el)).toBe(true) + await page.keyboard.press(toggle) + await drawer.waitFor({ state: 'hidden' }) + expect(await panel.evaluate(el => el.closest('[inert]') === null)).toBe(true) + } + await page.keyboard.press(`${primary}+Alt+k`) + await drawer.waitFor() + await expect.poll(() => drawer.getByPlaceholder('Search session names') + .evaluate(el => el === document.activeElement)).toBe(true) + await page.keyboard.press(toggle) + await drawer.waitFor({ state: 'hidden' }) + await assertAboveRightPanel() + await page.setViewportSize({ width: 1280, height: 844 }) + await expect.poll(() => panel.getAttribute('data-sidebar-right-panel')).toBe('push') + const tab = panel.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }) + const bounds = (await tab.boundingBox())! + await page.mouse.move(bounds.x + 6, bounds.y + bounds.height / 2) + await page.mouse.down() + try { + await page.mouse.move(190, 400, { steps: 8 }) + } finally { await page.mouse.up() } + const floating = page.locator('[data-dockkit-float]') + await floating.waitFor() + await page.setViewportSize({ width: 390, height: 844 }) + const box = (await floating.boundingBox())! + expect(box.x).toBeLessThan(390) + expect(box.x + box.width).toBeGreaterThan(0) + const point = { x: (Math.max(0, box.x) + Math.min(390, box.x + box.width)) / 2, y: box.y + 40 } + await expect.poll(() => floating.evaluate((el, at) => el.contains(document.elementFromPoint(at.x, at.y)), point)).toBe(true) + await assertAboveRightPanel(point) + } finally { + await browser.close() + } + } finally { + await scaffold.close() + } +}) diff --git a/apps/web/tests/stats-truncated-tooltip.e2e.ts b/apps/web/tests/stats-truncated-tooltip.e2e.ts index 18e7d5e64c..fc3e25b419 100644 --- a/apps/web/tests/stats-truncated-tooltip.e2e.ts +++ b/apps/web/tests/stats-truncated-tooltip.e2e.ts @@ -92,7 +92,7 @@ describe('web e2e: truncated composer statistics', () => { const cut = () => label.evaluate(element => element.scrollWidth > element.clientWidth) expect(await cut()).toBe(false) - await page.setViewportSize({ width: 390, height: 900 }) + await page.setViewportSize({ width: 334, height: 900 }) await expect.poll(cut).toBe(true) await usagePill.hover() await expect.poll(() => tooltip.textContent()).toBe(USAGE_READING) diff --git a/apps/web/tests/support.ts b/apps/web/tests/support.ts index 953f701fc9..ad741f474d 100644 --- a/apps/web/tests/support.ts +++ b/apps/web/tests/support.ts @@ -200,6 +200,23 @@ export function probeFreePort(): Promise { }) } +/** + * Open collapsed mobile navigation before using a sidebar action. + * @param page - browser page with the mounted sidebar. + * @param locale - current UI language. + */ +export async function revealNavigationDrawer(page: Page, locale: 'en' | 'zh' | 'ja'): Promise { + const drawer = await page.evaluate(() => window.innerWidth < 768 + && !document.documentElement.hasAttribute('data-windows-titlebar')) + await page.waitForFunction(expected => Boolean(document.querySelector('[data-sidebar-drawer]')) === expected, drawer) + const closed = page.locator('[data-sidebar-drawer][data-sidebar-collapsed]') + if (await closed.count() === 0) return + await page.locator('[data-shell-leading]').getByRole('button', { + name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く' }[locale], exact: true, + }).click() + await closed.waitFor({ state: 'detached' }) +} + /** * Drive the hero's workspace picker through the composed directory dialog * until the live composer unlocks. A fresh world has no Workspace, so the boot @@ -219,6 +236,7 @@ export function probeFreePort(): Promise { */ export async function connectFreshWorkspace(page: Page, root: string, name = 'workspace'): Promise { mkdirSync(join(root, name), { recursive: true }) + await revealNavigationDrawer(page, 'en') await page.getByRole('button', { name: 'Add workspace', exact: true }).click() const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' }) await dialog.waitFor({ timeout: 10_000 }) @@ -245,6 +263,7 @@ export async function connectFreshWorkspace(page: Page, root: string, name = 'wo */ export async function connectFreshWorkspaceZh(page: Page, root: string, name = 'workspace', modelAvailable = true): Promise { mkdirSync(join(root, name), { recursive: true }) + await revealNavigationDrawer(page, 'zh') await page.getByRole('button', { name: '添加工作区', exact: true }).click() const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) await dialog.waitFor({ timeout: 10_000 }) @@ -346,6 +365,14 @@ export function conversationContextKey(kind: string, id: string): string { */ export async function openSettings(page: Page, locale: 'en' | 'zh' | 'ja'): Promise { const labels = { en: ['Account menu', 'Settings'], zh: ['账号菜单', '设置'], ja: ['アカウントメニュー', '設定'] } as const - await page.getByRole('button', { name: labels[locale][0], exact: true }).click() + const trigger = page.getByRole('button', { + name: labels[locale][0], exact: true, includeHidden: true, + }) + await trigger.waitFor({ state: 'attached' }) + await revealNavigationDrawer(page, locale) + if (!await trigger.isVisible()) { + await page.getByRole('button', { name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く' }[locale], exact: true }).click() + } + await trigger.click() await page.getByRole('menuitem', { name: labels[locale][1], exact: true }).click() } diff --git a/apps/web/tests/window-drag-coverage.e2e.ts b/apps/web/tests/window-drag-coverage.e2e.ts index 87c468a901..70fd84f7a1 100644 --- a/apps/web/tests/window-drag-coverage.e2e.ts +++ b/apps/web/tests/window-drag-coverage.e2e.ts @@ -107,10 +107,10 @@ async function collectedRegions(page: Page, selector: string): Promise { const top = document.elementFromPoint(x, y) - // A pane's programmatic focus target also contains its window-drag strip. - // The strip owns those pixels; controls inside it still need their own subtraction. - const strip = top?.closest('[data-dockkit-strip][data-window-drag]') - if (element.matches('[data-dockkit-pane][tabindex="-1"]') + // Panes and the navigation dialog contain their own window-drag rows. + // Those rows own their pixels; controls inside still subtract themselves. + const strip = top?.closest('[data-window-drag]') + if (element.matches('[data-dockkit-pane][tabindex="-1"], [data-shortcut-modal="sidebar"][role="dialog"]') && strip != null && element.contains(strip)) return false return top !== null && (top === element || element.contains(top)) }) @@ -503,6 +503,32 @@ describe('web e2e: macOS window drag coverage', () => { } }, 120_000) + it('keeps the drawer titlebar draggable without swallowing its close button', async () => { + const { page, tripwire } = await desktopPage() + try { + await page.setViewportSize({ width: 571, height: 696 }) + await page.locator('[data-sidebar-drawer][data-sidebar-collapsed]').waitFor() + await page.locator('[data-shell-leading]').getByRole('button', { name: 'Open sidebar', exact: true }).click() + const drawer = page.getByRole('dialog', { name: 'Navigation', exact: true }) + await drawer.waitFor() + await settled(page) + const toggle = drawer.getByRole('button', { name: 'Collapse sidebar', exact: true }) + const button = (await toggle.boundingBox())! + const seat = await rectOf(page, '[data-shell-leading]') + const regions = await collectedRegions(page, INTERACTIVE_SELECTOR) + const y = button.y + button.height / 2 + expect(isDraggableAt(regions, seat.x + seat.width / 2, y), 'the inactive header controls behind the drawer').toBe(true) + expect(isDraggableAt(regions, (seat.x + seat.width + button.x) / 2, y), 'the gap before the close button').toBe(true) + expect(isDraggableAt(regions, button.x + button.width / 2, y), 'the close button').toBe(false) + expect(swallowedBoxes(regions)).toEqual([]) + await toggle.click() + await drawer.waitFor({ state: 'hidden' }) + expect(tripwire.pageErrors).toEqual([]) + } finally { + await page.close() + } + }) + it('keeps an entry page’s chrome row draggable', async () => { const { page, tripwire } = await desktopPage() try { diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index 44dcc4fbdd..c653301218 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -23,6 +23,7 @@ // this client-registered project must not also hold them (one program // cannot see both sides of the cordis Context merges). "exclude": [ + "tests/sidebar-drawer.e2e.ts", "tests/creation-recommendations.e2e.ts", "tests/plugin-recommendations.e2e.ts", "tests/japanese-plugin-metadata.e2e.ts", diff --git a/benchmarks/session-corpus/README.i18n.yaml b/benchmarks/session-corpus/README.i18n.yaml index 2162840b3e..5e02d08e37 100644 --- a/benchmarks/session-corpus/README.i18n.yaml +++ b/benchmarks/session-corpus/README.i18n.yaml @@ -12,8 +12,8 @@ en: 66a769ce60d49ff3 zh: 7e0bfa7c598157fa /session-corpus-benchmarks/run: - en: 2560e832041ae481 - zh: 2fbbff71135e52ab + en: c770082e58aa8194 + zh: 339d659595a1f97d /session-corpus-benchmarks/measurements: en: c357c231c3bfb588 zh: 3d901a2caccf2587 diff --git a/benchmarks/session-corpus/README.md b/benchmarks/session-corpus/README.md index d504417d77..f55fc563ec 100644 --- a/benchmarks/session-corpus/README.md +++ b/benchmarks/session-corpus/README.md @@ -18,7 +18,7 @@ Measure the Web Host's Session list, content search, and fork over synthetic cor From the repository root, build the libraries and workers with `pnpm run build:bench`, then run `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/session-corpus/session-corpus.bench.ts`. Do not overlap timing runs with builds or other benchmarks. Seeding writes about 1.5 GB of Zstandard logs under a private temporary root, which the test removes after success or failure. -The test reports every fresh-process sample, the CPU model, available parallelism, platform, and Node version, and enforces median budgets. Its last case fails when the file, including seeding, exceeds five minutes. A failed worker reports its exit, signal, timeout, and stderr tail. The required benchmark lane discovers this file automatically. +The test reports every fresh-process sample, the CPU model, available parallelism, platform, and Node version, and enforces median budgets. Its last case fails when the file, including seeding, exceeds five minutes. Fork workers use a fixed V8 heap limit; peak RSS still measures the whole process. A failed worker reports its exit, signal, timeout, and stderr tail. The required benchmark lane discovers this file automatically. diff --git a/benchmarks/session-corpus/README.zh.md b/benchmarks/session-corpus/README.zh.md index 1077b5233e..e7b1f1586a 100644 --- a/benchmarks/session-corpus/README.zh.md +++ b/benchmarks/session-corpus/README.zh.md @@ -18,7 +18,7 @@ 在仓库根目录使用 `pnpm run build:bench` 构建库和 worker,然后运行 `pnpm exec vitest run --config vitest.bench.config.ts benchmarks/session-corpus/session-corpus.bench.ts`。不要让计时运行与构建或其他基准重叠。播种过程会在私有临时根目录下写入约 1.5 GB 的 Zstandard 日志,测试成功或失败后都会删除该目录。 -测试报告每个新进程样本、CPU 型号、可用并行度、平台和 Node 版本,并约束中位数预算。当整个文件(包括播种)超过五分钟时,最后一个用例失败。worker 失败时报告退出状态、信号、超时和 stderr 末尾。必需基准通道自动发现此文件。 +测试报告每个新进程样本、CPU 型号、可用并行度、平台和 Node 版本,并约束中位数预算。当整个文件(包括播种)超过五分钟时,最后一个用例失败。Fork worker 使用固定的 V8 堆上限;峰值 RSS 仍测量整个进程。worker 失败时报告退出状态、信号、超时和 stderr 末尾。必需基准通道自动发现此文件。 diff --git a/benchmarks/session-corpus/session-corpus.bench.ts b/benchmarks/session-corpus/session-corpus.bench.ts index 00bc2d2979..3bbb66809c 100644 --- a/benchmarks/session-corpus/session-corpus.bench.ts +++ b/benchmarks/session-corpus/session-corpus.bench.ts @@ -29,6 +29,8 @@ const CORPUS = { search: 1_000, fork: 1_000, list: 3_000 } as const const FILE_LIMIT_MS = 300_000 /** Per-child deadline: an endpoint slower than its budget still reports a measurement instead of a kill. */ const WORKER_TIMEOUT_MS = FILE_LIMIT_MS +/** Fixed old-space capacity makes fork RSS comparable across hosted V8 heap defaults. */ +const FORK_HEAP_LIMIT_MB = 512 /** Fresh processes per list and fork-strata scenario; the median enforces each budget. */ const ATTEMPTS = { list: 3, fork: 3 } as const /** Concurrent anchor-preparation processes; standard hosted runners have two CPUs. */ @@ -119,7 +121,10 @@ function serialDeadline(workers: number): number { } async function run(args: readonly string[]): Promise { - const outcome = await runBuiltBenchmarkWorker({ worker: WORKER, args, timeoutMs: WORKER_TIMEOUT_MS, exposeGc: true }) + const outcome = await runBuiltBenchmarkWorker({ + worker: WORKER, args, timeoutMs: WORKER_TIMEOUT_MS, exposeGc: true, + ...(args[1] === 'fork' ? { heapLimitMb: FORK_HEAP_LIMIT_MB } : {}), + }) if (outcome.report === undefined) { const stderr = outcome.stderr.trim().split('\n').slice(-20).join('\n') throw new Error(`session-corpus worker ${args[1] ?? ''} failed: exit=${String(outcome.exitCode)}, ` diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index afeba74d2c..69805a5895 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: fb590ba0e99cef86 - zh: 1acbf97138a4ec37 + en: 6dfe441b758583b2 + zh: fb28de0533f07432 diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 84d110253e..e42fc5d08e 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -84,9 +84,10 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_session_log_deepseek["session-log-deepseek"] + svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] svc_deepseekLlmApiExtensions["ctx.deepseekLlmApiExtensions
Official DeepSeek request extensions"] - pkg_session_log_deepseek["session-log-deepseek"] pkg_plugin_package_inventory_deepseek["plugin-package-inventory-deepseek"] pkg_token_meter["token-meter"] svc_tokenMeter["ctx.tokenMeter
Replay token measurement"] @@ -422,6 +423,7 @@ flowchart LR pkg_schedule --> svc_schedule pkg_session --> svc_sessions pkg_session_log_deepseek --> svc_deepseekLlmApiExtensions + pkg_session_log_deepseek --> svc_sessionLogDeepSeek pkg_session_persistence --> svc_sessionPersistence pkg_session_persistence_jsonl --> svc_sessionPersistence pkg_session_projection --> svc_sessionProjections @@ -672,6 +674,7 @@ flowchart LR | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. | | `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | Adapters register provider implementations; the loop and compaction call the provider-neutral stream service. | +| `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | Plugins register caller-owned exclusions before the canonical Session-log request contribution is prepared; unmatched requests use normal upload eligibility. | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | Plugins prepare independent top-level fields; the official adapter merges them and commits their delivery state after HTTP acceptance. | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Owns isolated per-session replay folds; pressure consumers share immutable revisioned measurements. | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | Rewrites oversized current tool results through replayable single-node surface replacements before summary compaction. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index c5f6706993..f434835133 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -86,9 +86,10 @@ flowchart LR pkg_llm_replay["llm-replay"] pkg_agent_loop["agent-loop"] pkg_compaction_basic["compaction-basic"] + pkg_session_log_deepseek["session-log-deepseek"] + svc_sessionLogDeepSeek["ctx.sessionLogDeepSeek
Session-log upload policy"] pkg_deepseek_llm_api_extensions["deepseek-llm-api-extensions"] svc_deepseekLlmApiExtensions["ctx.deepseekLlmApiExtensions
Official DeepSeek request extensions"] - pkg_session_log_deepseek["session-log-deepseek"] pkg_plugin_package_inventory_deepseek["plugin-package-inventory-deepseek"] pkg_token_meter["token-meter"] svc_tokenMeter["ctx.tokenMeter
Replay token measurement"] @@ -424,6 +425,7 @@ flowchart LR pkg_schedule --> svc_schedule pkg_session --> svc_sessions pkg_session_log_deepseek --> svc_deepseekLlmApiExtensions + pkg_session_log_deepseek --> svc_sessionLogDeepSeek pkg_session_persistence --> svc_sessionPersistence pkg_session_persistence_jsonl --> svc_sessionPersistence pkg_session_projection --> svc_sessionProjections @@ -674,6 +676,7 @@ flowchart LR | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 | | `ctx.llm` | `seam` | [`llm`](../packages/llm/llm) | [`llm-deepseek`](../packages/llm/llm-deepseek), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-replay`](../packages/test-support/llm-replay) | [`agent-loop`](../packages/core/agent-loop), [`compaction-basic`](../packages/compaction/compaction-basic) | - | 适配器注册提供方实现;agent loop(智能体循环)与压缩功能调用提供方无关的流服务。 | +| `ctx.sessionLogDeepSeek` | `core` | [`session-log-deepseek`](../packages/session/session-log-deepseek) | - | - | - | 插件在准备权威 Session 日志请求贡献前注册归调用方所有的排除条件;没有条件匹配的请求应用普通上传资格判断。 | | `ctx.deepseekLlmApiExtensions` | `seam` | [`deepseek-llm-api-extensions`](../packages/llm/deepseek-llm-api-extensions) | [`session-log-deepseek`](../packages/session/session-log-deepseek), [`plugin-package-inventory-deepseek`](../packages/llm/plugin-package-inventory-deepseek) | [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 插件准备彼此独立的顶层字段;官方适配器会合并这些字段,并在 HTTP 接受后提交其交付状态。 | | `ctx.tokenMeter` | `core` | [`token-meter`](../packages/llm/token-meter) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 拥有按会话隔离的回放折叠区;压力消费方共享不可变且带修订版本的测量结果。 | | `ctx.toolResultPruner` | `core` | [`compaction-tool-result-pruner`](../packages/compaction/compaction-tool-result-pruner) | - | [`compaction-basic`](../packages/compaction/compaction-basic) | - | 在摘要压缩前,通过可回放的单节点表层替换来改写过大的当前工具结果。 | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 9b409c6b55..ca0dc021f1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -729,7 +729,7 @@ export interface Config { ## `@deepseek-ai/dsh-compaction-basic` - `inject`: `llm` · `tokenMeter` · `sessions` -- `source`: [`packages/compaction/compaction-basic/src/types.ts:40`](../packages/compaction/compaction-basic/src/types.ts) +- `source`: [`packages/compaction/compaction-basic/src/types.ts:46`](../packages/compaction/compaction-basic/src/types.ts) ```ts config-catalog /** Basic compaction configuration with an optional exact-target policy table. */ @@ -1126,7 +1126,7 @@ export type Config = CuaConfig ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:205`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:230`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -2997,7 +2997,7 @@ export interface JsonRpcConfig { - `inject`: `deepseekLlmApiExtensions` · `sessions` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/session/session-log-deepseek/src/index.ts:39`](../packages/session/session-log-deepseek/src/index.ts) +- `source`: [`packages/session/session-log-deepseek/src/index.ts:47`](../packages/session/session-log-deepseek/src/index.ts) ```ts config-catalog /** Session-log request contribution configuration. */ diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 25094e00e3..2b9d252a52 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -731,7 +731,7 @@ export interface Config { ## `@deepseek-ai/dsh-compaction-basic` - `inject`: `llm` · `tokenMeter` · `sessions` -- `source`: [`packages/compaction/compaction-basic/src/types.ts:40`](../packages/compaction/compaction-basic/src/types.ts) +- `source`: [`packages/compaction/compaction-basic/src/types.ts:46`](../packages/compaction/compaction-basic/src/types.ts) ```ts config-catalog /** Basic compaction configuration with an optional exact-target policy table. */ @@ -1128,7 +1128,7 @@ export type Config = CuaConfig ## `@deepseek-ai/dsh-experimental-forge` -- `source`: [`packages/experimental/forge/src/types.ts:205`](../packages/experimental/forge/src/types.ts) +- `source`: [`packages/experimental/forge/src/types.ts:230`](../packages/experimental/forge/src/types.ts) ```ts config-catalog /** Poll cadence and fetch deadline for watched change requests. */ @@ -2999,7 +2999,7 @@ export interface JsonRpcConfig { - `inject`: `deepseekLlmApiExtensions` · `sessions` - `refs`: `Volatile` (`@deepseek-ai/cordis`) -- `source`: [`packages/session/session-log-deepseek/src/index.ts:39`](../packages/session/session-log-deepseek/src/index.ts) +- `source`: [`packages/session/session-log-deepseek/src/index.ts:47`](../packages/session/session-log-deepseek/src/index.ts) ```ts config-catalog /** Session-log request contribution configuration. */ diff --git a/docs/deepseek-llm-api-wire-extensions.i18n.yaml b/docs/deepseek-llm-api-wire-extensions.i18n.yaml index 79b48d6dc5..c5248fa3f7 100644 --- a/docs/deepseek-llm-api-wire-extensions.i18n.yaml +++ b/docs/deepseek-llm-api-wire-extensions.i18n.yaml @@ -9,8 +9,8 @@ en: 1da81051addc4b47 zh: 3e8d7cd3f8c1cdba /official-deepseek-llm-api-wire-extensions/request-headers: - en: 740e92e903ecb594 - zh: f934d3c9e5c56bfe + en: d3d6a2c8240b80e9 + zh: debf42ed01233728 /official-deepseek-llm-api-wire-extensions/body-extension-transaction: en: 48001cfd1281a23b zh: d410530ae8aa2823 @@ -18,8 +18,8 @@ en: f89059050613f3e8 zh: da5cf2a4eeb81b75 /official-deepseek-llm-api-wire-extensions/dsh-session-log: - en: de1a3f2c377d74e3 - zh: 7c803345f71117c5 + en: 0d033f72951e2920 + zh: 767efca0dc39ac03 /official-deepseek-llm-api-wire-extensions/dsh-session-log/wire-session-header: en: ccd8fcd773df21c4 zh: 7ea020068ad093ae diff --git a/docs/deepseek-llm-api-wire-extensions.md b/docs/deepseek-llm-api-wire-extensions.md index 1a30f7c463..e9a270d98e 100644 --- a/docs/deepseek-llm-api-wire-extensions.md +++ b/docs/deepseek-llm-api-wire-extensions.md @@ -28,7 +28,7 @@ The [`DeepSeekLlmApiExtensionRegistry`](../packages/llm/deepseek-llm-api-extensi | `x-deepseek-harness-session-id` | Model requests carrying a Session id | The exact request `sessionId` string | | `x-deepseek-harness-compact` | Model requests whose purpose is `compaction` | The literal string `1` | -Credential failure happens before anonymous-user-id resolution, so an unauthorized request neither sends these headers nor creates the identity file. A direct request without a Session omits `x-deepseek-harness-session-id`. Session-title requests have no additional purpose header; the ordinary Session-id rule still applies when one carries a `sessionId`. +Credential failure happens before anonymous-user-id resolution, so an unauthorized request neither sends these headers nor creates the identity file. A direct request without a Session omits `x-deepseek-harness-session-id`. Session-title and Auto review requests have no additional purpose header; the ordinary Session-id rule still applies when one carries a `sessionId`. ## Body-extension transaction @@ -73,7 +73,7 @@ An enabled inventory with no qualifying entries sends `packages: []`; disabling ## `dsh_session_log` -[`@deepseek-ai/dsh-session-log-deepseek`](../packages/session/session-log-deepseek/README.md) contributes one contiguous suffix of the canonical Session log. The field is enabled by default. It applies to a request with a live Session and at least one event; a direct request, a stale Session id, or an empty log omits the field, as does a request whose first pending event alone exceeds `maxBytes` or cannot be serialized; a composition disables it with `enabled: false`. The examples below use logical Session format 2 only to illustrate the wire fields; they do not identify the [current writer format](session-format-status.md). +[`@deepseek-ai/dsh-session-log-deepseek`](../packages/session/session-log-deepseek/README.md) contributes one contiguous suffix of the canonical Session log. The field is enabled by default. It applies to a request with a live Session and at least one event; a direct request, a stale Session id, an empty log, or a request matched by a registered upload exclusion omits the field, as does a request whose first pending event alone exceeds `maxBytes` or cannot be serialized; a composition disables it with `enabled: false`. The examples below use logical Session format 2 only to illustrate the wire fields; they do not identify the [current writer format](session-format-status.md). ```json { diff --git a/docs/deepseek-llm-api-wire-extensions.zh.md b/docs/deepseek-llm-api-wire-extensions.zh.md index dcccecc6a7..d498e8f951 100644 --- a/docs/deepseek-llm-api-wire-extensions.zh.md +++ b/docs/deepseek-llm-api-wire-extensions.zh.md @@ -28,7 +28,7 @@ | `x-deepseek-harness-session-id` | 携带会话 id 的模型请求 | 确切的请求 `sessionId` 字符串 | | `x-deepseek-harness-compact` | 用途为 `compaction` 的模型请求 | 字面字符串 `1` | -凭据失败发生在解析匿名用户 id 之前,因此未授权请求既不会发送这些标头,也不会创建身份文件。没有会话的直接请求会省略 `x-deepseek-harness-session-id`。会话标题请求没有额外的用途标头;请求携带 `sessionId` 时,仍然适用普通的会话 id 规则。 +凭据失败发生在解析匿名用户 id 之前,因此未授权请求既不会发送这些标头,也不会创建身份文件。没有会话的直接请求会省略 `x-deepseek-harness-session-id`。会话标题请求和 Auto 审查请求没有额外的用途标头;请求携带 `sessionId` 时,仍然适用普通的会话 id 规则。 ## 正文扩展事务 @@ -73,7 +73,7 @@ ## `dsh_session_log` -[`@deepseek-ai/dsh-session-log-deepseek`](../packages/session/session-log-deepseek/README.zh.md) 贡献权威会话日志的一段连续后缀。该字段默认启用。它适用于携带存活会话且至少存在一个事件的请求;直接请求、陈旧会话 id 或空日志会省略该字段,第一条待发事件本身超过 `maxBytes` 或无法序列化的请求也会省略该字段;组合可用 `enabled: false` 禁用它。下方示例使用逻辑 Session 格式 2 仅为说明协议字段,并不标识[当前写入格式](session-format-status.zh.md)。 +[`@deepseek-ai/dsh-session-log-deepseek`](../packages/session/session-log-deepseek/README.zh.md) 贡献权威会话日志的一段连续后缀。该字段默认启用。它适用于携带存活会话且至少存在一个事件的请求;直接请求、陈旧会话 id、空日志或命中已注册上传排除条件的请求会省略该字段,第一条待发事件本身超过 `maxBytes` 或无法序列化的请求也会省略该字段;组合可用 `enabled: false` 禁用它。下方示例使用逻辑 Session 格式 2 仅为说明协议字段,并不标识[当前写入格式](session-format-status.zh.md)。 ```json { diff --git a/docs/persistence-catalog.i18n.yaml b/docs/persistence-catalog.i18n.yaml index cc139495c8..dce8443743 100644 --- a/docs/persistence-catalog.i18n.yaml +++ b/docs/persistence-catalog.i18n.yaml @@ -186,14 +186,14 @@ en: 6c6a27578dff5828 zh: 9a5add2bc0df2d0a /session-persistence-event-catalog/events/session/session-title-llm-request-log-only: - en: 50d9e29d3d2bfe52 - zh: 3ff1d959cf7776b9 + en: 59b02baa2be32ca0 + zh: 3637c99652ca89cf /session-persistence-event-catalog/events/session-log-deepseek: en: 7b827672c80aecdd zh: 7b827672c80aecdd /session-persistence-event-catalog/events/session-log-deepseek/session-log-deepseek-delivery-accepted-log-only: - en: 4e9ce9182ec05808 - zh: 7f643a6756ec8f76 + en: a3e2059fcc540b64 + zh: cc9933fd677560f0 /session-persistence-event-catalog/events/step: en: bd0dcbbc352b771a zh: bd0dcbbc352b771a @@ -1209,8 +1209,8 @@ en: 1f9f610fa0e05abf zh: 11560710a1b871de /session-persistence-event-catalog/resolved-persistence-types/sessiontitlellmrequesteventdata: - en: aed2a9c4310d2cb8 - zh: 5d96d69c322286ec + en: 465fe144e60dd62f + zh: 29e1029426106c3b /session-persistence-event-catalog/resolved-persistence-types/sessiontitlemodelidentity: en: 9531468264499498 zh: 9da23c0ad2776563 @@ -1932,8 +1932,8 @@ en: 04b34b8ffe7e7764 zh: a792d5371516fd9d /session-persistence-event-catalog/resolved-persistence-types/sessionformatversion-sessionid-throughseq: - en: 8aaa02b06896492d - zh: 4dd0e1ee40d8f22d + en: 8063597183ef767f + zh: b064698c54089f07 /session-persistence-event-catalog/resolved-persistence-types/shadowedrange-shadowedseqs-shadowedtokencount: en: 7a2ab7b62244f43b zh: 1084e3f8876feebc diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 303b628cd1..96128feabb 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -878,7 +878,7 @@ Source: [`packages/session/session-title/src/index.ts:77`](../packages/session/s Types: [SessionTitleLlmRequestEventData](subsystems/session-title.md) -Source: [`packages/session/session-title-llm/src/index.ts:57`](../packages/session/session-title-llm/src/index.ts) +Source: [`packages/session/session-title-llm/src/index.ts:63`](../packages/session/session-title-llm/src/index.ts) ### `session-log-deepseek/*` @@ -898,7 +898,7 @@ Source: [`packages/session/session-title-llm/src/index.ts:57`](../packages/sessi } ``` -Source: [`packages/session/session-log-deepseek/src/types.ts:81`](../packages/session/session-log-deepseek/src/types.ts) +Source: [`packages/session/session-log-deepseek/src/types.ts:96`](../packages/session/session-log-deepseek/src/types.ts) ### `step/*` @@ -4709,7 +4709,7 @@ Sources: [`packages/session/session-title/src/types.ts:41`](../packages/session/ SHA-256: `7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54` -Sources: [`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) +Sources: [`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) | Property | Presence | Type | |---|---|---| @@ -7979,7 +7979,7 @@ Sources: [`packages/web/web-search-deepseek/src/provider.ts:64`](../packages/web SHA-256: `8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52` -Sources: [`packages/session/session-log-deepseek/src/types.ts:81`](../packages/session/session-log-deepseek/src/types.ts) +Sources: [`packages/session/session-log-deepseek/src/types.ts:96`](../packages/session/session-log-deepseek/src/types.ts) | Property | Presence | Type | |---|---|---| diff --git a/docs/persistence-catalog.zh.md b/docs/persistence-catalog.zh.md index ffb641e2b7..c890b50507 100644 --- a/docs/persistence-catalog.zh.md +++ b/docs/persistence-catalog.zh.md @@ -880,7 +880,7 @@ export type SessionEvent = { 类型:[SessionTitleLlmRequestEventData](subsystems/session-title.zh.md) -来源:[`packages/session/session-title-llm/src/index.ts:57`](../packages/session/session-title-llm/src/index.ts) +来源:[`packages/session/session-title-llm/src/index.ts:63`](../packages/session/session-title-llm/src/index.ts) ### `session-log-deepseek/*` @@ -900,7 +900,7 @@ export type SessionEvent = { } ``` -来源:[`packages/session/session-log-deepseek/src/types.ts:81`](../packages/session/session-log-deepseek/src/types.ts) +来源:[`packages/session/session-log-deepseek/src/types.ts:96`](../packages/session/session-log-deepseek/src/types.ts) ### `step/*` @@ -4711,7 +4711,7 @@ SHA-256: `b56f6a885da3dc394c69a3e3cc5c0cfc4da15601b63fda4989eee8f40efc5be4` SHA-256: `7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54` -来源:[`packages/session/session-title-llm/src/index.ts:37`](../packages/session/session-title-llm/src/index.ts) +来源:[`packages/session/session-title-llm/src/index.ts:43`](../packages/session/session-title-llm/src/index.ts) | 属性 | 存在性 | 类型 | |---|---|---| @@ -7981,7 +7981,7 @@ SHA-256: `9a2a9029f8d7ede05336980d8342737557f487b913bfd28853d0ab5214600ab5` SHA-256: `8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52` -来源:[`packages/session/session-log-deepseek/src/types.ts:81`](../packages/session/session-log-deepseek/src/types.ts) +来源:[`packages/session/session-log-deepseek/src/types.ts:96`](../packages/session/session-log-deepseek/src/types.ts) | 属性 | 存在性 | 类型 | |---|---|---| diff --git a/docs/persistence-schema.json b/docs/persistence-schema.json index 4e54738289..aa46bc962e 100644 --- a/docs/persistence-schema.json +++ b/docs/persistence-schema.json @@ -380,7 +380,7 @@ {"digest":"7f7fd5a6b0064f597534b29ff62ef26e786dffccf5e14f654a7d4fcea2c35f04","names":[],"sources":[]}, {"digest":"7f9365bae9fcb73e1e34061a1acfe0422c1a5fd351848cace9bebbe806f28462","names":["packages/workflow/tool-workflow/src/types.ts#ToolWorkflowRunEndData"],"sources":["packages/workflow/tool-workflow/src/types.ts:36"]}, {"digest":"7f959241c24128b4983b559984811861dc59774b85905c8fa57c6cb0148a3dbc","names":["packages/goal/goal/src/domain.ts#GoalMessageSource"],"sources":["packages/goal/goal/src/domain.ts:47"]}, - {"digest":"7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:37"]}, + {"digest":"7ff62f6599c083ceb5a0d7a8940ff85ba80dc1d7ddd6ba9339903e93f74cba54","names":["packages/session/session-title-llm/src/index.ts#SessionTitleLlmRequestEventData"],"sources":["packages/session/session-title-llm/src/index.ts:43"]}, {"digest":"8064c03c87c357fd1575cb9395ce86e6dcbe2d275bf7717864a02cddf01827d5","names":["packages/llm/llm/src/types.ts#ContentBlock"],"sources":["packages/llm/llm/src/types.ts:157"]}, {"digest":"80677c8c8b804189a0fde8aa70dd4ad7af8bb12dfd03027e8e023c8592c838bc","names":[],"sources":[]}, {"digest":"8067b0d232c350f189738e60ee3c9939d46ca3b32b45db5525237b077893f649","names":[],"sources":[]}, @@ -413,7 +413,7 @@ {"digest":"8a9c990773f798eac10ca8878e6bcc531ee080bc589cac956730e462cc6a09ad","names":[],"sources":["packages/interaction/permission-presets/src/index.ts:53"]}, {"digest":"8ad45ad053b4d89f8865c17cc9ff3b8748e86045f3f0fb816269a34af2619141","names":[],"sources":["packages/experimental/hook-protocol/src/types.ts:31"]}, {"digest":"8af841fc9b265ade3441caf9fe40dd24db24226befba48150e6d0eeccc1389c3","names":[],"sources":[]}, - {"digest":"8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52","names":[],"sources":["packages/session/session-log-deepseek/src/types.ts:81"]}, + {"digest":"8bb8c3751a6ce64b61aba1ec7ae798c00a5803c4d868a0430873216c6569ed52","names":[],"sources":["packages/session/session-log-deepseek/src/types.ts:96"]}, {"digest":"8c1c4f72755a78ea163523a46565316e36e9b644382eb48e6635c71a6f412dd2","names":[],"sources":[]}, {"digest":"8c627d7a45fa406cea879a3922105e27ed4c3c7966e264afaf11ea7a330f2dd1","names":[],"sources":[]}, {"digest":"8cdd3fdd295cee53035de16a1b23411716f75e9f994fe9510cac5d7fef605c76","names":[],"sources":[]}, diff --git a/docs/subsystems/core.i18n.yaml b/docs/subsystems/core.i18n.yaml index 02e7a5d4f6..a2b168f3fd 100644 --- a/docs/subsystems/core.i18n.yaml +++ b/docs/subsystems/core.i18n.yaml @@ -30,8 +30,8 @@ en: 057db6d8bf356c0f zh: 1441b39e5142b0bf /core/repo-wide-type-patterns/the-map-derived-union-pattern: - en: 84c039e929edb897 - zh: 84241bb993f23ef2 + en: 87a19311e2a97270 + zh: 8df92c72793e8275 /core/repo-wide-type-patterns/branded-ids: en: 10f8ac0f97e7c54a zh: 75cd2311aabfe464 diff --git a/docs/subsystems/core.md b/docs/subsystems/core.md index 86df19aa94..48ff2ce633 100644 --- a/docs/subsystems/core.md +++ b/docs/subsystems/core.md @@ -450,12 +450,13 @@ declare module '@deepseek-ai/dsh-llm' { } ``` -Five canonical maps use this pattern; a plugin author extends these: +Six canonical maps use this pattern; a plugin author extends these: | Map | Package | Derives | Catalog | |---|---|---|---| | `ContentBlockMap` | dsh-llm | `ContentBlock` | [llm-streaming.md](llm-streaming.md#content-blocks-and-messages) | | `MessageSourceMap` | dsh-llm | `MessageSource` | [llm-streaming.md](llm-streaming.md#content-blocks-and-messages) | +| `LlmRequestPurposeMap` | dsh-llm | `LlmRequestPurpose` | [llm-streaming.md](llm-streaming.md#the-model-request-and-result) | | `FinishReasonMap` | dsh-llm | `FinishReason` | [llm-streaming.md](llm-streaming.md#the-model-request-and-result) | | `TurnEndReasonMap` | dsh-session | `TurnEndReason` | [session.md](session.md) | | `SessionEventMap` | dsh-session | `SessionEvent` | [session.md](session.md) | diff --git a/docs/subsystems/core.zh.md b/docs/subsystems/core.zh.md index db4bb206f5..19acf51b51 100644 --- a/docs/subsystems/core.zh.md +++ b/docs/subsystems/core.zh.md @@ -460,12 +460,13 @@ declare module '@deepseek-ai/dsh-llm' { } ``` -五个规范 map 使用此模式;插件作者扩展它们: +六个规范 map 使用此模式;插件作者扩展它们: | Map | 包 | 派生 | 目录 | |---|---|---|---| | `ContentBlockMap` | dsh-llm | `ContentBlock` | [llm-streaming.md](llm-streaming.zh.md#content-blocks-and-messages) | | `MessageSourceMap` | dsh-llm | `MessageSource` | [llm-streaming.md](llm-streaming.zh.md#content-blocks-and-messages) | +| `LlmRequestPurposeMap` | dsh-llm | `LlmRequestPurpose` | [llm-streaming.zh.md](llm-streaming.zh.md#the-model-request-and-result) | | `FinishReasonMap` | dsh-llm | `FinishReason` | [llm-streaming.md](llm-streaming.zh.md#the-model-request-and-result) | | `TurnEndReasonMap` | dsh-session | `TurnEndReason` | [session.md](session.zh.md) | | `SessionEventMap` | dsh-session | `SessionEvent` | [session.md](session.zh.md) | diff --git a/docs/subsystems/forge.i18n.yaml b/docs/subsystems/forge.i18n.yaml index 53a7964033..92bc2298cd 100644 --- a/docs/subsystems/forge.i18n.yaml +++ b/docs/subsystems/forge.i18n.yaml @@ -12,8 +12,8 @@ en: 26ccfa2e342e3e67 zh: fe6cc2a622757c48 /forges/change-request-actions: - en: 00e4490e416099d2 - zh: 5724d08b6ae230f7 + en: 87d2c81d9514267f + zh: 1daf31c5b0127a1c /forges/session-bindings: en: 13dfd36f2166bba0 zh: a369434f52f04d57 diff --git a/docs/subsystems/forge.md b/docs/subsystems/forge.md index 4bb2251a52..67331f49f0 100644 --- a/docs/subsystems/forge.md +++ b/docs/subsystems/forge.md @@ -45,6 +45,8 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'> interface ForgeProvider { /** Forge family name stored in every repository this provider returns. */ readonly forge: string + /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ + submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -246,6 +248,37 @@ interface ForgeActionFailure { } ``` +`ctx.forge.submitReview` delegates an explicit comment or completed review to the provider. A provider that omits this capability returns unsupported. Consumers retain pending drafts and reconcile unknown write outcomes before resubmitting. + +```ts type-equiv +/** One inline comment addressed to the old or new side of a pull request diff. */ +interface ForgeLineComment { + readonly path: string + readonly side: 'L' | 'R' + readonly startLine: number + readonly endLine: number + readonly body: string +} +``` + +```ts type-equiv +/** A single published comment or one completed review containing all pending comments. */ +type ForgeReviewRequest = { + /** Commit the user reviewed; providers must check it before writing and address that commit explicitly. */ + readonly headSha: string +} & ( + | { readonly kind: 'comment'; readonly comment: ForgeLineComment } + | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } +) +``` + +```ts type-equiv +/** Result of a review write; unknown outcomes must be checked on the host before another submission. */ +type ForgeReviewResult = + | { readonly ok: true; readonly url: string } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } +``` + ## Session bindings `ctx.forgeSession` derives each Session's bindings from its own log: `gh pr create` results bind the URLs they print, `gh pr view`, `gh pr edit`, and `gh pr checkout` calls bind the change request they act on, and `git push` results trigger head-branch discovery through `ctx.forge`; the panel also reports the branch its checkout tracks for the same discovery. Track, dismiss, and discovery actions are `plugin:forge-session/binding` records, which stay outside the model-visible conversation. The `forgeChangeRequests` projection's client view, which the Session summary carries, lists the bindings without their status. The [Session binding README](../../packages/experimental/forge-session/README.md#use-this-package) owns the recognition and discovery rules. @@ -744,6 +777,15 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): */ async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Publish one comment or a completed review, then refresh the watched status. + * @param ref - change request served by a registered provider. + * @param request - explicitly selected commit, comments, and review decision. + * @param signal - request cancellation. + * @returns a publication URL or a failure, including an unknown write outcome. + */ +async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** * Read the text of one file at a commit of a change request's repository. * @param ref - change request served by a registered provider. @@ -915,6 +957,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Publish a line comment or completed review for a visible Session binding. + * @param session - Session retaining the change request. + * @param url - visible binding URL. + * @param request - reviewed head, ranges, plain text, and explicit review decision. + * @param signal - request cancellation. + * @returns confirmed publication or a typed failure; unknown outcomes require reconciliation on the host. + */ +@Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. diff --git a/docs/subsystems/forge.zh.md b/docs/subsystems/forge.zh.md index 0819fa9f6c..2d726ca39d 100644 --- a/docs/subsystems/forge.zh.md +++ b/docs/subsystems/forge.zh.md @@ -45,6 +45,8 @@ type ChangeRequestKey = Branded<'ChangeRequestKey'> interface ForgeProvider { /** Forge family name stored in every repository this provider returns. */ readonly forge: string + /** Publish a comment or completed review. Omission declares that this provider cannot write reviews. */ + submitReview?(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise /** Map a Git remote URL to its repository, or undefined when this provider does not serve it. */ repositoryFromRemote(url: string): ForgeRepository | undefined /** Map a change request web URL to its reference, or undefined when this provider does not serve it. */ @@ -246,6 +248,37 @@ interface ForgeActionFailure { } ``` +`ctx.forge.submitReview` 将明确指定的评论或完整评审交给 provider;未实现此能力的 provider 返回不支持。消费者保存待提交草稿,并在再次提交前核对结果不明的写操作。 + +```ts type-equiv +/** One inline comment addressed to the old or new side of a pull request diff. */ +interface ForgeLineComment { + readonly path: string + readonly side: 'L' | 'R' + readonly startLine: number + readonly endLine: number + readonly body: string +} +``` + +```ts type-equiv +/** A single published comment or one completed review containing all pending comments. */ +type ForgeReviewRequest = { + /** Commit the user reviewed; providers must check it before writing and address that commit explicitly. */ + readonly headSha: string +} & ( + | { readonly kind: 'comment'; readonly comment: ForgeLineComment } + | { readonly kind: 'review'; readonly event: 'comment' | 'approve' | 'request-changes'; readonly body: string; readonly comments: readonly ForgeLineComment[] } +) +``` + +```ts type-equiv +/** Result of a review write; unknown outcomes must be checked on the host before another submission. */ +type ForgeReviewResult = + | { readonly ok: true; readonly url: string } + | { readonly ok: false; readonly code: 'unsupported' | 'stale' | 'failed' | 'unknown'; readonly message: string } +``` + ## Session 绑定 `ctx.forgeSession` 从每个 Session 自己的日志派生其绑定:`gh pr create` 的结果绑定其输出的 URL,`gh pr view`、`gh pr edit` 与 `gh pr checkout` 调用绑定它们所操作的变更请求,`git push` 的结果通过 `ctx.forge` 触发按 head 分支的发现;面板也会报告其检出所跟踪的分支,触发同样的发现。track、dismiss 与发现操作都是 `plugin:forge-session/binding` 插件记录,位于模型可见对话之外。`forgeChangeRequests` 投影的客户端视图随 Session 摘要下发,列出绑定但不含其状态。识别与发现规则见 [Session 绑定 README](../../packages/experimental/forge-session/README.zh.md#use-this-package)。 @@ -744,6 +777,15 @@ async merge(ref: ChangeRequestRef, request: MergeRequest, signal: AbortSignal): */ async diff(ref: ChangeRequestRef, signal: AbortSignal): Promise +/** + * Publish one comment or a completed review, then refresh the watched status. + * @param ref - change request served by a registered provider. + * @param request - explicitly selected commit, comments, and review decision. + * @param signal - request cancellation. + * @returns a publication URL or a failure, including an unknown write outcome. + */ +async submitReview(ref: ChangeRequestRef, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** * Read the text of one file at a commit of a change request's repository. * @param ref - change request served by a registered provider. @@ -915,6 +957,16 @@ Serves the forge panel. Following a Session inspects the checkout of its current */ @Remote async changeRequestText(session: Session, url: string, commit: string, path: string, signal: AbortSignal): Promise +/** + * Publish a line comment or completed review for a visible Session binding. + * @param session - Session retaining the change request. + * @param url - visible binding URL. + * @param request - reviewed head, ranges, plain text, and explicit review decision. + * @param signal - request cancellation. + * @returns confirmed publication or a typed failure; unknown outcomes require reconciliation on the host. + */ +@Remote async submitReview(session: Session, url: string, request: ForgeReviewRequest, signal: AbortSignal): Promise + /** * Mark a draft change request of a Session ready for review; the change * request is polled again once the host answers. diff --git a/docs/subsystems/llm-streaming.md b/docs/subsystems/llm-streaming.md index 70adbab81e..cf8d4c8310 100644 --- a/docs/subsystems/llm-streaming.md +++ b/docs/subsystems/llm-streaming.md @@ -642,8 +642,21 @@ type RequestMessage = Message | RequestUserInput ``` ```ts type-equiv -/** A single model request, fully assembled. */ -interface GenerateOptions { +/** Auxiliary request purposes declared by their producer packages. */ +interface LlmRequestPurposeMap {} +``` + +```ts type-equiv +/** Declared auxiliary request purpose; ordinary conversation requests leave it absent. */ +type LlmRequestPurpose = Extract +``` + +```ts type-equiv +/** + * A single model request, fully assembled. + * @typeParam Purpose - declared purpose keys for callers; forwarding adapters may accept `string`. + */ +interface GenerateOptions { /** Registered provider route selecting the adapter instance. */ provider: string model: string @@ -684,7 +697,7 @@ interface GenerateOptions { * map the purpose to model-hidden transport metadata. Ordinary conversation * requests leave it unset. */ - purpose?: 'compaction' | 'session-title' + purpose?: Purpose } ``` diff --git a/docs/subsystems/llm-streaming.zh.md b/docs/subsystems/llm-streaming.zh.md index 05accb437c..0feb80a1a1 100644 --- a/docs/subsystems/llm-streaming.zh.md +++ b/docs/subsystems/llm-streaming.zh.md @@ -648,8 +648,21 @@ type RequestMessage = Message | RequestUserInput ``` ```ts type-equiv -/** A single model request, fully assembled. */ -interface GenerateOptions { +/** Auxiliary request purposes declared by their producer packages. */ +interface LlmRequestPurposeMap {} +``` + +```ts type-equiv +/** Declared auxiliary request purpose; ordinary conversation requests leave it absent. */ +type LlmRequestPurpose = Extract +``` + +```ts type-equiv +/** + * A single model request, fully assembled. + * @typeParam Purpose - declared purpose keys for callers; forwarding adapters may accept `string`. + */ +interface GenerateOptions { /** Registered provider route selecting the adapter instance. */ provider: string model: string @@ -690,7 +703,7 @@ interface GenerateOptions { * map the purpose to model-hidden transport metadata. Ordinary conversation * requests leave it unset. */ - purpose?: 'compaction' | 'session-title' + purpose?: Purpose } ``` diff --git a/docs/subsystems/session.i18n.yaml b/docs/subsystems/session.i18n.yaml index 53d89173b4..b4cd4bba34 100644 --- a/docs/subsystems/session.i18n.yaml +++ b/docs/subsystems/session.i18n.yaml @@ -68,3 +68,6 @@ /sessions/remote-catalog-and-workspace-opening: en: dd27307e0d7c893c zh: b77d2a749b7b641c +/sessions/session-log-upload-exclusions: + en: cfe3323aade972be + zh: 8423b490c47c5013 diff --git a/docs/subsystems/session.md b/docs/subsystems/session.md index 7cbc91298d..fb3e56ee87 100644 --- a/docs/subsystems/session.md +++ b/docs/subsystems/session.md @@ -817,6 +817,29 @@ The backends that consume this contract are on [persistence.md](persistence.md). The optional `application` selects a registered file handler without changing the system default; `workspacePathApplications({ path })` returns current handlers, names, icons, and default selection after Host path verification. +## Session-log upload exclusions + +`ctx.sessionLogDeepSeek.registerExclusion()` registers a caller-owned predicate over `SessionLogUploadRequest`. Any match omits the log contribution and its acceptance callback before reading Session events. No match preserves normal upload eligibility. The [package README](../../packages/session/session-log-deepseek/README.md#upload-exclusions) defines failure and disposal behavior. + +```ts type-equiv +/** Request identity inspected before preparing a Session-log contribution. */ +interface SessionLogUploadRequest { + /** Live Session whose canonical log would be contributed. */ + readonly sessionId: SessionId + /** Auxiliary request classification; absent for ordinary conversation requests. */ + readonly purpose?: string +} +``` + +```ts type-equiv +/** + * Synchronous, side-effect-free upload exclusion owned by its registering plugin. + * @param request - request identity; the predicate must not mutate it. + * @returns `true` to omit the log field and acceptance callback, or `false` to keep checking eligibility. + */ +type SessionLogUploadExclusion = (request: SessionLogUploadRequest) => boolean +``` + @@ -1035,6 +1058,26 @@ Types: [SessionId](core.md) · [SessionSearchRequest](session-query.md) Source: [`packages/api/session-controller/src/index.ts`](../../packages/api/session-controller/src/index.ts) + + +### `ctx.sessionLogDeepSeek` — `SessionLogDeepSeekService` + +Incremental Session-log contributor with caller-owned upload exclusions. + +```ts cordis-catalog +/** + * Exclude matching requests before reading or preparing their log contribution. + * Any matching rule suppresses both the field and its acceptance callback. With + * no matching rules, normal upload eligibility applies. A throwing rule fails + * this contribution; the request-extension registry omits it and reports the error. + * @param exclude - synchronous, side-effect-free predicate; `true` skips this upload. + * @returns effect disposer that removes this registration when called or when the caller unloads. + */ +registerExclusion(exclude: SessionLogUploadExclusion): () => Promise +``` + +Source: [`packages/session/session-log-deepseek/src/index.ts`](../../packages/session/session-log-deepseek/src/index.ts) + ### `ctx.sessions` — `SessionStore` diff --git a/docs/subsystems/session.zh.md b/docs/subsystems/session.zh.md index 1f40042967..fb26a5105c 100644 --- a/docs/subsystems/session.zh.md +++ b/docs/subsystems/session.zh.md @@ -821,6 +821,29 @@ interface PluginRecord { 可选的 `application` 指定文件关联应用,不修改系统默认值;`workspacePathApplications({ path })` 在校验 Host 路径后返回当前关联应用、名称、图标和默认项。 +## Session 日志上传排除条件 + +`ctx.sessionLogDeepSeek.registerExclusion()` 注册归调用方所有的判断函数,输入为 `SessionLogUploadRequest`。任意条件匹配时,在读取 Session 事件前省略日志贡献与接受回调。没有条件匹配时保留普通上传资格判断。[包 README](../../packages/session/session-log-deepseek/README.zh.md#upload-exclusions) 定义失败与释放行为。 + +```ts type-equiv +/** Request identity inspected before preparing a Session-log contribution. */ +interface SessionLogUploadRequest { + /** Live Session whose canonical log would be contributed. */ + readonly sessionId: SessionId + /** Auxiliary request classification; absent for ordinary conversation requests. */ + readonly purpose?: string +} +``` + +```ts type-equiv +/** + * Synchronous, side-effect-free upload exclusion owned by its registering plugin. + * @param request - request identity; the predicate must not mutate it. + * @returns `true` to omit the log field and acceptance callback, or `false` to keep checking eligibility. + */ +type SessionLogUploadExclusion = (request: SessionLogUploadRequest) => boolean +``` + @@ -1039,6 +1062,26 @@ Types: [SessionId](core.zh.md) · [SessionSearchRequest](session-query.zh.md) Source: [`packages/api/session-controller/src/index.ts`](../../packages/api/session-controller/src/index.ts) + + +### `ctx.sessionLogDeepSeek` — `SessionLogDeepSeekService` + +Incremental Session-log contributor with caller-owned upload exclusions. + +```ts cordis-catalog +/** + * Exclude matching requests before reading or preparing their log contribution. + * Any matching rule suppresses both the field and its acceptance callback. With + * no matching rules, normal upload eligibility applies. A throwing rule fails + * this contribution; the request-extension registry omits it and reports the error. + * @param exclude - synchronous, side-effect-free predicate; `true` skips this upload. + * @returns effect disposer that removes this registration when called or when the caller unloads. + */ +registerExclusion(exclude: SessionLogUploadExclusion): () => Promise +``` + +Source: [`packages/session/session-log-deepseek/src/index.ts`](../../packages/session/session-log-deepseek/src/index.ts) + ### `ctx.sessions` — `SessionStore` diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.i18n.yaml new file mode 100644 index 0000000000..7bae7f2845 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/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-alpha.2/llm-request-purpose-declarations/guide.md +/: + en: 0a5cfa851101f3e9 + zh: 1c8e0e437718d4e2 +/declare-auxiliary-llm-request-purposes: + en: 5d5e1b6cb5b9c95e + zh: 11cf31babb07da28 +/declare-auxiliary-llm-request-purposes/change: + en: 0682a43eb52792fd + zh: 954b186cc66fdb08 +/declare-auxiliary-llm-request-purposes/migration: + en: eae671d1e185ecbf + zh: c042a276a1a7ad17 diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.md b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.md new file mode 100644 index 0000000000..d71d8f6bef --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "Auxiliary LLM request purposes require producer-owned type declarations instead of a shared fixed union." +--- + +# Declare auxiliary LLM request purposes + +English | [中文](guide.zh.md) + +## Change + +`GenerateOptions.purpose` derives from the declaration-mergeable `LlmRequestPurposeMap` exported by `@deepseek-ai/dsh-llm/types`. The shared package no longer declares `compaction` or `session-title`. Plugins that construct auxiliary requests must load the producer's declarations or declare their own purpose. Existing runtime purpose strings keep their meaning. + +## Migration + +1. Import `@deepseek-ai/dsh-compaction-basic` for direct compaction requests, or `@deepseek-ai/dsh-session-title-llm` for title requests, using a type-only import when only the declaration is needed. +2. For a plugin-owned purpose, augment `LlmRequestPurposeMap` from the plugin's public type entry. Map the purpose key to `true`: + + ```ts + import type {} from '@deepseek-ai/dsh-llm/types' + + declare module '@deepseek-ai/dsh-llm/types' { + interface LlmRequestPurposeMap { + 'my-plugin-purpose': true + } + } + ``` + +3. Compile the plugin against the new package declarations. Confirm that its request accepts the declared purpose and rejects an undeclared key. diff --git a/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.zh.md b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.zh.md new file mode 100644 index 0000000000..d1fd550142 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-alpha.2/llm-request-purpose-declarations/guide.zh.md @@ -0,0 +1,29 @@ +--- +kind: upgrade-guide +description: "辅助 LLM 请求用途改为生产方拥有的类型声明,不再使用共享固定联合。" +--- + +# 声明辅助 LLM 请求用途 + +[English](guide.md) | 中文 + +## 变更 + +`GenerateOptions.purpose` 由 `@deepseek-ai/dsh-llm/types` 导出的可声明合并的 `LlmRequestPurposeMap` 派生。共享包不再声明 `compaction` 或 `session-title`。构造辅助请求的插件必须加载生产方的声明,或声明自己的用途。现有运行时用途字符串保持原有含义。 + +## 迁移 + +1. 直接构造压缩请求时导入 `@deepseek-ai/dsh-compaction-basic`,构造标题请求时导入 `@deepseek-ai/dsh-session-title-llm`;只需要声明时使用仅类型导入。 +2. 对插件拥有的用途,在插件公开类型入口中扩展 `LlmRequestPurposeMap`,将用途键映射到 `true`: + + ```ts + import type {} from '@deepseek-ai/dsh-llm/types' + + declare module '@deepseek-ai/dsh-llm/types' { + interface LlmRequestPurposeMap { + 'my-plugin-purpose': true + } + } + ``` + +3. 使用新包的声明编译插件,确认请求接受已声明用途,并拒绝未声明的键。 diff --git a/packages/client/ui-dockkit/README.i18n.yaml b/packages/client/ui-dockkit/README.i18n.yaml index 6bff57dde1..0fadf55cad 100644 --- a/packages/client/ui-dockkit/README.i18n.yaml +++ b/packages/client/ui-dockkit/README.i18n.yaml @@ -18,8 +18,8 @@ en: 718f52cfce426009 zh: e8282e2e3713d242 /deepseek-ai-dsh-client-ui-dockkit/embedding-it: - en: 87fab28e0608044e - zh: 2d5f80a367f1852b + en: 53bbabeb910c6f77 + zh: 51fb4f8fb78cfd02 /deepseek-ai-dsh-client-ui-dockkit/interaction-rules-worth-keeping: en: cf2d00ce2b7d5719 zh: 5510420f8872e23a diff --git a/packages/client/ui-dockkit/README.md b/packages/client/ui-dockkit/README.md index 12f5b74938..a446fdedd6 100644 --- a/packages/client/ui-dockkit/README.md +++ b/packages/client/ui-dockkit/README.md @@ -60,6 +60,8 @@ Everything host-specific arrives through props: `dropZones="horizontal"` offers two half-pane hints; once budget or width forbids another split, the whole body accepts a move. A hint is a dashed card inset 8px inside its region, showing the zone's glyph and `labels.dropZone[zone]`; the preview layer covers all tab-body content, while the card under the pointer takes the accent and its neighbour stays a quiet outline. `minPaneFraction` sets the preview minimum, and `planResizeSplit` accepts the same minimum for the committed operation. The Sidebar uses 0.2 and enforces two panes in its own store. The generic engine retains its tree and other split directions. `hideSplitWhenBlocked` hides a blocked split control — pane budget spent or pane too narrow — instead of rendering it disabled; its default is false. +The split control wrapper exposes `data-dockkit-split-control` for embedder styling, independently of its element tag. + A tab's `kind` is an opaque string. Seeded tabs are factories (`DockControllerOptions`), so what a fresh pane contains is the embedder's decision, not this package's. Content identity is the pair (`kind`, `contentId`): `findContentTab(state, contentId, kind?)` finds the tab showing it anywhere and `findPaneContentTab(state, paneId, contentId, kind?)` within one pane, and `planOpenContent` focuses that tab instead of opening another unless told `revealIfOpened: false`; an explicit `index` seats a new tab at a strip slot rather than at the end. `DockLayout`, used by the Sidebar, keeps each tab in a stable DOM cell across selection, pane moves and floating. It accepts one docked pane or two horizontal panes; CSS Grid resolves their widths. `keepMounted(tab)` retains visited bodies and `active` controls Session visibility without reparenting content. diff --git a/packages/client/ui-dockkit/README.zh.md b/packages/client/ui-dockkit/README.zh.md index 06b1a593f3..d94e4ee9f3 100644 --- a/packages/client/ui-dockkit/README.zh.md +++ b/packages/client/ui-dockkit/README.zh.md @@ -60,6 +60,8 @@ kind: "package-reference" `dropZones="horizontal"` 提供左右两个半区提示;预算或宽度不允许再拆时,正文整格接收移动。提示是一张内缩 8px 的虚线卡片,显示该落区的图形和 `labels.dropZone[zone]`;预览层覆盖全部 tab 正文,指针所在的卡片取强调色,另一张保持安静的轮廓。`minPaneFraction` 控制预览的最小比例,`planResizeSplit` 接受相同最小值以约束提交;Sidebar使用0.2并在自己的store限制两格。通用引擎仍保留原有树与其它分割方向。 `hideSplitWhenBlocked` 在分栏被阻止时(窗格预算已满或格太窄)直接隐藏分栏控件而不是渲染禁用态,默认值为 false。 +分栏控件的包裹元素通过 `data-dockkit-split-control` 提供宿主样式入口,不依赖具体元素标签。 + tab 的 `kind` 是不透明字符串。种子 tab 是工厂(`DockControllerOptions`),因此新格里放什么由嵌入方决定,与本包无关。内容身份是二元组(`kind`、`contentId`):`findContentTab(state, contentId, kind?)` 在任意位置找到展示它的 tab,`findPaneContentTab(state, paneId, contentId, kind?)` 在一个格内找;`planOpenContent` 会聚焦该 tab 而非再开一个,除非被告知 `revealIfOpened: false`;显式的 `index` 把新 tab 放到 tab 条的某个位置而非末尾。 Sidebar 使用的 `DockLayout` 在选中项变化、跨格移动与浮动期间,把每个 tab 保留在稳定的 DOM 容器中。它接受一个停靠格或左右两个格,由 CSS Grid 计算宽度。`keepMounted(tab)` 保留已访问正文,`active` 控制 Session 可见性,不改变内容的父子关系。 diff --git a/packages/client/ui-dockkit/src/components/TabPanel.tsx b/packages/client/ui-dockkit/src/components/TabPanel.tsx index 632a763ff3..df0e39bdb4 100644 --- a/packages/client/ui-dockkit/src/components/TabPanel.tsx +++ b/packages/client/ui-dockkit/src/components/TabPanel.tsx @@ -427,6 +427,7 @@ export function TabStrip({ state, pane, callbacks, offsets }: TabStripProps): Re {!(callbacks.hideSplitWhenBlocked && block !== undefined) && ( { if (block !== undefined) event.stopPropagation() }} diff --git a/packages/client/ui-dockkit/tests/components.client.spec.tsx b/packages/client/ui-dockkit/tests/components.client.spec.tsx index 492f7478dd..59f50bfab8 100644 --- a/packages/client/ui-dockkit/tests/components.client.spec.tsx +++ b/packages/client/ui-dockkit/tests/components.client.spec.tsx @@ -281,6 +281,7 @@ describe('DockSurface', () => { expect(disabled.hasAttribute('disabled')).toBe(true) expect(disabled.parentElement?.getAttribute('aria-label')).toBe(TEST_LABELS.splitPaneDisabled) expect(disabled.getAttribute('data-dockkit-split-blocked')).toBe('budget') + expect(disabled.parentElement?.hasAttribute('data-dockkit-split-control')).toBe(true) intents.splitPane.mockClear() const hint = disabled.parentElement! fireEvent.pointerDown(hint, { pointerType: 'touch' }) diff --git a/packages/client/ui-layout/README.i18n.yaml b/packages/client/ui-layout/README.i18n.yaml index 4ad7481ef7..a89c7c4b40 100644 --- a/packages/client/ui-layout/README.i18n.yaml +++ b/packages/client/ui-layout/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-layout/use-this-package: - en: cc6e9021ba3001bc - zh: 97444857762b4e8e + en: 2a0687d0683eaa9a + zh: 402c55259770f565 /deepseek-ai-dsh-client-ui-layout/use-this-package/window-chrome-seat: en: 7eac53b38d0777fe zh: 7f9422dff671ba50 @@ -24,8 +24,8 @@ en: 5ac34303ad90b484 zh: abcc4a1dcf28391e /deepseek-ai-dsh-client-ui-layout/understand-the-implementation: - en: 5ab6b311a912fb06 - zh: d7e88894686b1682 + en: e3cb25f05902369a + zh: c1a8f049a7a4effb /deepseek-ai-dsh-client-ui-layout/further-exploration: en: 74de780b4592e28e zh: a413f06f8ec406d0 @@ -36,8 +36,8 @@ en: ca75c51c89c2c9b0 zh: de54f3467ef3b9be /deepseek-ai-dsh-client-ui-layout/known-limitations-and-deferred-work: - en: da92b97ac60d989f - zh: 5816b861728f1a04 + en: 834ae31817179718 + zh: d2cff416fd0f643a /deepseek-ai-dsh-client-ui-layout/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/client/ui-layout/README.md b/packages/client/ui-layout/README.md index 43c61b89d1..8a20476270 100644 --- a/packages/client/ui-layout/README.md +++ b/packages/client/ui-layout/README.md @@ -25,9 +25,13 @@ This package provides the Web GUI's three-column AppFrame, edge-column widths, a ## Use this package -Desktop Mod+B toggles the left sidebar through the same layout action used by its controls. The shortcut command is unavailable behind modal dialogs and yields to terminal input. +Desktop Mod+B toggles the left sidebar through the same layout action used by its controls. The shortcut remains available inside the navigation drawer, is unavailable behind other modal dialogs, and yields to terminal input. -The root slot composes the sidebar, main content, and right column. The sidebar spans 264–420px, defaults to 280px, and retains a 56px rail when collapsed; below 1024px it collapses automatically, and opening the right panel collapses a manually expanded sidebar. The right panel first opens at 45% of the viewport, then retains the user's pixel preference, capped at 70%. To protect 400px for the center, the frame first reduces the right panel to 300px, then reports insufficient room so its occupant closes it, and only then compresses the center further. Dragging has no transition delay; the right handle is absent while closed or fullscreen. +The root slot composes the sidebar, main content, and right column. The sidebar spans 264–420px, defaults to 280px, and retains a 56px rail when collapsed at widths of 768px and above. Below 768px, without a native Windows caption, it uses a modal drawer without reserving a column; the header retains the reopen controls, and navigation closes the drawer. Below 1024px it collapses automatically, and opening the right panel collapses a manually expanded sidebar. The right panel first opens at 45% of the viewport, then retains the user's pixel preference, capped at 70%. To protect 400px for the center, the frame first reduces the right panel to 300px, then reports insufficient room so its occupant closes it, and only then compresses the center further. Dragging has no transition delay; the right handle is absent while closed or fullscreen. + +When the browser reports a folded device in landscape and the frame is at least 768px wide, the expanded sidebar occupies half the frame. This midpoint heuristic targets book postures with a vertical center fold; it does not identify the hinge direction or reserve its physical width, so horizontal or off-center folds are not supported by this adjustment. Its resize handle is hidden; unfolding restores the saved width. Fold changes at a stable viewport width use the existing track transition; reduced motion disables it. Browsers without the device-posture media feature keep the ordinary layout. + +The drawer mask fades with the panel’s transition duration and easing on both open and close; reduced motion disables both transitions. Entering drawer mode from an already collapsed sidebar hides the drawer immediately; an expanded sidebar keeps its closing slide. The drawer has no edge divider, and its frame does not scroll. On macOS, the drawer uses the same opaque background as Web; window vibrancy applies only to the ordinary sidebar. The frame fills the shell’s layout viewport, retaining its height while the keyboard opens. Drawer backing and mask cover the shell’s full height, including `shell.bottom`, above fullscreen and floating right panels. Browser-owned status and address bars remain outside the shell; the layout adds no synthetic safe-area insets. Global panels occupy the root-scoped `main` keyed slot; `conversation` is the reserved key for the Conversation. `ctx.layout.selectPanel(id)` selects a registered panel, and `null` selects the Conversation without changing the current Session. The Plugins page contributes one of the shipped global panels. @@ -54,6 +58,8 @@ The presenter consumes resolved theme snapshots and projects them onto the docum
Implementation internals — click to expand +The root registration supplies folded-landscape posture through an injected observable. The renderer owns its media-query subscription; AppFrame reads the snapshot through the bound hook. Client registrations running without browser media APIs use the ordinary layout. + `selectPanel(id)` checks the live `main` registry before changing selection; an absent key throws and leaves the current panel intact. `beginNavigation()` returns an abort signal for an asynchronous UI navigation. A later call, a valid panel selection (including repeated selection), or layout disposal aborts that signal without cancelling underlying Session creation. Consumers check the signal before committing navigation or moving drafts. One registration declares the frame slots and binds `ctx.layout` methods `selectPanel`, `toggleSidebar`, `openRightbar(track, fullscreen)`, and `closeRightbar`. One root store separates `panelInfo` selection from `layoutInfo` measurements, width preferences, and presentation reports. `ctx.layout.panelInfo` and the standard `usePanelInfo` hook share the same selection source; AppFrame subscribes to the stable layout object. The `rightbar` owner supplies actual `width`, `viewportWidth`, and normal-presentation eligibility `canShow`; insufficient room causes a deterministic close, never automatic reopening on widening. Fullscreen hides the width handle without releasing a track the occupant retains. AppFrame keeps the column containers mounted. The right column's root controller renders `rightbar.session` through `SessionProvider` only while the Conversation is selected; its unmount report releases the track. The independent title component uses the selected Session title only while the Conversation is visible, with the build-configured product title or localized `common.brand.localBuild` as its fallback; locale revisions update that fallback. The theme presenter is a second effect: pure DOM writes from resolved snapshots — initial state through the getter once, then event-driven only, with no React path. It applies palette, font-size, font-list, and token variables before measuring the rendered background as the single color authority. Fullscreen presentation suppresses grid and handle transitions; its occupant reports the new columns only after covering the frame. Fullscreen exit keeps transitions suppressed while the frame installs its destination geometry: close removes the right track, and restore retains it. Subsequent normal geometry actions restore ordinary transitions. @@ -92,7 +98,7 @@ None; this package neither assembles nor sends a provider request. These limits define the current layout behavior. They are current package constraints, not a general window-manager comparison or a task backlog. - **Panel geometry is transient** — reload restores the sidebar default and the right panel hidden; each dragged width is one frame-wide preference, not a per-Session fact. -- **Extremely narrow windows** — after the right panel closes, the center may still fall below 400px; the left 56px rail remains. +- **Extremely narrow windows** — after the right panel closes, the center may still fall below 400px; browser drawers reserve no sidebar width below 768px. - **Track and panel travel on one shared curve only while animating** — during a discrete open/close the frame sets `data-animating` and its track transition and the occupant's slide read the same duration and easing variables; an occupant that used its own would detach the panel's edge from the conversation's while squeezing. Drags and instant presentation switches run transition-free, so the curve does not cover them. - **No scroll anchoring during squeeze reflow** — layout changes may move the reader's viewport. diff --git a/packages/client/ui-layout/README.zh.md b/packages/client/ui-layout/README.zh.md index 9b426dcdef..e19b7a0bd2 100644 --- a/packages/client/ui-layout/README.zh.md +++ b/packages/client/ui-layout/README.zh.md @@ -25,9 +25,13 @@ kind: "package-reference" ## 使用本包 -桌面 Mod+B 通过与控件共用的布局操作切换左侧栏。模态弹窗打开时此快捷键不可用;终端输入优先。 +桌面 Mod+B 通过与控件共用的布局操作切换左侧栏。此快捷键在导航抽屉内仍可用,在其他模态弹窗打开时不可用;终端输入优先。 -本插件在 root slot 中组合侧边栏、主内容和右栏。侧边栏宽度为 264~420px,默认为 280px,收起后保留 56px 控制栏;窗口宽度低于 1024px 时自动收起,打开右侧面板也会收起手动展开的侧边栏。右侧面板首次打开时使用视口宽度的 45%,之后保留用户的像素宽度偏好,上限为 70%。为给中栏保留 400px,框架先将右侧面板缩减至 300px,再报告空间不足,使占用方将其关闭,最后才进一步压缩中栏。拖动没有过渡延迟;右侧手柄在关闭或全屏时不显示。 +本插件在 root slot 中组合侧边栏、主内容和右栏。侧边栏宽度为 264~420px,默认为 280px,在宽度不低于 768px 时,收起后保留 56px 控制栏。低于 768px 且没有原生 Windows 顶栏时,采用模态抽屉,不占据列宽;标题区域保留重新打开的控件,导航后关闭抽屉。窗口宽度低于 1024px 时自动收起,打开右侧面板也会收起手动展开的侧边栏。右侧面板首次打开时使用视口宽度的 45%,之后保留用户的像素宽度偏好,上限为 70%。为给中栏保留 400px,框架先将右侧面板缩减至 300px,再报告空间不足,使占用方将其关闭,最后才进一步压缩中栏。拖动没有过渡延迟;右侧手柄在关闭或全屏时不显示。 + +当浏览器报告设备处于横屏半折叠状态,且框架宽度不低于 768px 时,展开的侧边栏占据一半宽度。这一中点启发式面向折痕竖直且位于中央的书本姿态;它不识别铰链方向,也不为实体铰链宽度留空,因此这项调整不支持水平或偏离中央的折痕。此时隐藏拖拽手柄;完全展开后恢复保存的宽度。视口宽度不变时,折叠状态切换复用现有的列宽过渡;减少动态效果时禁用该过渡。不支持 device-posture 媒体特性的浏览器继续使用常规布局。 + +抽屉遮罩使用与面板相同的时长和缓动,在打开与关闭时渐变透明度;减少动态效果时两者均不播放动画。从已收起的侧栏切换到抽屉布局时,抽屉立即隐藏;已展开的侧栏保留收起动画。抽屉边缘不绘制分隔线,外层框架不滚动。macOS 抽屉与 Web 使用相同的不透明背景,毛玻璃仅用于普通侧栏。框架铺满外壳的布局视口,在键盘抬起时保留原有高度。抽屉背景和遮罩覆盖外壳完整高度,包括 `shell.bottom`,并显示在全屏和浮动右侧面板之上。浏览器管理的状态栏和地址栏位于外壳之外;布局不添加模拟安全区边距。 全局面板占据 root 作用域的 `main` keyed slot;`conversation` 是为会话界面保留的 key。`ctx.layout.selectPanel(id)` 选中已注册面板,`null` 则选中会话界面,但不改变当前会话。Plugins 页面是默认组合中的一个全局面板。 @@ -54,6 +58,8 @@ Windows Electron 的 `data-windows-titlebar` 标记在所有列上方预留顶
实现细节——点击展开 +root 注册通过注入的可观察源提供横屏折叠状态,由渲染器负责媒体查询订阅,AppFrame 只通过绑定的 hook 读取快照。在没有浏览器媒体 API 的环境中运行客户端注册时,使用常规布局。 + `selectPanel(id)` 在改变选中态前检查实时 `main` 注册表;缺失的 key 会抛错并保留当前面板。`beginNavigation()` 为异步 UI 导航返回 abort signal。后续调用、有效面板选择(包括重复选择)或布局释放会中止该 signal,但不取消底层会话创建。消费方在提交导航或搬移草稿前检查 signal。 一次注册声明框架的子 slot,并绑定 `ctx.layout` 的 `selectPanel`、`toggleSidebar`、`openRightbar(track, fullscreen)` 与 `closeRightbar`。同一个 root 存储把 `panelInfo` 选中态与 `layoutInfo` 测量、宽度偏好、呈现报告分开。`ctx.layout.panelInfo` 与标准 `usePanelInfo` hook 共用同一个选中态来源;AppFrame 订阅引用稳定的布局对象。`rightbar` owner 提供实际 `width`、`viewportWidth`,以及表示能否以普通模式呈现的 `canShow`;占用方在空间不足时执行确定性的收起,变宽不自行重新展开。全屏隐藏宽度手柄,但不自行释放占用方要求保留的轨道。AppFrame 保持各列容器挂载。右栏的 root 控制器仅在选中会话界面时,经 `SessionProvider` 渲染 `rightbar.session`;内容卸载时的报告释放轨道。独立的标题组件仅在会话界面可见时使用所选会话标题,以构建配置的产品标题或本地化 `common.brand.localBuild` 为回退值;语言变化会更新该回退值。主题呈现器是第二个 effect:从解析后的快照做纯 DOM 写入——初始状态经 getter 读取一次,此后仅事件驱动,不经过 React。它先应用调色板、字号、字体列表与 token 变量,再把渲染出的背景测量为唯一的颜色依据。全屏呈现禁用网格和手柄过渡;占用方完全覆盖框架后才报告新的列布局。退出全屏时,框架先保持无过渡并安装目标布局:关闭移除右轨道,恢复保留右轨道。后续普通几何操作恢复正常过渡。 @@ -92,7 +98,7 @@ Windows Electron 的 `data-windows-titlebar` 标记在所有列上方预留顶 这些限制界定了当前布局行为。它们是当前包约束,不是通用窗口管理器对比或任务积压。 - **面板几何是瞬时状态**——重新加载会恢复侧栏默认值并隐藏右侧面板;拖动设置的宽度是整个框架共用的一份偏好,而非每个会话各自的属性。 -- **极窄窗口**——右侧面板关闭后,中栏仍可能小于 400px;左侧 56px 控制栏仍会保留。 +- **极窄窗口**——右侧面板关闭后,中栏仍可能小于 400px;低于 768px 时,浏览器抽屉不占据侧栏宽度。 - **轨道与面板仅在动画期间沿同一条曲线运动**——离散开合时框架设置 `data-animating`,其轨道过渡和占用方的滑入读取同一组时长与缓动变量;占用方若自用一套,挤压时面板边缘就会与会话界面的边缘脱开。拖拽和即时呈现切换不带过渡,因此该曲线不覆盖它们。 - **挤压重排期间无滚动锚定**——布局变化可能移动读者的视口。 diff --git a/packages/client/ui-layout/src/client/AppFrame.module.css b/packages/client/ui-layout/src/client/AppFrame.module.css index 5b71ebecfd..0840483b53 100644 --- a/packages/client/ui-layout/src/client/AppFrame.module.css +++ b/packages/client/ui-layout/src/client/AppFrame.module.css @@ -3,11 +3,12 @@ display: grid; grid-template-rows: minmax(0, 1fr) auto; height: 100%; + box-sizing: border-box; overflow: hidden; background: var(--dsw-alias-bg-base); } -/* Only a discrete collapse/expand toggle eases the tracks (the TSX holds +/* Only discrete collapse/expand and fold changes ease the tracks (the TSX holds data-animating across the toggle on the deepsuite sider curve). Steady-state tracks move only with the viewport, and those updates must land instantly: an eased track chases the live window edge and the centre column visibly @@ -56,6 +57,8 @@ } .sidebarCol { + grid-column: 1; + grid-row: 1; min-width: 0; overflow: hidden; background: var(--dsw-specific-sidebar-fill); @@ -63,12 +66,22 @@ } .centerCol { + grid-column: 2; + grid-row: 1; min-width: 0; display: flex; flex-direction: column; overflow: hidden; } +.mainPanel { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; + min-height: 0; +} + /* macOS desktop: the frame goes transparent so window vibrancy reaches the sidebar column, which keeps only a translucent tint; the centre paints the base background itself to stay opaque. The sidebar/centre separator moves @@ -107,7 +120,7 @@ --dsh-frame-chrome-top: 0px; } -:global([data-platform='darwin']) .sidebarCol { +:global([data-platform='darwin']) .frame:not([data-sidebar-drawer]) .sidebarCol { /* A blue wash over the top of the translucent tint, gone by a third of the column; a faint blue-grey-violet rises through the bottom third; and a faint blue cast is mixed into the tint itself. Every layer stays @@ -126,7 +139,7 @@ /* Dark drops the blue cast (the light-mode wash reads purple over dark fills) and thins the fill so more wallpaper shows; the washes stay. */ -:global([data-platform='darwin']) :global([data-ds-dark-theme]) .sidebarCol { +:global([data-platform='darwin']) :global([data-ds-dark-theme]) .frame:not([data-sidebar-drawer]) .sidebarCol { background: linear-gradient( to bottom, @@ -143,8 +156,8 @@ them with a 90%-opaque fill of the same token in both themes (the dark selector repeats so this outranks its thinner fill). */ @media (prefers-reduced-transparency: reduce) { - :global([data-platform='darwin']) .sidebarCol, - :global([data-platform='darwin']) :global([data-ds-dark-theme]) .sidebarCol { + :global([data-platform='darwin']) .frame:not([data-sidebar-drawer]) .sidebarCol, + :global([data-platform='darwin']) :global([data-ds-dark-theme]) .frame:not([data-sidebar-drawer]) .sidebarCol { background: color-mix(in srgb, var(--dsw-specific-sidebar-fill) 90%, transparent); } } @@ -265,11 +278,91 @@ * where it is. The occupant draws its own left border. */ .rightbarCol { + grid-column: 3; + grid-row: 1; position: relative; min-width: 0; overflow: visible; } +.frame[data-sidebar-drawer] { + --dsh-frame-leading-clearance: 84px; + overflow: clip; +} + +.frame[data-sidebar-drawer] .mainPanel[data-global-panel] { + padding-top: max(0px, calc(48px - var(--dsh-frame-top-clearance, 0px))); +} + +.frame[data-sidebar-drawer] .sidebarCol { + position: absolute; + grid-area: auto; + inset: 0 auto 0 0; + z-index: 71; + box-sizing: border-box; + border-right: none; + transform: translateX(0); + visibility: visible; + transition: transform var(--ds-transition-duration-slow) var(--ds-ease-in-out); +} + +.frame[data-sidebar-drawer][data-sidebar-collapsed] .sidebarCol { + transform: translateX(-100%); + visibility: hidden; + transition: + transform var(--ds-transition-duration-slow) var(--ds-ease-in-out), + visibility 0s linear var(--ds-transition-duration-slow); +} + +.frame[data-sidebar-drawer][data-sidebar-instant] .sidebarCol { + transition: none; +} + +.drawerMask { + position: absolute; + inset: var(--dsh-frame-chrome-top, 0px) 0 0; + z-index: 70; + background: var(--dsw-alias-bg-mask-1); + backdrop-filter: var(--dsw-mask-blur); + opacity: 0; + pointer-events: none; + transition: opacity var(--ds-transition-duration-slow) var(--ds-ease-in-out); +} + +.frame[data-sidebar-drawer]:not([data-sidebar-collapsed]) .drawerMask { + opacity: 1; + pointer-events: auto; +} + +.frame[data-sidebar-drawer] .leadingSeat { + top: 11px; + left: 12px; +} + +:global([data-platform='darwin']) .frame[data-sidebar-drawer] { + --dsh-frame-leading-clearance: 160px; +} + +:global([data-platform='darwin']) .frame[data-sidebar-drawer] .leadingSeat { + left: 88px; +} + +:global([data-platform='darwin'][data-fullscreen]) .frame[data-sidebar-drawer] { + --dsh-frame-leading-clearance: 84px; +} + +:global([data-platform='darwin'][data-fullscreen]) .frame[data-sidebar-drawer] .leadingSeat { + left: 12px; +} + +@media (prefers-reduced-motion: reduce) { + .frame[data-sidebar-drawer] .sidebarCol, + .frame[data-sidebar-drawer][data-sidebar-collapsed] .sidebarCol, + .drawerMask { + transition: none; + } +} + .bottomRow { grid-column: 1 / -1; min-width: 0; diff --git a/packages/client/ui-layout/src/client/AppFrame.tsx b/packages/client/ui-layout/src/client/AppFrame.tsx index 5614947447..14b64dd92b 100644 --- a/packages/client/ui-layout/src/client/AppFrame.tsx +++ b/packages/client/ui-layout/src/client/AppFrame.tsx @@ -17,29 +17,37 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import type { ReactNode } from 'react' import type { - PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, + HostObservable, InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime, PropsStore, } from '@deepseek-ai/dsh-client-ui-slots' -import { CENTER_MIN, clampWidth, computeColumns, RIGHTBAR_DEFAULT_RATIO, RIGHTBAR_MAX_RATIO, RIGHTBAR_MIN, SIDEBAR_AUTO_COLLAPSE, SIDEBAR_COLLAPSED, SIDEBAR_DEFAULT } from './columns.ts' +import { CENTER_MIN, clampWidth, computeColumns, RIGHTBAR_DEFAULT_RATIO, RIGHTBAR_MAX_RATIO, RIGHTBAR_MIN, SIDEBAR_AUTO_COLLAPSE, SIDEBAR_COLLAPSED, SIDEBAR_DEFAULT, SIDEBAR_DRAWER_BREAKPOINT } from './columns.ts' import { DocumentTitle } from './DocumentTitle.tsx' import type { createLayoutStore } from './stores.ts' import css from './AppFrame.module.css' -/** Full composed props: runtime share + child-slot render share + store share. */ +/** Browser posture supplied by the root registration. */ +export interface AppFrameInjected { + hooks: { foldedLandscape: HostObservable } +} + +/** Full composed props: runtime, child slots, store, locale, and injected posture. */ export type AppFrameProps = & PropsRuntime<'root'> & PropsRenderSlots<'sidebar' | 'main' | 'rightbar' | 'shell.bottom' | 'shell.overlay' | 'shell.leading'> & PropsStore> & PropsLocale<'common'> + & InjectFace /** Center column grid item (session-body building block). */ -function CenterColumn(props: { children?: ReactNode }) { - return
{props.children}
+function CenterColumn(props: { children?: ReactNode; inert: boolean }) { + return
{props.children}
} /** Subscribe to the main key without subscribing the column frame to each panel id. */ function MainPanel({ usePanelInfo, renderSlot }: Pick, 'usePanelInfo'> & PropsRenderSlots<'main'>) { const panelId = usePanelInfo(info => info.activePanelId) - return renderSlot('main', {}, { entryKey: panelId ?? 'conversation' }) + return
+ {renderSlot('main', {}, { entryKey: panelId ?? 'conversation' })} +
} /** @@ -47,8 +55,8 @@ function MainPanel({ usePanelInfo, renderSlot }: Pick, 'use * occupant's panel is positioned against the column's right edge, which never * moves, so it can hang over the centre when there is no track. */ -function RightbarColumn(props: { children?: ReactNode }) { - return
{props.children}
+function RightbarColumn(props: { children?: ReactNode; inert: boolean }) { + return
{props.children}
} /** @@ -122,6 +130,7 @@ export function AppFrame({ useStore, useSessions, usePanelInfo, + useFoldedLandscape, actions, renderSlot, t, @@ -129,6 +138,7 @@ export function AppFrame({ const layoutInfo = useStore(state => state.layoutInfo) const frameRef = useRef(null) const viewport = layoutInfo.viewportWidth + const foldedLandscape = useFoldedLandscape(matches => matches) // Track the frame's own box (not the window): rAF-throttled ResizeObserver. useLayoutEffect(() => { @@ -158,7 +168,16 @@ export function AppFrame({ }, [actions]) const narrow = viewport < SIDEBAR_AUTO_COLLAPSE + const windowsTitlebar = document.documentElement.hasAttribute('data-windows-titlebar') + const drawer = viewport < SIDEBAR_DRAWER_BREAKPOINT && !windowsTitlebar + const centeredSidebar = foldedLandscape && viewport >= SIDEBAR_DRAWER_BREAKPOINT const sidebarCollapsed = narrow ? !layoutInfo.narrowExpanded : layoutInfo.sidebar === 0 + const drawerOpen = drawer && !sidebarCollapsed + // Entering drawer mode from a collapsed rail hides the backing immediately. + const [sidebarTransition, setSidebarTransition] = useState({ drawer, collapsed: sidebarCollapsed, instant: true }) + if (sidebarTransition.drawer !== drawer || sidebarTransition.collapsed !== sidebarCollapsed) { + setSidebarTransition({ drawer, collapsed: sidebarCollapsed, instant: drawer && sidebarCollapsed && sidebarTransition.collapsed }) + } const sidebarPreference = sidebarCollapsed ? 0 : layoutInfo.sidebar === 0 ? SIDEBAR_DEFAULT : layoutInfo.sidebar @@ -166,12 +185,15 @@ export function AppFrame({ // Desktop reopen controls occupy the frame's shell.leading seat (macOS) or // the Windows caption row; neither platform keeps an icon rail. const darwin = document.documentElement.dataset.platform === 'darwin' - const collapsedWidth = darwin - || document.documentElement.hasAttribute('data-windows-titlebar') ? 0 : SIDEBAR_COLLAPSED + const collapsedWidth = drawer || darwin || windowsTitlebar ? 0 : SIDEBAR_COLLAPSED // Opening on a narrow frame collapses the left sidebar. Eligibility must // include that space before the occupant's first shown report arrives. - const normal = computeColumns(viewport, !layoutInfo.rightbarShown && narrow ? 0 : sidebarPreference, rightbarPreference, collapsedWidth) - const cols = computeColumns(viewport, sidebarPreference, layoutInfo.rightbarTrack ? rightbarPreference : 0, collapsedWidth) + const normal = computeColumns( + viewport, !layoutInfo.rightbarShown && narrow ? 0 : sidebarPreference, rightbarPreference, collapsedWidth, centeredSidebar, + ) + const cols = computeColumns( + viewport, drawer ? 0 : sidebarPreference, layoutInfo.rightbarTrack ? rightbarPreference : 0, collapsedWidth, centeredSidebar, + ) const colsRef = useRef(cols) colsRef.current = cols const rightbarWidth = useRef(normal.rightbar) @@ -185,8 +207,8 @@ export function AppFrame({ // Track-level transitions pause for the whole gesture: eased tracks would // detach the column edge from the pointer (AppFrame.module.css). const [dragging, setDragging] = useState(false) - // Track easing is scoped to a discrete open/close toggle: data-animating - // goes up when the collapse state or the rightbar track flips and comes down + // Track easing is scoped to discrete open/close and fold changes: data-animating + // goes up when the sidebar presentation or the rightbar track flips and comes down // at transition end (timeout as the reduced-motion/covered-frame fallback). // Steady-state viewport updates stay instant (AppFrame.module.css), and so // does a toggle arriving together with a viewport change — that is the @@ -194,15 +216,21 @@ export function AppFrame({ // chase the live window edge. The counter restarts the settle window when a // re-toggle interrupts a running transition. const [animating, setAnimating] = useState(0) - const trackToggle = `${sidebarCollapsed}:${layoutInfo.rightbarTrack}` + const trackToggle = `${sidebarCollapsed}:${layoutInfo.rightbarTrack}:${centeredSidebar}` const previousToggle = useRef(trackToggle) const previousViewport = useRef(viewport) + // Arm the transition before child layout effects measure the new column widths. + const animateTracks = previousViewport.current === viewport && (animating > 0 || previousToggle.current !== trackToggle) useLayoutEffect(() => { const viewportChanged = previousViewport.current !== viewport previousViewport.current = viewport + if (viewportChanged) { + previousToggle.current = trackToggle + setAnimating(0) + return + } if (previousToggle.current === trackToggle) return previousToggle.current = trackToggle - if (viewportChanged) return setAnimating(token => token + 1) }, [trackToggle, viewport]) useEffect(() => { @@ -239,10 +267,14 @@ export function AppFrame({ // whole and was corrected two frames later — visible jitter. cols keeps only // the discrete decisions (track present, collapse state) and the drag base. const rightbarMax = cols.rightbar === 0 ? 0 : clampWidth(rightbarPreference, RIGHTBAR_MIN, viewport * RIGHTBAR_MAX_RATIO) + const sidebarWidth = drawer + ? Math.min(layoutInfo.sidebar || SIDEBAR_DEFAULT, Math.max(0, viewport - 48)) + : cols.sidebar const sidebar = useMemo(() => renderSlot('sidebar', { collapsed: sidebarCollapsed, - width: cols.sidebar, - }), [renderSlot, sidebarCollapsed, cols.sidebar]) + width: sidebarWidth, + drawer, + }), [renderSlot, sidebarCollapsed, sidebarWidth, drawer]) const main = useMemo(() => ( ), [usePanelInfo, renderSlot]) @@ -253,52 +285,58 @@ export function AppFrame({ // row (ui-sidebar). AppFrame.module.css publishes the matching // --dsh-frame-leading-clearance under the same collapsed condition. const leading = useMemo(() => renderSlot('shell.leading', {}), [renderSlot]) - const leadingMounted = darwin && sidebarCollapsed + const leadingMounted = drawer || darwin && sidebarCollapsed return (
0 || undefined} + data-animating={animateTracks || undefined} > -
+ {drawer &&
diff --git a/packages/client/web/src/base.css b/packages/client/web/src/base.css index af74988cf1..3a556a982e 100644 --- a/packages/client/web/src/base.css +++ b/packages/client/web/src/base.css @@ -89,6 +89,13 @@ html[data-platform='darwin'] :is( -webkit-app-region: no-drag; } +/* Reset both native region types for inert content. Chromium treats the explicit + `none` keyword as `no-drag`, which would erase foreground drag rows. */ +html[data-platform='darwin'] [inert], +html[data-platform='darwin'] [inert] * { + -webkit-app-region: initial; +} + code, pre, [data-diff], diff --git a/packages/compaction/compaction-basic/README.i18n.yaml b/packages/compaction/compaction-basic/README.i18n.yaml index 9e67ab2df6..e2609ea23a 100644 --- a/packages/compaction/compaction-basic/README.i18n.yaml +++ b/packages/compaction/compaction-basic/README.i18n.yaml @@ -57,8 +57,8 @@ en: 313e019b1a9f8aa8 zh: 3c75d11b02adb693 /deepseek-ai-dsh-compaction-basic/understand-the-implementation/source-map: - en: 3f1d7a55b790e623 - zh: 39e878c0785a885c + en: 747bad235fbb04ad + zh: 02e6562f3d745d4f /deepseek-ai-dsh-compaction-basic/further-exploration: en: 84b5b81eb9b5965d zh: 7000af0fa502fcc1 diff --git a/packages/compaction/compaction-basic/README.md b/packages/compaction/compaction-basic/README.md index 3956c8a57d..c8d0c6b748 100644 --- a/packages/compaction/compaction-basic/README.md +++ b/packages/compaction/compaction-basic/README.md @@ -148,6 +148,8 @@ The transaction validates the surface span and the durable lock, appends `compac | [`src/config.ts`](src/config.ts) | Load-time validation and routed-model policy resolution | | [`src/types.ts`](src/types.ts) | `BasicCompactionConfig` and resolved policy vocabulary | +The package root's type declarations add `compaction` to `LlmRequestPurposeMap`. Direct callers constructing compaction requests use `import type {} from '@deepseek-ai/dsh-compaction-basic'` so `GenerateOptions.purpose` includes that key. +
----- diff --git a/packages/compaction/compaction-basic/README.zh.md b/packages/compaction/compaction-basic/README.zh.md index 283a4d19eb..023d9ea436 100644 --- a/packages/compaction/compaction-basic/README.zh.md +++ b/packages/compaction/compaction-basic/README.zh.md @@ -148,6 +148,8 @@ kind: "package-reference" | [`src/config.ts`](src/config.ts) | 加载时验证与路由模型策略解析 | | [`src/types.ts`](src/types.ts) | `BasicCompactionConfig` 与已解析策略词汇 | +包根入口的类型声明将 `compaction` 添加到 `LlmRequestPurposeMap`。直接构造压缩请求的调用方使用 `import type {} from '@deepseek-ai/dsh-compaction-basic'`,使 `GenerateOptions.purpose` 包含该键。 + ----- diff --git a/packages/compaction/compaction-basic/src/types.ts b/packages/compaction/compaction-basic/src/types.ts index e8160dba2c..23e195aab7 100644 --- a/packages/compaction/compaction-basic/src/types.ts +++ b/packages/compaction/compaction-basic/src/types.ts @@ -4,6 +4,12 @@ * @module @deepseek-ai/dsh-compaction-basic/types */ +declare module '@deepseek-ai/dsh-llm/types' { + interface LlmRequestPurposeMap { + 'compaction': true + } +} + import type { LlmCallConfig } from '@deepseek-ai/dsh-llm' /** Policy fields shared by the default policy and exact model overrides. */ diff --git a/packages/core/session/tests/json.spec.ts b/packages/core/session/tests/json.spec.ts index e213fc9a17..a6de09218b 100644 --- a/packages/core/session/tests/json.spec.ts +++ b/packages/core/session/tests/json.spec.ts @@ -13,7 +13,7 @@ function objectWithForgedIntrinsicPrototype(revoked = false): Record, { value: 1 }) } -describe('snapshotJsonValue', () => { +describe('snapshotJsonValue and isJsonValue', () => { it('copies the complete JSON scalar vocabulary and rejects unsupported scalars', () => { const unsupportedFunction = (): void => {} @@ -120,6 +120,111 @@ describe('snapshotJsonValue', () => { expect(arrayReads).toBe(1) }) + it.each(['snapshot', 'predicate'] as const)('keeps captured keys and lengths with depth-first getter reads in %s mode', (mode) => { + const reads: string[] = [] + const items: unknown[] = [0, 1] + Object.defineProperty(items, 0, { + enumerable: true, + get: () => { + reads.push('item') + items[1] = 7 + items.push('added') + return { get child() { reads.push('child'); return 3 } } + }, + }) + const source = { + get items() { + reads.push('items') + Object.defineProperty(source, 'added', { + enumerable: true, + get: () => { reads.push('added'); return 9 }, + }) + return items + }, + get tail() { reads.push('tail'); return 4 }, + } + + const result = mode === 'snapshot' ? snapshotJsonValue(source) : isJsonValue(source) + + expect(result).toEqual(mode === 'snapshot' ? { items: [{ child: 3 }, 7], tail: 4 } : true) + expect(reads).toEqual(['items', 'item', 'child', 'tail']) + }) + + it.each(['snapshot', 'predicate'] as const)('rejects an array slot deleted by an earlier getter in %s mode', (mode) => { + const source = [0, 1] + Object.defineProperty(source, 0, { + enumerable: true, + get: () => { + Reflect.deleteProperty(source, 1) + return 0 + }, + }) + + expect(mode === 'snapshot' ? snapshotJsonValue(source) : isJsonValue(source)) + .toBe(mode === 'snapshot' ? undefined : false) + }) + + it.each(['snapshot', 'predicate'] as const)('uses one captured Proxy index schedule in %s mode', (mode) => { + for (const secondLength of [2, 1.5, Number.NaN]) { + let coercions = 0 + const length = { + valueOf() { + coercions += 1 + if (coercions > 2) throw new Error('length was coerced again') + return coercions === 1 ? 2 : secondLength + }, + } + const source = new Proxy([1, 2], { + get(target, key): unknown { + if (key === 'length') return length + const value: unknown = Reflect.get(target, key) + return value + }, + }) + const expected = Number.isNaN(secondLength) ? [] : secondLength === 2 ? [1, 2] : undefined + + const result = mode === 'snapshot' ? snapshotJsonValue(source) : isJsonValue(source) + + expect(result).toEqual(mode === 'snapshot' ? expected : expected !== undefined) + expect(coercions).toBe(2) + } + }) + + it.each([false, true])('does not read an array slot outside a fractional Proxy length, throwing slot=%s', (throwing) => { + let reads = 0 + const source = new Proxy([42], { + get(target, key): unknown { + if (key === 'length') return 1 - Number.EPSILON / 2 + if (key === '0') { + reads += 1 + if (throwing) throw new Error('array slot must not be read') + } + const value: unknown = Reflect.get(target, key) + return value + }, + }) + + expect(JSON.stringify(source)).toBe('[]') + expect(snapshotJsonValue(source)).toEqual([]) + expect(isJsonValue(source)).toBe(true) + expect(reads).toBe(0) + }) + + it('detaches every occurrence of a shared child in a wide array', () => { + const shared = { nested: [{ value: 1 }] } + const source = Array.from({ length: 4_096 }, () => shared) + + expect(isJsonValue(source)).toBe(true) + const snapshot = snapshotJsonValue(source)! + expect(snapshot).toEqual(source) + shared.nested[0]!.value = 2 + snapshot[0]!.nested[0]!.value = 3 + + expect(source.at(-1)?.nested[0]?.value).toBe(2) + expect(snapshot[0]?.nested[0]?.value).toBe(3) + expect(snapshot.at(-1)?.nested[0]?.value).toBe(1) + }) + it('accepts deeply nested valid JSON without using the JavaScript call stack', () => { let value: JsonValue = 'leaf' for (let depth = 0; depth < 5_000; depth++) value = [value] diff --git a/packages/experimental/auto-review/README.i18n.yaml b/packages/experimental/auto-review/README.i18n.yaml index f045208cdf..b4345e70f0 100644 --- a/packages/experimental/auto-review/README.i18n.yaml +++ b/packages/experimental/auto-review/README.i18n.yaml @@ -45,8 +45,8 @@ en: 9c3e575c061d53fe zh: 74db1c5a77b2d2a7 /deepseek-ai-dsh-experimental-auto-review/model-experience/per-call-reviewer/kv-cache-effect: - en: 941f6afc75f896e7 - zh: 54800fb8feaa6718 + en: ec9e16640f1ea1bc + zh: 8052d486d61807c6 /deepseek-ai-dsh-experimental-auto-review/model-experience/tool-denial: en: f9b4d7b686f14fc5 zh: a2fac9a8eaf5e2a3 @@ -60,8 +60,8 @@ en: 8da1089dee147f94 zh: 87361347bfd10c6c /deepseek-ai-dsh-experimental-auto-review/known-limitations-and-deferred-work: - en: 6ab80358ea26c1c3 - zh: b80dc28e3c3524bf + en: a48835d5113cbcfd + zh: 243ff731c27270b7 /deepseek-ai-dsh-experimental-auto-review/known-limitations-and-deferred-work/dev-note: en: e67f633dc6fe7773 zh: 3bb0c20c93f16f98 diff --git a/packages/experimental/auto-review/README.md b/packages/experimental/auto-review/README.md index 273c40ce5f..63f136177d 100644 --- a/packages/experimental/auto-review/README.md +++ b/packages/experimental/auto-review/README.md @@ -110,7 +110,7 @@ One additional model request per supported call, without caching, retries, trunc #### KV Cache effect -Each review's messages begin with all messages of the previous review, including its pending call, so routes that cache by prompt prefix, at message ends, or at a final marker with lookback reuse the policy and earlier history. Compaction, a cwd change, an earlier item leaving the surface, and the first review after a restart end that reuse once. Auto adds no dedicated runtime context or mode-switch prompt to the main agent. +Each review's messages begin with all messages of the previous review, including its pending call, so routes that cache by prompt prefix, at message ends, or at a final marker with lookback reuse the policy and earlier history. Compaction, a cwd change, an earlier item leaving the surface, and the first review after a restart end that reuse once. Auto adds no dedicated runtime context or mode-switch prompt to the main agent. Each review request carries the reviewed Session's `sessionId` and `purpose: 'auto-review'` as model-hidden transport metadata. Routes that key prompt caching or request routing by Session, such as OpenAI `prompt_cache_key` and the `x-opencode-session` header that OpenCode requires, send reviews under that Session's key; [the DeepSeek Session-log upload](../../session/session-log-deepseek/README.md#request-field) contributes the canonical Session log when enabled and no registered exclusion matches. ### Tool denial @@ -136,7 +136,6 @@ The denial appends an ordinary tool result; it does not rewrite earlier context - Model classification can be wrong. There are no deterministic tool exemptions, persistent grants, configurable policy, or retry layer. - In-process Auto children review their own calls. Out-of-process children retain their native permission systems after the parent delegation call is allowed. - The reviewer reads the Session action history through the deprecated synchronous `snapshotEvents()` reader under a line-scoped waiver. Prior calls, PTC starts, and the direct parent's initial prompt have no projection or paged reader yet, so the migration stays deferred by [the synchronous-read decision](../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md). -- Review requests carry no `sessionId`, so OpenAI routes receive no `prompt_cache_key`. Passing it would also attach the DeepSeek session-log upload and session headers to review requests, which first needs a request-purpose decision. ### Dev Note diff --git a/packages/experimental/auto-review/README.zh.md b/packages/experimental/auto-review/README.zh.md index a7893291e6..39aa14ce15 100644 --- a/packages/experimental/auto-review/README.zh.md +++ b/packages/experimental/auto-review/README.zh.md @@ -110,7 +110,7 @@ Reviewer 使用最新 `request/header.config` 的 provider 与模型,并沿用 #### KV Cache 影响 -每次评审的消息都以上一次评审的全部消息(包括其待审调用)开头,因此按 prompt 前缀、按消息结尾或在末尾标记处回溯缓存的路由都能复用策略与先前历史。Compaction、cwd 变化、较早条目离开 surface,以及重启后的第一次评审会让复用中断一次。Auto 不向主 agent 增加专门 runtime context 或模式切换提示词。 +每次评审的消息都以上一次评审的全部消息(包括其待审调用)开头,因此按 prompt 前缀、按消息结尾或在末尾标记处回溯缓存的路由都能复用策略与先前历史。Compaction、cwd 变化、较早条目离开 surface,以及重启后的第一次评审会让复用中断一次。Auto 不向主 agent 增加专门 runtime context 或模式切换提示词。每个评审请求都携带被评审 Session 的 `sessionId` 和 `purpose: 'auto-review'`,作为模型不可见的传输元数据。按 Session 划分 prompt 缓存或请求路由的路由(例如 OpenAI 的 `prompt_cache_key`,以及 OpenCode 要求的 `x-opencode-session` header)会以该 Session 的键发送评审;[DeepSeek session-log 上传](../../session/session-log-deepseek/README.zh.md#request-field)在启用且没有已注册排除条件匹配时贡献权威 Session 日志。 ### 工具拒绝 @@ -136,7 +136,6 @@ Reviewer 使用最新 `request/header.config` 的 provider 与模型,并沿用 - 模型分类可能出错。不提供确定性工具豁免、持久 grant、可配置策略或重试层。 - 进程内 Auto child 独立审查自身调用。进程外 child 在父委派调用获准后保留原生权限系统。 - reviewer 在带行级豁免的情况下,通过已废弃的同步 `snapshotEvents()` 读取 Session 动作历史。此前的调用、PTC start 与直接父级的初始 prompt 目前都没有投影或分页读取方,因此迁移按[同步读取决策](../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.zh.md)继续延期。 -- 评审请求不携带 `sessionId`,因此 OpenAI 路由不会收到 `prompt_cache_key`。传入它还会让评审请求附带 DeepSeek session-log 上传与 session header,需要先做请求用途决策。 ### 开发备注 diff --git a/packages/experimental/auto-review/src/index.ts b/packages/experimental/auto-review/src/index.ts index f612447720..29df7771f0 100644 --- a/packages/experimental/auto-review/src/index.ts +++ b/packages/experimental/auto-review/src/index.ts @@ -8,6 +8,12 @@ * @module @deepseek-ai/dsh-experimental-auto-review */ +declare module '@deepseek-ai/dsh-llm/types' { + interface LlmRequestPurposeMap { + 'auto-review': true + } +} + import type {} from '@deepseek-ai/dsh-tool-executor-ptc/types' import type {} from '@deepseek-ai/dsh-working-directory' import { FiberState, type Context } from '@deepseek-ai/cordis' @@ -672,12 +678,15 @@ async function classifyRisk( const snapshot = snapshotAutoReview(agent, exec, cwd, shown) shown.set(snapshot.pending.key, snapshot.pending.schema) // This review prompt is sent only through ctx.llm.stream and never enters a Session log. + // The Session id also supplies provider routing and request-extension identity. const options: GenerateOptions = deepFreeze({ provider: snapshot.provider, model: snapshot.model, system: REVIEW_POLICY, messages: reviewMessages(snapshot), temperature: 0, + sessionId: agent.session.id, + purpose: 'auto-review', signal, }) return readDecision(ctx.llm.stream(options)) diff --git a/packages/experimental/auto-review/tests/auto-review.spec.ts b/packages/experimental/auto-review/tests/auto-review.spec.ts index 20ab50c4c4..fd9be88b47 100644 --- a/packages/experimental/auto-review/tests/auto-review.spec.ts +++ b/packages/experimental/auto-review/tests/auto-review.spec.ts @@ -414,8 +414,9 @@ describe('native review request', () => { model: 'same-model', system: EXPECTED_REVIEW_POLICY, temperature: 0, + sessionId: session.id, + purpose: 'auto-review', }) - expect(request).not.toHaveProperty('sessionId') expect(request.maxTokens).toBeUndefined() expect(request.tools).toBeUndefined() for (const message of request.messages) { diff --git a/packages/experimental/client-ui-forge/README.i18n.yaml b/packages/experimental/client-ui-forge/README.i18n.yaml index 8c53380124..2970934549 100644 --- a/packages/experimental/client-ui-forge/README.i18n.yaml +++ b/packages/experimental/client-ui-forge/README.i18n.yaml @@ -15,20 +15,20 @@ en: d152484eb41ac6b4 zh: 2f8a621b991260a1 /deepseek-ai-dsh-experimental-client-ui-forge/use-this-package: - en: 4c7d1cbc76085d84 - zh: 3f8fc65d6bea1cfb + en: 4d8f639509bd13f7 + zh: 8a1576790ac37018 /deepseek-ai-dsh-experimental-client-ui-forge/understand-the-implementation: - en: 013e84157a09da7e - zh: 99b4f276385d5e16 + en: 1849afb6a4afcc42 + zh: 5d1841f1d48e8b14 /deepseek-ai-dsh-experimental-client-ui-forge/further-exploration: en: fa4d8c579ffc49ff zh: 5856ed7469e4585b /deepseek-ai-dsh-experimental-client-ui-forge/model-experience: - en: 8dbddff9f5369ca0 - zh: 59651db8ae490342 + en: f7a1517de6265e7b + zh: 4e4ddc7e1fde8e54 /deepseek-ai-dsh-experimental-client-ui-forge/model-experience/kv-cache-effect: - en: e29ceb229a7c5b11 - zh: 6f6364154b43bb94 + en: 2bc25a99e17789c4 + zh: 4bec723fbf249d28 /deepseek-ai-dsh-experimental-client-ui-forge/known-limitations-and-deferred-work: en: a49947fd6d5909ad zh: 47afed048292b285 diff --git a/packages/experimental/client-ui-forge/README.md b/packages/experimental/client-ui-forge/README.md index e38514f161..e233cd325b 100644 --- a/packages/experimental/client-ui-forge/README.md +++ b/packages/experimental/client-ui-forge/README.md @@ -29,17 +29,21 @@ Enable the [forge bundle](../forge-bundle/README.md) on the Plugins page; it com Panel text follows the application language: Chinese, English, Japanese, Spanish, French, German, Russian, or Portuguese. -- **Worktree option** — on the New Session screen, Worktree sits at the right end of the row with the workspace and mode pickers. Checking it shows the base branch, the current branch by default; the menu lists recent local branches. The option is disabled, with the reason in its tooltip, outside a Git checkout, in a read-only Session, and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. +- **Worktree option** — on the New Session screen, New worktree sits beside the current branch at the right end of the row with the workspace and mode pickers. Both stay hidden outside a Git checkout. The branch is read-only until New worktree is checked, when it becomes the base branch selector; the menu lists recent local branches. If permissions block an existing request, its selected base stays visible without a selector and the request can still be withdrawn. Hovering, focusing, or tapping the read-only branch or base shows its full description. The option is disabled, with the reason in its tooltip, in a read-only Session and when the checkout or its Git directory lies outside the Session's writable root, as for a project that is itself a linked worktree. Sending the first message hands it to the Session at once, and it waits there while the branch `dsh--<4 random hexadecimal digits>` is created from the base under the repository's `.agents/worktrees/` and its checkout becomes the Session's working directory; the message's turn starts once the worktree exists. - **Creation card** — while the worktree is created, a card above the composer shows the new branch and its two steps, creating the branch and checking out files; More details adds the branch and base. Cancel stops the attempt. After a stopped or failed attempt the message keeps waiting, and the card shows the reason of a failure: Retry tries again with a new branch name, and Continue without a worktree withdraws the request so the message goes on in the current checkout. - **Removed worktree** — when the worktree the Session works in has been removed outside the Session, a card above the composer says so, and a message sent meanwhile waits without starting its turn until the worktree is restored or left; the card then says that the message goes on afterwards. Restore worktree, also offered as Restore in the tab, checks the branch out again at the same directory, or creates the branch again at the commit it started from when the branch is gone too; while it runs, the card follows its two steps, preparing the worktree and checking out files, and the tab's Restore turns into a spinner. Continue in the project moves the Session to the source checkout. Meanwhile the tab's first row shows a warning glyph. - **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 a dot for 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. 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. - **Local changes card** — while the `branch` scope changes files and no open change request has the checked-out branch as its head, a card above the change requests names the ref it compares with, such as `HEAD → origin/main`, 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 once the code host repository is recognized, 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. A local view shows Branch by default: the working tree and untracked files against the fork point, which is the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote. 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. Clicking the file name or directory in either diff source copies its repository-relative path and reports success or failure in a toast. 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, which is the base commit of the worktree the Session created, else the merge base of HEAD with the default branch of the code host remote. 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. + +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). +All files opens a searchable directory tree. 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 hides or restores it. The search, folds, and width survive 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. 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; 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. 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. + ----- @@ -61,7 +65,7 @@ Each inspection also decides whether the worktree is missing: the Session's dire `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`. It runs `diff --no-ext-diff --no-textconv --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. 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. -`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. 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. +`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 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. @@ -102,11 +106,11 @@ 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. Inspection, status, diffs, restoring, the Session list, and the rest of the panel add nothing to model requests. +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. 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 -None for a new worktree, as its notice belongs to the first request of the Session, before any cached prefix exists. A notice after Continue in the project and the message Create change request sends are appended after the cached prefix. +None for a new worktree, as its notice belongs to the first request of the Session, before any cached prefix exists. A notice after Continue in the project and the message Create change request sends, and submitted review quotes are appended after the cached prefix. ## Known Limitations and Deferred Work diff --git a/packages/experimental/client-ui-forge/README.zh.md b/packages/experimental/client-ui-forge/README.zh.md index 1ff38bba3c..30e6c6545f 100644 --- a/packages/experimental/client-ui-forge/README.zh.md +++ b/packages/experimental/client-ui-forge/README.zh.md @@ -29,17 +29,21 @@ kind: "package-reference" 面板文案跟随应用语言,支持中文、英文、日语、西班牙语、法语、德语、俄语和葡萄牙语。 -- **工作树选项**——在新会话页面上,“工作树”位于工作区与模式选择器那一行的右端。勾选后显示基准分支,默认为当前分支;菜单列出最近的本地分支。不在 Git 检出中、Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 +- **工作树选项**——在新会话页面上,“新建工作树”与当前分支一起位于工作区与模式选择器那一行的右端。不在 Git 检出中时,两者均隐藏。分支默认为只读展示;勾选“新建工作树”后,它变为基准分支选择器,菜单列出最近的本地分支。权限阻止已有请求时,仍只读显示已选基准,并允许取消请求。悬停、聚焦或轻点只读分支或基准会显示完整说明。Session 为只读,或检出及其 Git 目录不在 Session 的可写根内(例如项目本身就是链接 worktree)时,该选项不可用,提示中说明原因。发送第一条消息后,消息立即交给 Session 并在那里等待,同时从基准分支在仓库的 `.agents/worktrees/` 下创建分支 `dsh--<4 位随机十六进制数>`,并把它的检出设为 Session 的工作目录;worktree 建好后这条消息的这一轮才开始。 - **创建卡片**——创建 worktree 期间,输入框上方的卡片显示新分支以及“创建分支”“检出文件”两个步骤;“更多详情”会列出分支与基准。“取消”停止这次尝试。尝试被停止或失败后,消息继续等待,失败时卡片显示原因:“重试”换一个新分支名再试;“不使用工作树”撤回请求,消息在当前检出中继续发送。 - **工作树已被删除**——Session 所在的 worktree 在 Session 之外被删除后,输入框上方的卡片会说明这一点;此期间发送的消息会等待、不开始这一轮,直到该 worktree 被恢复或离开,卡片也会说明消息之后会接着发送。“恢复工作树”(标签页中的“恢复”与之相同)在原目录重新检出该分支;分支也已删除时,从它开始时的提交重新创建分支;恢复期间卡片显示“准备工作树”“检出文件”两个步骤,标签页中的“恢复”变为加载状态。“在项目目录继续”把 Session 移回源检出。此期间标签页顶部一行显示警示图标。 - **标题栏按钮**——Session 有已绑定的变更请求、或其目录位于 Git 检出中时出现,用来显示或隐藏标签页。打开状态的变更请求存在检查失败、被要求修改或冲突时,按钮带红点。 - **会话列表**——Session 在面板为它创建的 worktree 中工作时,会话行的时间之后显示分支图标;另有一个图标显示它最需要关注的变更请求的状态,依次为需要处理、打开、草稿、尚未轮询、已合并、已关闭。打开中的变更请求图标保持会话行的浅色,并用圆点标出检查进行中、已通过或失败;已合并与已关闭的保留各自的状态颜色。会话行的悬浮卡片写出 worktree 分支及其起点,再列出最多三个变更请求的编号、标题、状态与检查,并说明还有多少个。重启后,下次轮询之前显示重启前已知的状态。 - **标签页**——顶部一行显示当前检出的分支(分离 HEAD 时为缩写提交),项目目录前显示目录图标、worktree 前显示分支图标,并说明检出的类型(Session 创建的 worktree 及其基准、其他 worktree 或项目目录);它的提示给出路径,宿主主目录缩写为 `~`,旁边的按钮复制完整路径;worktree 已被删除时提供“恢复”。其下每张变更请求卡片显示状态图标、标题(点击在浏览器中打开)与编号;图标区分打开、草稿、已合并与已关闭,打开中的变更请求(草稿除外)检查失败、被要求修改或有冲突时显示为“需要处理”,与标题栏按钮的红点一致。卡片右上角还提供“在浏览器中打开”“复制变更请求链接”与“从本会话移除”,移除后的 toast 提供“撤销”。折叠的卡片还显示打开的变更请求的检查,以及被要求修改、冲突、草稿中最需要注意的一项;已合并或已关闭的则显示结束时间。展开的卡片显示源分支与目标分支,下面每项一行:打开的变更请求依次是检查(点击该行弹出检查列表,失败的排在前面,带耗时与链接)、评审结论与未解决讨论数、合并状态,已合并或已关闭的显示结束时间;最后是按所选界面语言格式化的变更行数,点击该行打开变更视图。打开中的草稿还提供“标记为可评审”;主机现在就会合并的变更请求提供“合并”,其菜单列出仓库允许的合并方式并选中用户常用的一种,打开时固定卡片显示的 head。“确认合并”使用这个 head;轮询发现 head 变化后禁用确认,需重新检查并打开菜单。每次操作的结果都以 toast 报告;该 head 之后有新提交时不会合并。恰好有一个已绑定的变更请求处于打开状态时,它的卡片默认展开。刷新会重新检查检出与登录状态,并立即再次轮询每个变更请求;检查与登录状态确认结束前,刷新图标持续旋转。缺少登录时,横幅显示 `gh auth login` 命令。 -- **变更卡片**——`branch` 范围有文件变更、且没有以当前检出分支为源分支的打开中变更请求时,变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库后,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 -- **变更视图**——展开的变更请求卡片上的“变更”一行与变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地变更默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更;分叉点是 Session 创建的 worktree 的基准提交,否则是 HEAD 与代码托管远端默认分支的合并基准。“未提交”与 HEAD 比较,“未暂存”与暂存区比较,“已暂存”比较暂存区与 HEAD。变更请求的视图显示托管平台在其 head 处的 diff;当前检出分支就是该变更请求的源分支时,还会说明本地分支比该 head 多出几个提交。工具栏可以跳到某个文件、汇总变更行数、刷新,并在左右对比与单栏对比、自动换行与截断长行之间切换。访问过的变更标签页会在切换标签页与 Session、隐藏侧边栏及调整停靠位置时保持挂载,在 diff 未改变时保留文件折叠、大文件展开、上下文展开、布局与滚动位置。隐藏的变更视图释放面板订阅并推迟 diff 读取;返回时仅在最新 head 或本地摘要不同时重新读取。刷新替换 diff 后会丢弃展开的上下文,内容变化也可能移动阅读位置。视图隐藏时关闭临时菜单。关闭标签页或重新加载应用后不保留这些进度。文件名在前,目录在后,用更小的浅色字显示,空间不够时目录先缩短;悬停时显示完整路径,重命名的文件显示新旧两条路径。两种 diff 来源中,点击文件名或目录都会复制仓库相对路径,并通过 toast 报告成功或失败。每个文件带有新文件、已删除、重命名的标记(重命名标记写出原文件名,只换了目录时写出原路径),“分支”范围下的未跟踪文件还标“未提交”;文件菜单可以复制路径,本地变更可在侧边栏打开整个文件,变更请求可在浏览器中查看该文件在 head 处的页面。hunk 之间未变更的行折叠成一行,点击后从文件的新版本展开:工作树、“已暂存”时为暂存区,或经托管平台读取的 head 提交;读取 diff 之后文件又有修改时不会展开,直到视图重新读取。二进制文件与超过 `maxDiffBytes` 的未跟踪文件只显示一条说明;hunk 超过 1,000 行的文件先显示为一条写出变更行数的折叠条,点击后才绘制;前面的文件累计变更超过 5,000 行后,其后的文件默认收起。刷新与页面刷新快捷键、每次导航、变更请求的 head 变化,以及“分支”范围的摘要变化时,视图都会重新读取;变更请求的视图会先等到给出 head 的状态再读取,除非没有提供方服务它或那次轮询失败。重新读取已显示的变更时,刷新图标会旋转。托管平台或其提供方因超过大小上限拒绝给出 diff 的变更请求(例如 GitHub 上超过 300 个文件的 diff)显示“变更太大,无法在这里显示”并提供“在浏览器中查看”;其他读取失败提供“重试”,变更请求还提供“在浏览器中查看”。变更请求的 diff 在缓存期间对每个 head 提交与目标分支只下载一次,因此在同一 head 下重新打开、刷新与导航都不会再从托管平台读取。 +- **本地变更卡片**——`branch` 范围有文件变更、且没有以当前检出分支为源分支的打开中变更请求时,变更请求列表上方的卡片显示比较的基准(例如 `HEAD → origin/main`)以及新增、删除行数与文件数,点击打开变更视图;展开的文件列表像变更视图一样标出各个文件,点击某个文件时,变更视图定位到该文件。识别出代码托管仓库后,卡片提供“创建变更请求”:它以界面语言向 Session 发送一条用户消息,请 Agent 为这些变更创建变更请求,并以 toast 报告是否已发送。 +- **变更视图**——展开的变更请求卡片上的“变更”一行与本地变更卡片会打开一个右侧边栏标签页,列出所有变更的文件。本地标签页名为“本地变更”,默认显示“分支”:工作树与未跟踪文件相对于分叉点的变更;分叉点是 Session 创建的 worktree 的基准提交,否则是 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 下重新打开、刷新与导航都不会再从托管平台读取。 + +点击 diff 内容区可将焦点移入。左右方向键按 diff 顺序跳到上一个、下一个文件并展开它;到达首尾时停留。上下方向键保留原有滚动行为。手动滚动后,文件跳转从视口顶部的文件继续。文本编辑、非折叠文本选区、组合键、菜单与文件树控件保留各自的键盘行为。 `gitCommand`、`gitTimeoutMs`、`graceMs`、`maxOutputBytes`、`readinessTimeoutMs`、`maxBranches`、`worktreePrefix`、`maxDiffBytes`、`maxUntrackedFiles` 与 `maxCachedDiffBytes` 列在[配置目录](../../../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 并明确允许再次提交。 + ----- @@ -50,7 +54,7 @@ kind: "package-reference" `ForgePanelController` 为每个被关注的 Session 保留一个 `SessionPanel`,最后一个关注方离开时销毁它。面板从 Session 的工作目录与绑定开始,在每个 `working-directory/change`、`tool/result` 与 `sandbox/mode` 事件之后重新检查,每次变化都发布新的 `ForgePanelState`。每个变更请求在后续轮询失败时保留最近一次轮询得到的快照。并行 Git 读取失败时会取消并等待同批读取结束。检查一次只运行一个,最多再追加一次;Session 已离开的目录的结果会被丢弃。代码托管平台按远端顺序识别:先是上游所在的远端,然后是 `origin`,最后是其余远端。检查发现提供方识别的远端上有上游分支时,面板调用 `ctx.forgeSession.discoverBranch` 绑定该分支打开状态的变更请求;同一远端与分支在刷新前只查找一次。识别出的托管平台变化时以及刷新时,会在 `readinessTimeoutMs` 内检查登录状态;一次刷新在它触发的检查与登录状态检查结束后完成,轮询结果之后才到达。 -检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`。之后,检查会为变更卡片统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,并列出未跟踪文件。每个命令都在 Session 的只读沙箱策略下运行,禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 +检查运行 `rev-parse --show-toplevel`、`rev-parse --path-format=absolute --git-common-dir`、`rev-parse --path-format=absolute --git-dir`、`symbolic-ref --short HEAD`、`rev-parse --short HEAD`、`rev-parse --abbrev-ref @{upstream}` 与 `remote -v`;`branches` 运行 `symbolic-ref` 与 `for-each-ref --count=`。之后,检查会为本地变更卡片统计 `branch` 范围的规模:找出分叉点,对它运行 `diff --numstat -z -M`,并列出未跟踪文件。每个命令都在 Session 的只读沙箱策略下运行,禁用可选的索引写入、钩子、文件系统监视器、提示与对象的延迟获取,移除继承的 Git 选择器与携带密钥的变量,并各自受 `gitTimeoutMs` 时限与每个输出流的 `maxOutputBytes` 上限约束。Git 打印的顶层目录、Git 目录与公共 Git 目录经 `ctx.fs` 解析为工作目录服务记录的规范进程路径;Git 目录与公共 Git 目录不同的检出是链接 worktree。工作树选项在 `danger-full-access` 沙箱模式下可用,在 `read-only` 下不可用,在 `workspace-write` 下只有两个目录都位于 Session 沙箱策略的规范工作区根内时才可用。 worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWorktree` 投影折叠:请求与撤回在第一个 `turn/start` 或创建之前生效;在第一个 `step/start` 之前,未完成请求的第一条 `created` 记录生效。该投影还从 Session 头部与每个 `working-directory/change` 记录 Session 的目录;它的客户端视图随 Session 摘要下发,在该目录就是所创建的 worktree 或位于其下时为该 worktree,否则为 null。一轮开始或 worktree 已创建之后,`requestWorktree` 以 `forgePanel/session-started` 拒绝;没有 `worktrees` 服务时以 `forgePanel/worktrees-unavailable` 拒绝;分支名为空时以 `forgePanel/invalid-branch` 拒绝;`cancelWorktree` 只以第一种拒绝,也不需要 `worktrees` 服务;两者都会忘掉失败的尝试。消息进入有未完成请求的 Session 的收件箱时,一个 `agent/inbox/inserted` 监听器在这次投递唤醒 Agent 之前启动 Session 所属 Agent 的维护任务,因此 Agent 会暂存唤醒,等这次暂留结束后才开始这条消息的这一轮。暂留使用新分支名进行一次尝试,在面板状态中发布正在进行的阶段,设置 `held`,`waiting` 为 `creation`,并记录带源仓库根目录的 `created`。尝试失败(其分支、基准、失败步骤与原因以 `failure` 留在面板状态中)或经 `stopCreation` 停止后,暂留继续等待:`retryWorktree` 再做一次尝试,没有消息等待或已有尝试进行时以 `forgePanel/not-waiting` 拒绝;撤回请求则让消息在当前检出中继续。Agent 空闲且 Session 在所创建 worktree 中工作时,进入的每条消息都会启动一次暂留,检查该 worktree 是否缺失;缺失期间暂留以 `waiting` 为 `restoration` 等待,`restoreWorktree` 或 `continueInProject` 在暂留内运行,之后放行消息;检查无法给出结果时立即放行。Agent 的取消与 Remote 的停止都会结束暂留;Agent 正在运行一轮或其他维护任务时进入的消息不会被暂留。worktree 服务把工作目录通知排进队列,由第一步认领。一个 `agent/pre-step` 监听器在请求仍未完成的 Session 的第 1 步创建 worktree,覆盖没有被暂留的消息;它把通知移入本步提议的消息,失败时这一轮结束、请求保留。没有消息等待时,`restoreWorktree` 与 `continueInProject` 以各自的维护任务运行;`restoreWorktree` 以 `restoration` 发布正在进行的步骤,并在结束恢复的同一状态中清除 `missing`。套件把它的 `worktrees` 服务隔离,因此同时启用 Git Worktrees 时会有两个互不影响的服务。`track` 以 `forgePanel/unrecognized-url` 拒绝没有提供方识别的 URL。`markReady` 与 `merge` 只作用于该 Session 中由提供方服务的可见绑定,否则以 `forgePanel/not-bound` 拒绝;`merge` 带上卡片显示的 head 提交,head 已变化时以 `forgePanel/stale-head` 拒绝,其他拒绝都是带主机原因的 `forgePanel/action-failed`。 @@ -61,7 +65,7 @@ worktree 请求是一条 `plugin:client-ui-forge/worktree` 记录,由 `forgeWo Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommit` 为分叉点;否则按代码托管远端的顺序,对每个远端依次运行 `symbolic-ref --quiet --short refs/remotes//HEAD` 与 `merge-base HEAD` 找出分叉点;找不到时 `branch` 范围以 `forgePanel/no-fork-point` 拒绝。它以固定的 `a/`、`b/` 前缀和 `core.quotePath=false` 运行 `diff --no-ext-diff --no-textconv --no-color -M`,分别与分叉点、HEAD(第一次提交之前为空树)、暂存区比较,或带 `--cached` 与 HEAD 比较。未跟踪文件由 `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。 -`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 存储服务时,流以失败结束。 +`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 读取,并用共享的代码高亮器高亮各行;标签页标题显示变更图标与视图名称。 @@ -77,7 +81,7 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi | [`src/local-diff.ts`](src/local-diff.ts) | 分叉点、本地范围、新版本文本与 `branch` 范围摘要 | | [`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/LocalChangesCard.tsx`](src/client/LocalChangesCard.tsx) | 本地变更卡片 | | [`src/client/ChangesTab.tsx`](src/client/ChangesTab.tsx) | 变更视图 | | [`src/client/DiffFile.tsx`](src/client/DiffFile.tsx) | 变更视图中的一个文件 | | [`src/client/FileLabel.tsx`](src/client/FileLabel.tsx) | 变更文件的标签:文件名在前,目录在后 | @@ -102,11 +106,11 @@ Session 在所创建的 worktree 中工作时,`localDiff` 以它的 `baseCommi ## 模型体验 -间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。检查、状态、diff、恢复、会话列表与面板的其余部分都不会给模型请求增加内容。 +间接影响,经由工作目录服务与 Session 的对话:关于 Session 新 worktree 的通知会加入第一次请求的消息,“在项目目录继续”会为下一次请求排入同类通知,“创建变更请求”会发送一条请 Agent 创建变更请求的用户消息。“添加到输入框”提供以 `## User Comment N` 开头的冻结引用,包含 File、Side、Lines、Source、diff hunk 与 Comment;PR 引用还包含评审的提交。只有发送主输入框后,这些引用才进入正常记录的用户消息。检查、状态、恢复、会话列表与 GitHub 评审提交不会增加模型上下文。 #### KV Cache 影响 -新 worktree 的通知没有影响,因为它属于 Session 的第一次请求,那时还没有任何缓存前缀。“在项目目录继续”之后的通知与“创建变更请求”发送的消息都追加在缓存前缀之后。 +新 worktree 的通知没有影响,因为它属于 Session 的第一次请求,那时还没有任何缓存前缀。“在项目目录继续”之后的通知、“创建变更请求”发送的消息与发送后的评审引用都追加在缓存前缀之后。 ## 已知限制与待办工作 diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css new file mode 100644 index 0000000000..4a57098d20 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.module.css @@ -0,0 +1,19 @@ +/* The same directory rows fit a portal menu and the changes pane's navigation column. */ +.root { box-sizing: border-box; width: 100%; min-width: 0; display: flex; flex-direction: column; min-height: 0; color: var(--dsw-alias-label-primary); font-size: 12px; } +.search { padding: 8px; } +.rows { overflow: auto; min-height: 0; padding: 0 4px 6px; } +.row { box-sizing: border-box; display: flex; align-items: center; gap: 6px; width: 100%; min-width: 0; min-height: 30px; padding: 4px 6px; border: 0; border-radius: var(--dsw-radius-sm); background: transparent; color: inherit; font: inherit; text-align: start; cursor: pointer; } +.row svg { flex: none; } +.name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.selected { background: var(--dsw-alias-interactive-bg-hover); } +.chevron { display: inline-flex; flex: 0 0 12px; } +.collapsed { transform: rotate(-90deg); } +.empty { padding: 12px 8px; color: var(--dsw-alias-label-secondary); } +.menu { width: min(360px, calc(100vw - 24px)); } +.trigger { display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 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; } +.trigger:disabled { color: var(--dsw-alias-label-tertiary); cursor: default; } +@media (hover: hover) { .row:hover, .trigger:hover:not(:disabled) { background: var(--dsw-alias-interactive-bg-hover); } } +@media (pointer: coarse) { .row { min-height: 44px; } .search input { font-size: 16px; } } + +.searchInput { box-sizing: border-box; width: 100%; max-width: 100%; } +.searchInput input::placeholder { color: var(--dsw-alias-label-secondary); } diff --git a/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx new file mode 100644 index 0000000000..7fae97d78d --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/ChangedFiles.tsx @@ -0,0 +1,95 @@ +/** Changed-file navigation shared by the toolbar menu and wide diff pane, with a disclosure column on every row. */ +import { useMemo, useState, type ReactNode } from 'react' +import clsx from 'clsx' +import { FileTypeIcon, IconChevronDownOutlineRegular, IconFolderCloseRegular, Input, Menu, Tooltip } from '@deepseek-ai/dsh-client-ui-primitives' +import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots' +import type { ForgeDiffFile } from '../types.ts' +import { Counts } from './DiffFile.tsx' +import { changedFileTree, filterFileTree, type ChangedFileNode } from './file-tree.ts' +import type { NS } from './locales.ts' +import css from './ChangedFiles.module.css' + +/** Viewing choices remain owned by the changes tab while either navigation surface is hidden. */ +export interface ChangedFilesState { + readonly query: string + readonly collapsed: Readonly> + readonly selected: string | null +} + +/** Data and actions of the changed-file navigator. */ +export interface ChangedFilesProps extends PropsLocale { + readonly files: readonly ForgeDiffFile[] + readonly state: ChangedFilesState + readonly filter: (query: string) => void + readonly toggle: (path: string) => void + readonly jump: (path: string) => void + /** A menu row participates in the shared menu's keyboard walk. */ + readonly menu?: boolean +} + +function Rows({ nodes, depth, props }: { + readonly nodes: readonly ChangedFileNode[] + readonly depth: number + readonly props: ChangedFilesProps +}): ReactNode { + const { state, toggle, jump, menu, t } = props + return nodes.map((node) => { + const directory = node.kind === 'directory' + const expanded = directory && (state.query.trim() !== '' || state.collapsed[node.path] !== true) + const label = node.kind === 'file' && node.file.previousPath !== null + ? t('diff.renamedPath', { from: node.file.previousPath, path: node.path }) : node.path + return
+ + + + {node.kind === 'directory' && expanded && } +
+ }) +} + +/** + * Render searchable directory navigation without reading file contents. + * @param props - changed files, per-tab choices, navigation actions, and localized copy. + * @returns the search field and matching branches. + */ +export function ChangedFiles(props: ChangedFilesProps): ReactNode { + const tree = useMemo(() => changedFileTree(props.files), [props.files]) + const nodes = useMemo(() => filterFileTree(tree, props.state.query), [tree, props.state.query]) + return
+
{ props.filter(event.target.value) }} + onKeyDown={(event) => { if (['Home', 'End', 'ArrowLeft', 'ArrowRight'].includes(event.key)) event.stopPropagation() }} />
+
+ {nodes.length === 0 ?
{props.t('diff.noMatchingFiles')}
: } +
+
+} + +/** + * Open directory navigation through the existing files toolbar entry. + * @param props - navigator data and whether its owning tab is visible. + * @returns the toolbar entry and its portalled menu. + */ +export function ChangedFilesMenu({ visible, ...props }: ChangedFilesProps & { readonly visible: boolean }): ReactNode { + const [open, setOpen] = useState(false) + return { setOpen(false) }} + anchor={}> + { setOpen(false); props.jump(path) }} /> + +} 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 95b8d3410a..739513374c 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.module.css @@ -1,6 +1,7 @@ /* Changes view: the source header, the toolbar, notices, then one scrolling list of file sections whose headers stick while their lines scroll. */ .root { + container: forge-changes / inline-size; --forge-changes-bg: var(--dsw-alias-bg-base); --forge-fill: var(--dsw-static-neutral-50); --forge-diff-empty: color-mix(in srgb, var(--dsw-alias-interactive-bg-hover) 50%, transparent); @@ -227,12 +228,30 @@ margin-left: auto; } -.files { +.body { + display: flex; flex: 1; min-height: 0; +} + +.treeToggle { display: none; } + +@container forge-changes (min-width: 760px) { + .treeToggle { display: inline-flex; } + .treePane:not([hidden]) { display: block; } +} + +.files { + flex: 1; + min-width: 0; + min-height: 0; overflow: auto; } +.files:focus { + outline: none; +} + /* The actions of a failed read, side by side. */ .actions { display: flex; @@ -306,13 +325,6 @@ display: flex; flex: 0 1 auto; min-width: 0; - padding: 0; - border: 0; - background: transparent; - color: inherit; - cursor: pointer; - font: inherit; - text-align: left; } .fileSpacer { @@ -356,7 +368,7 @@ .line { display: grid; - grid-template-columns: 3.5em 3.5em 1.4em minmax(0, 1fr); + grid-template-columns: var(--forge-number-width, 3.5em) var(--forge-number-width, 3.5em) 1.4em minmax(0, 1fr); box-sizing: border-box; min-height: 22px; line-height: 22px; @@ -364,7 +376,7 @@ } .code:not([data-wrap]):not([data-split]) .line { - grid-template-columns: 3.5em 3.5em 1.4em max-content; + grid-template-columns: var(--forge-number-width, 3.5em) var(--forge-number-width, 3.5em) 1.4em max-content; } .pair { @@ -377,7 +389,7 @@ .cell { display: grid; - grid-template-columns: 3.5em minmax(0, 1fr); + grid-template-columns: var(--forge-number-width, 3.5em) minmax(0, 1fr); box-sizing: border-box; min-width: 0; } @@ -401,7 +413,8 @@ } .number { - padding-right: 8px; + box-sizing: border-box; + padding-right: 6px; color: var(--dsw-alias-label-tertiary); text-align: right; user-select: none; @@ -615,10 +628,22 @@ .localView:focus-visible, .localToggle:focus-visible, .fileToggle:focus-visible, -.filePath:focus-visible, .localFile:focus-visible, .select:focus-visible, .gap:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-state-business-primary)); outline-offset: -2px; } + +.reviewNotice { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 10px; } + +.code[data-split][data-native-side="L"] [data-diff-side="R"], +.code[data-split][data-native-side="L"] [data-diff-side="R"] *, +.code[data-split][data-native-side="R"] [data-diff-side="L"], +.code[data-split][data-native-side="R"] [data-diff-side="L"] * { user-select: none; } +.reviewSubmit { flex: none; white-space: nowrap; } + +.code[data-single-side] .line { grid-template-columns: var(--forge-number-width) 1.4em minmax(0, 1fr); } +.code[data-single-side]:not([data-wrap]) .line { grid-template-columns: var(--forge-number-width) 1.4em max-content; } +.reviewFile { padding: 12px 0; } +.reviewFile > h3 { margin: 0 10px; font-size: 12px; font-weight: 500; overflow-wrap: anywhere; } diff --git a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx index 377ea7e932..906ff4863d 100644 --- a/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx +++ b/packages/experimental/client-ui-forge/src/client/ChangesTab.tsx @@ -7,25 +7,33 @@ * scope summary changes; a read keeps the previous changes on screen until it settles. */ -import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react' +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type KeyboardEvent, type ReactNode } from 'react' import clsx from 'clsx' import { Button, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconCompareSplitOutlineRegular, IconInfoOutlineRegular, - IconListPenOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWrapFillRegular, Menu, StateDot, Tooltip, + IconListPenOutlineRegular, IconNowrapFillRegular, IconRightUpOutlineRegular, IconWorkspaceTreeOutlineRegular, IconWrapFillRegular, + Menu, StateDot, Tooltip, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' -import type {} from '@deepseek-ai/dsh-client-ui-sidebar-right/client' +import type { SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client' import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol' import { fileAddressFor, pathPartsOf } from '@deepseek-ai/dsh-util-workspace-path' import type { ForgeChangeRequestDiff, ForgeDiffFile, ForgeLocalDiff, ForgeLocalScope, ForgePanelChangeRequest, ForgePanelState, } from '../types.ts' +import type { 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' +import { SubmitReview } from './SubmitReview.tsx' +import type { ReviewSelection } from './review.ts' import { parseChangesAddress, type ChangesSource } from './changes-address.ts' import type { createChangesStore } from './changes-store.ts' import { Counts, DiffFile, type DiffFileAction } from './DiffFile.tsx' +import { FileTreePane } from './FileTreePane.tsx' +import { ChangedFilesMenu, type ChangedFilesProps, type ChangedFilesState } from './ChangedFiles.tsx' import { drawnLines, matchesHunks, textLines } from './diff-rows.ts' -import { FileLabel } from './FileLabel.tsx' import { ChangeRequestGlyph } from './glyphs.tsx' import type { ForgePanelKey, NS } from './locales.ts' import { RefreshGlyph } from './RefreshGlyph.tsx' @@ -40,6 +48,12 @@ type ScopeKind = ForgeLocalScope['kind'] /** Business face of the changes tab body. */ export interface ChangesTabInjected { + /** Append a frozen comment to the main input without submitting it. */ + readonly addReviewToInput: (selection: ReviewSelection) => boolean + /** Records retained across Session switches and cleared when this tab occurrence closes. */ + readonly reviewQueue: (tab: Pick) => ReviewQueue + /** Publish one comment or a completed review; never retries mutations. */ + readonly submitReview: (url: string, request: ForgeReviewRequest) => Promise> /** Panel source while visible; the renderer releases the subscription for an inactive key. */ readonly keyedHooks: { readonly panel: (visibility: string) => HostObservable | undefined } /** Open the panel stream again after it ended. */ @@ -177,9 +191,12 @@ function badgeOf(file: ForgeDiffFile, data: ChangesData, t: Translate): string { return parts.join(' · ') } -function ChangeHeader({ url, entry, openLink, t }: { +function ChangeHeader({ url, entry, openLink, reviewCount, reviewDisabled, onReview, t }: { readonly url: string readonly entry: ForgePanelChangeRequest | undefined + readonly reviewCount: number + readonly reviewDisabled: boolean + readonly onReview: () => void readonly openLink: (url: string) => void readonly t: Translate }): ReactNode { @@ -192,8 +209,11 @@ function ChangeHeader({ url, entry, openLink, t }: { {snapshot === null ? url : snapshot.title} {number !== null && {t('change.number', { number })}} + - @@ -259,40 +279,6 @@ function ScopeMenu({ scope, choose, t }: { ) } -function FilesMenu({ files, jump, t }: { - readonly files: readonly ForgeDiffFile[] - readonly jump: (path: string) => void - readonly t: Translate -}): ReactNode { - const [open, setOpen] = useState(false) - return ( - ({ - id: file.path, - label: , - }))} - onClose={() => { setOpen(false) }} - onSelect={(path) => { - setOpen(false) - jump(path) - }} - anchor={( - - )} - /> - ) -} - function Notice({ children, action }: { readonly children: ReactNode; readonly action?: ReactNode }): ReactNode { return (
@@ -303,6 +289,19 @@ function Notice({ children, action }: { readonly children: ReactNode; readonly a ) } + +function OrphanReviews({ path, actions, t }: PropsLocale & { + readonly path: string + readonly actions: ReviewActions +}): ReactNode { + const state = useFileReview(actions, path) + return
+

{path}

+ {state.threads.map(thread => )} +
+} + /** * Render the changes tab of one Session. * @param props - tab information, the tab's choices, the panel snapshot hook, reads and actions, and copy. @@ -310,15 +309,59 @@ function Notice({ children, action }: { readonly children: ReactNode; readonly a */ export function ChangesTab({ useTabInfo, sessionId, useStore, actions, usePanel, reconnect, localDiff, localText, changeRequestDiff, changeRequestText, - openLink, copyPath, createChangeRequest, report, t, + openLink, copyPath, createChangeRequest, addReviewToInput, reviewQueue, submitReview, report, t, }: ChangesTabProps): ReactNode { const { tab } = useTabInfo() const { navigation, signal } = tab const target = useMemo(() => parseChangesAddress(tab.contentId), [tab.contentId]) if (target === undefined) throw new Error(`forge-panel: not a changes address "${tab.contentId}"`) const source = target.source + const queue = reviewQueue(tab) + useSyncExternalStore(queue.subscribe, queue.getStatus) + const reviewState = queue.getSnapshot() + const [reviewOpen, setReviewOpen] = useState(false) + const [reviewBusy, setReviewBusy] = useState(false) + useEffect(() => { if (!tab.visible) setReviewOpen(false) }, [tab.visible]) + const reviewRunning = useRef(false) + const [reviewError, setReviewError] = useState(null) + const publishReview = async ( + url: string, request: ForgeReviewRequest, complete: (url: string) => boolean, + ): Promise => { + if (reviewRunning.current || !queue.begin(request)) return t('review.saveFailed') + reviewRunning.current = true + setReviewBusy(true) + setReviewError(null) + try { + const response = await submitReview(url, request) + if (!response.ok || (!response.value.ok && response.value.code === 'unknown')) { + setReviewError(t('review.unknown')) + return t('review.unknown') + } + const result = response.value + if (!result.ok) { + queue.finish(false) + const message = result.code === 'stale' ? t('review.stale') : result.code === 'unsupported' + ? t('review.unsupported') : t('review.failed', { message: result.message }) + setReviewError(message) + return message + } + if (!complete(result.url)) return t('review.unknown') + report(request.kind === 'review' ? 'review.submitted' : 'review.published') + if (request.kind === 'review') setReviewOpen(false) + return undefined + } catch (_error) { + setReviewError(t('review.unknown')) + return t('review.unknown') + } finally { + reviewRunning.current = false + setReviewBusy(false) + } + } const choices = useStore(store => store.byTab[tab.id]) const [wanted, setWanted] = useState(null) + const [treeState, setTreeState] = useState({ query: '', collapsed: {}, selected: null }) + const [treeVisible, setTreeVisible] = useState(true) + const treeId = useId() const [chosen, setChosen] = useState>>({}) // Each navigation applies once; its file, if it names one, opens and scrolls into view. useEffect(() => { @@ -326,6 +369,7 @@ export function ChangesTab({ actions.navigated(tab.id, navigation.revision) const path = navigation.params?.path if (path === undefined) return + setTreeState(value => ({ ...value, selected: path })) setChosen(value => ({ ...value, [path]: true })) setWanted(path) }, [choices, navigation.revision, navigation.params, actions, tab.id]) @@ -380,9 +424,13 @@ export function ChangesTab({ const [revealed, setRevealed] = useState>(new Set()) const initial = useMemo(() => initiallyOpen(data === null ? [] : data.files), [data]) 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 sections.current.get(wanted)?.scrollIntoView({ block: 'start' }) + if (scrollport.current !== null) jumpPosition.current = { data, top: scrollport.current.scrollTop } setWanted(null) }, [tab.visible, wanted, data]) const refresh = (): void => { setAttempt(value => value + 1) } @@ -434,6 +482,58 @@ 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={() => { + const latest = queue.getSnapshot() + void publishReview(data.url, { kind: 'review', headSha: data.headSha, event: latest.event, + body: latest.body, comments: latest.comments.map(item => item.comment) }, url => queue.finish(true, url)) + }} t={t} /> + + const recordActions: ReviewActions = { + source: source.kind === 'local' ? { kind: 'local', scope } : { kind: 'change', url: source.url, headSha: data?.kind === 'change' ? data.headSha : '' }, + records: queue, addToInput: addReviewToInput, openLink, + } + const absentPaths = [...new Set([...reviewState.comments, ...reviewState.records.map(item => item.selection)] + .filter(item => sameReviewSource(item.source, recordActions.source)).map(item => item.comment.path))] + .filter(path => !data?.files.some(file => file.path === path)) + const orphanRecords = absentPaths.map(path => ) + + const files = data === null ? [] : data.files + const jump = (path: string): void => { + setTreeState(value => ({ ...value, selected: path })) + setChosen(value => ({ ...value, [path]: true })) + setWanted(path) + } + 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 + })) + } + event.preventDefault() + event.stopPropagation() + const next = files[index + (event.key === 'ArrowRight' ? 1 : -1)] + if (next === undefined) return + viewport.focus({ preventScroll: true }) + jump(next.path) + } + let body: ReactNode if (data === null) { if (state === null && snapshot?.disconnected) { @@ -461,10 +561,14 @@ export function ChangesTab({ ) } } else if (data.files.length === 0) { - body =
{t('diff.empty')}
+ body =
{orphanRecords}
{t('diff.empty')}
} else { body = ( -
+
{ + if (jumpPosition.current?.top !== event.currentTarget.scrollTop) jumpPosition.current = null + }}> {data.files.map((file) => { const path = file.path return ( @@ -472,6 +576,19 @@ export function ChangesTab({ key={path} visible={tab.visible} file={file} + review={{ source: data.kind === 'local' ? { kind: 'local', scope: data.scope } : { kind: 'change', url: data.url, headSha: data.headSha }, + addToInput: addReviewToInput, + records: queue, openLink, reviewStarted: reviewState.comments.length > 0, + onQuoted: (selection) => { if (!queue.recordAgent(selection)) report('review.saveFailed') }, + publishingBlocked: reviewState.uncertain !== null, + ...data.kind === 'local' ? {} : { + queue: selection => queue.add(selection), + publish: selection => selection.source.kind === 'change' + ? publishReview(selection.source.url, { kind: 'comment', headSha: selection.source.headSha, comment: selection.comment }, + url => queue.published(selection, url)) + : Promise.resolve(t('review.stale')), + }, + }} expanded={chosen[path] ?? initial.has(path)} onToggle={() => { setChosen(value => ({ ...value, [path]: !(value[path] ?? initial.has(path)) })) }} large={drawnLines(file) > LARGE_FILE_LINES} @@ -485,7 +602,6 @@ export function ChangesTab({ badge={badgeOf(file, data, t)} tooltip={pathTooltipOf(file, t)} actions={fileActions(data, file)} - onCopyPath={() => { copyPath(path) }} sectionRef={(element) => { if (element === null) sections.current.delete(path) else sections.current.set(path, element) @@ -494,10 +610,16 @@ export function ChangesTab({ /> ) })} + {orphanRecords}
) } - const files = data === null ? [] : data.files + const navigator: ChangedFilesProps = { + files, state: treeState, t, + filter: (query) => { setTreeState(value => ({ ...value, query })) }, + toggle: (path) => { setTreeState(value => ({ ...value, collapsed: { ...value.collapsed, [path]: value.collapsed[path] !== true } })) }, + 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 expansionLabel = t(anyExpanded ? 'diff.collapseAll' : 'diff.expandAll') @@ -511,17 +633,19 @@ export function ChangesTab({
{source.kind === 'local' ? - : } + : { 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')} + {reviewState.uncertain.kind === 'comment' &&
{reviewState.uncertain.comment.body}
} + + +
} + {!reviewOpen && reviewError !== null && reviewState.uncertain === null && {reviewError}}
{tab.visible && source.kind === 'local' && { actions.scoped(tab.id, next) }} t={t} />} - {tab.visible && { - setChosen(value => ({ ...value, [path]: true })) - setWanted(path) - }} - t={t} - />} + {tab.visible && } {files.length > 0 && } @@ -548,6 +672,15 @@ export function ChangesTab({ {wrap ? : } + + + + +
{data !== null && failed !== null && ( @@ -559,7 +692,11 @@ export function ChangesTab({ {t('diff.stale', { count: data.localAhead })} )} {data?.kind === 'local' && data.omitted > 0 && {t('diff.omitted', { count: data.omitted })}} - {body} + {reviewForm} +
+ {body} + {files.length > 0 && } +
) } diff --git a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx index 6a67f99eab..a3c8d9a2ba 100644 --- a/packages/experimental/client-ui-forge/src/client/DiffFile.tsx +++ b/packages/experimental/client-ui-forge/src/client/DiffFile.tsx @@ -4,15 +4,23 @@ * unchanged lines between them collapsed into rows that expand them. */ -import { useMemo, useState, type ReactNode } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react' import clsx from 'clsx' +import { flushSync } from 'react-dom' import { - FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, + FileTypeIcon, IconChevronDownOutlineRegular, IconChevronsUpDownOutlineRegular, IconEllipsisOutlineRegular, IconPlusOutlineRegular, + 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' import type { ForgeDiffFile } from '../types.ts' import { segmentsOf, splitRows, type DiffRow, type SplitCell, type SplitRow } from './diff-rows.ts' +import { codeSideAt, readCodeSelection } from './code-selection.ts' +import { reviewMatches, selectReviewLines, type ReviewSelection } from './review.ts' +import { ReviewThread, useFileReview } from './ReviewThread.tsx' +import type { FileReviewState } from './review-queue.ts' +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 css from './ChangesTab.module.css' @@ -34,6 +42,8 @@ export type DiffFileText = readonly string[] | 'loading' | undefined export interface DiffFileProps { /** Whether the owning tab is visible and may show temporary menus. */ readonly visible: boolean + /** Comment destinations and the source being reviewed. */ + readonly review?: ReviewActions /** The file and its hunks. */ readonly file: ForgeDiffFile /** Whether the section shows its lines. */ @@ -62,8 +72,6 @@ export interface DiffFileProps { readonly tooltip: string /** Rows of the file's menu. */ readonly actions: readonly DiffFileAction[] - /** Copy the repository-relative path from the file header. */ - readonly onCopyPath: () => void /** Receives the section element, which scrolling to the file targets. */ readonly sectionRef: (element: HTMLElement | null) => void /** Forge panel copy. */ @@ -112,91 +120,238 @@ function sideSpans(rows: readonly DiffRow[], side: 'old' | 'new', highlighter: C return new Map(numbered.map((line, index) => [line.no, highlighted[index] ?? []])) } -function Code({ text, spans }: { readonly text: string; readonly spans: readonly HighlightSpan[] | undefined }): ReactNode { +function Code({ text, spans, old, next }: { + readonly text: string + readonly spans: readonly HighlightSpan[] | undefined + readonly old: number | null + readonly next: number | null +}): ReactNode { return ( - + {spans === undefined ? text : spans.map((span, index) => {span.text})} ) } -function Cell({ cell, spans }: { readonly cell: SplitCell | null; readonly spans: SideSpans }): ReactNode { - if (cell === null) return - return ( - - {cell.no} - - - ) -} - /** Whether a side-by-side row repeats an unchanged line or shows a change. */ function pairKind(pair: SplitRow): 'context' | 'change' { return pair.left !== null && pair.left.kind === 'context' ? 'context' : 'change' } /** The hunks of one file with their collapsed and expanded unchanged lines. */ -function Lines({ file, text, open, onExpand, split, wrap, t }: Pick): ReactNode { +function Lines({ file, text, open, onExpand, split, wrap, review, visible, comments, t }: Pick & { readonly comments: FileReviewState }): ReactNode { const lines = typeof text === 'object' ? text : undefined const columns = split && file.additions > 0 && file.deletions > 0 + const singleSide = file.status === 'added' ? 'R' : file.status === 'deleted' ? 'L' : null + let maximum = Math.max(1, lines?.length ?? 0, (lines?.length ?? 0) + file.deletions - file.additions) + for (const hunk of file.hunks) maximum = Math.max(maximum, hunk.oldStart + hunk.oldLines - 1, hunk.newStart + hunk.newLines - 1) + const style: CSSProperties & { '--forge-number-width': string } = { '--forge-number-width': `calc(${Math.max(2, String(maximum).length)}ch + 12px)` } const highlighter = useCodeHighlighter(languageForPath(file.path)) + const [selection, setSelection] = useState(null) + const root = useRef(null) + const origin = useRef<{ side: 'L' | 'R'; line: number } | null>(null) + const dragging = useRef<'gutter' | 'text' | null>(null) + const [selecting, setSelecting] = useState(false) + const [editing, setEditing] = useState(false) + const [nativeSide, setNativeSide] = useState<'L' | 'R' | null>(null) + const nativeSelection = useCallback((): void => { + if (editing || nativeSide === null || root.current === null || review === undefined) return + const selected = readCodeSelection(root.current, nativeSide) + if (selected === undefined) { + setSelection(null) + setNativeSide(null) + return + } + const comment = selectReviewLines(file, selected.side, selected.from, selected.to) + setSelection(previous => comment === undefined ? null + : previous?.comment.side === comment.side && previous.comment.startLine === comment.startLine + && previous.comment.endLine === comment.endLine + ? previous : { source: review.source, comment }) + }, [editing, nativeSide, review, file]) + useEffect(() => { + if (nativeSide === null || editing) return + const changed = (): void => { if (dragging.current === null) nativeSelection() } + document.addEventListener('selectionchange', changed) + return () => { document.removeEventListener('selectionchange', changed) } + }, [nativeSide, editing, nativeSelection]) + useEffect(() => { + if (nativeSide === null) return + const copy = (event: ClipboardEvent): void => { + if (root.current === null || event.clipboardData === null + || (event.target instanceof Element && event.target.closest('input, textarea, [contenteditable="true"]') !== null)) return + const selected = readCodeSelection(root.current, nativeSide) + if (selected === undefined) return + event.preventDefault() + event.clipboardData.setData('text/plain', selected.text) + } + document.addEventListener('copy', copy) + return () => { document.removeEventListener('copy', copy) } + }, [nativeSide]) + useEffect(() => { + if (!selecting) return + const finish = (): void => { + if (dragging.current === 'text') nativeSelection() + dragging.current = null + setSelecting(false) + } + window.addEventListener('pointerup', finish) + window.addEventListener('pointercancel', finish) + return () => { + window.removeEventListener('pointerup', finish) + window.removeEventListener('pointercancel', finish) + } + }, [selecting, nativeSelection]) const prepared = useMemo(() => segmentsOf(file, lines, open).map((segment): Prepared => segment.kind === 'gap' ? segment : { ...segment, old: sideSpans(segment.rows, 'old', highlighter), new: sideSpans(segment.rows, 'new', highlighter) }), [file, lines, open, highlighter]) - return ( -
- {prepared.map((segment, at) => { - if (segment.kind === 'gap') { - return ( - - ) + const choose = (side: 'L' | 'R', line: number, extend: boolean): void => { + if (review === undefined || editing) return + const from = extend && origin.current?.side === side ? origin.current.line : line + const comment = selectReviewLines(file, side, from, line) + if (comment === undefined) return + if (!extend || origin.current?.side !== side) origin.current = { side, line } + setSelection({ source: review.source, comment }) + } + const selected = (side: 'L' | 'R', line: number | null): boolean => line !== null && selection !== null + && selection.comment.side === side && line >= selection.comment.startLine && line <= selection.comment.endLine + const number = (side: 'L' | 'R', line: number | null): ReactNode => { + if (line === null || review === undefined || !file.hunks.some((hunk) => { + const start = side === 'L' ? hunk.oldStart : hunk.newStart + return line >= start && line < start + (side === 'L' ? hunk.oldLines : hunk.newLines) + })) { + return {line ?? ''} + } + return + + {!selecting && !editing && selection?.comment.side === side && selection.comment.endLine === line && ( + + + + )} + + } + const cell = (value: SplitCell | null, spans: SideSpans, side: 'L' | 'R'): ReactNode => value === null + ? + : + {number(side, value.no)} + + const rows: ReactNode[] = [] + let inserted = false + const editor = review === undefined || selection === null || !editing ? null : { + const native = window.getSelection() + if (root.current?.contains(native?.anchorNode ?? null) === true) native?.removeAllRanges() + setSelection(null) + setEditing(false) + setNativeSide(null) + origin.current = null + }} t={t} /> + const remaining = new Set(comments.threads) + const appendComments = (old: number | null, next: number | null): void => { + if (review === undefined) return + for (const thread of remaining) { + const comment = thread.selection.comment + if ((comment.side === 'L' ? old : next) !== comment.endLine || !reviewMatches(thread.selection, review.source, file)) continue + rows.push() + remaining.delete(thread) + } + } + const endsAt = (old: number | null, next: number | null): boolean => selection !== null + && (selection.comment.side === 'L' ? old : next) === selection.comment.endLine + for (const [at, segment] of prepared.entries()) { + if (segment.kind === 'gap') { + rows.push() + } else if (columns) { + for (const [index, pair] of splitRows(segment.rows).entries()) { + rows.push(
+ {cell(pair.left, segment.old, 'L')}{cell(pair.right, segment.new, 'R')} +
) + if (!inserted && endsAt(pair.left?.no ?? null, pair.right?.no ?? null)) { + rows.push(editor) + inserted = true } - if (columns) { - return splitRows(segment.rows).map((pair, index) => ( -
- - -
- )) + appendComments(pair.left?.no ?? null, pair.right?.no ?? null) + } + } else { + for (const [index, row] of segment.rows.entries()) { + rows.push(
+ {singleSide !== 'R' && number('L', row.old)}{singleSide !== 'L' && number('R', row.new)}{SIGN[row.kind]} + +
) + if (!inserted && endsAt(row.old, row.new)) { + rows.push(editor) + inserted = true } - return segment.rows.map((row, index) => ( -
- {row.old ?? ''} - {row.new ?? ''} - {SIGN[row.kind]} - -
- )) - })} -
- ) + appendComments(row.old, row.new) + } + } + } + if (review !== undefined) for (const thread of remaining) { + rows.push() + } + if (!inserted) rows.push(editor) + return
{ + if (event.button !== 0 || !(event.target instanceof Node)) return + const side = codeSideAt(event.currentTarget, event.target) + if (side === undefined) return + if (!event.shiftKey || nativeSide !== side) window.getSelection()?.removeAllRanges() + if (!editing) dragging.current = 'text' + // The chosen column must allow selection before the browser starts its native text range. + flushSync(() => { + setNativeSide(side) + if (editing) return + setSelection(null) + setSelecting(true) + }) + }}>{rows}
} function Body(props: DiffFileProps): ReactNode { - const { file, large, revealed, onReveal, t } = props - if (file.binary) return

{t('diff.binary')}

- if (file.oversized) return

{t('diff.fileTooLarge')}

- if (file.hunks.length === 0) return null + const { file, large, revealed, onReveal, review, t } = props + const comments = useFileReview(review, file.path) + const records = review === undefined ? null : comments.threads.map(thread => ) + if (file.binary) return <>

{t('diff.binary')}

{records} + if (file.oversized) return <>

{t('diff.fileTooLarge')}

{records} + if (file.hunks.length === 0) return records if (large && !revealed) { // A large file starts as one collapsed strip, drawn and opened like the collapsed unchanged lines. return ( - + {records} ) } - return + return } /** File actions live only while their owning tab is visible. */ @@ -248,7 +403,7 @@ function FileMenu({ name, actions, t }: { * @returns the file section. */ export function DiffFile(props: DiffFileProps): ReactNode { - const { file, expanded, onToggle, badge, tooltip, actions, onCopyPath, sectionRef, t } = props + const { file, expanded, onToggle, badge, tooltip, actions, sectionRef, t } = props const name = file.path.slice(file.path.lastIndexOf('/') + 1) return (
@@ -263,9 +418,9 @@ export function DiffFile(props: DiffFileProps): ReactNode { - + {badge !== '' && {badge}} {!file.binary && } diff --git a/packages/experimental/client-ui-forge/src/client/FileLabel.module.css b/packages/experimental/client-ui-forge/src/client/FileLabel.module.css index dcee927f92..add13b56ed 100644 --- a/packages/experimental/client-ui-forge/src/client/FileLabel.module.css +++ b/packages/experimental/client-ui-forge/src/client/FileLabel.module.css @@ -1,5 +1,7 @@ /* A changed file's name, then its directory in smaller subdued type. */ .label { + /* Keep the hidden accessible path inside the file's own scroll container. */ + position: relative; display: flex; min-width: 0; } diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.module.css b/packages/experimental/client-ui-forge/src/client/FileTreePane.module.css new file mode 100644 index 0000000000..341d889a1f --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.module.css @@ -0,0 +1,8 @@ +/* Container width keeps navigation separate from the compact files menu. */ +.pane { display: none; position: relative; flex: none; min-width: 0; min-height: 0; box-sizing: border-box; border-inline-start: 0.5px solid var(--dsw-alias-border-l3); } +.pane[hidden] { display: none; } +.navigation { height: 100%; min-width: 0; overflow-y: auto; } +.resize { position: absolute; inset-block: 0; inset-inline-start: -4px; width: 8px; z-index: 2; cursor: col-resize; touch-action: none; user-select: none; } +.resize::after { content: ''; position: absolute; inset-block: 0; inset-inline-start: 3px; width: 2px; } +.resize:focus-visible::after { background: var(--dsw-alias-state-business-primary); } +@media (hover: hover) { .resize:hover::after { background: var(--dsw-alias-state-business-primary); } } diff --git a/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx new file mode 100644 index 0000000000..9de6f00338 --- /dev/null +++ b/packages/experimental/client-ui-forge/src/client/FileTreePane.tsx @@ -0,0 +1,69 @@ +/** Resizable file navigation; width belongs to the mounted tab and survives hiding the pane. */ + +import clsx from 'clsx' +import changesCss from './ChangesTab.module.css' +import { useLayoutEffect, useRef, useState, type ReactNode } from 'react' +import { ChangedFiles, type ChangedFilesProps } from './ChangedFiles.tsx' +import css from './FileTreePane.module.css' + +const MIN_WIDTH = 200 +const MAX_WIDTH = 600 +const DIFF_MIN_WIDTH = 320 + +/** + * Render a keyboard- and pointer-resizable tree beside the diff. + * @param props - tree rows, pane visibility, and the toggle's controlled element id. + * @returns the bounded pane and its resize separator. + */ +export function FileTreePane({ open, id, ...props }: ChangedFilesProps & { readonly open: boolean; readonly id: string }): ReactNode { + const pane = useRef(null) + const drag = useRef<{ pointer: number; x: number; width: number } | null>(null) + const [width, setWidth] = useState(240) + const [maximum, setMaximum] = useState(MAX_WIDTH) + useLayoutEffect(() => { + const parent = pane.current?.parentElement + if (parent === undefined || parent === null) return + const measure = (): void => { + const available = parent.clientWidth + // A retained tab has no measurable width while its session or pane is hidden. + if (available === 0) return + setMaximum(Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, available - DIFF_MIN_WIDTH))) + } + measure() + const observer = new ResizeObserver(measure) + observer.observe(parent) + return () => { observer.disconnect() } + }, []) + const shown = Math.min(width, maximum) + const resize = (next: number): void => { setWidth(Math.round(Math.max(MIN_WIDTH, Math.min(maximum, next)))) } + return