Merge remote-tracking branch 'origin/master' into xtr/ptc-timeout-step-1

This commit is contained in:
_Kerman committed 2026-10-29 21:22:30 +08:00
commit aaa7f45d4f
586 files changed
+36682 -20935

No files matched your search

@@ -3,17 +3,17 @@
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-16-host-schedule-storage.md
/agent-note-host-owned-scheduled-messages:
en: 11854b220af809ea
zh: 0f0575de37107ed8
en: b3b0dde47f58ca48
zh: d4ba3a6cf1228578
/agent-note-host-owned-scheduled-messages/problem:
en: 2c774d05ae75784f
zh: 619ba7f281b13233
/agent-note-host-owned-scheduled-messages/decision:
en: 1210b3975fd26bb3
zh: 3322e6d0aa63fdb0
en: 20dcfc8e9c44cde7
zh: d9609e41eb4e9bd9
/agent-note-host-owned-scheduled-messages/alternatives-considered:
en: 21d7ec9a9ff3cbf2
zh: 93d03b8b3012aa7e
/agent-note-host-owned-scheduled-messages/consequences:
en: 3ae0cd93ed95431e
zh: 25a0a2bc25863651
en: ce4ef02663cd485c
zh: ad8ae567c3bab8e0
@@ -4,36 +4,20 @@ Status: implemented
English | [中文](2026-09-16-host-schedule-storage.zh.md)
This note remains current for Host authority, whole-unit durability, and saved inbox receipts. [Typed rule storage](2026-10-21-schedule-rule-storage.md) and [Session targets](2026-09-17-standalone-schedules.md) replace its original management and target contracts.
## Problem
Scheduled messages must remain discoverable after restart without loading every Session. A timer attached to a live Agent cannot dispatch a task whose Session remains cold. Users also need to inspect pending and delivered tasks without activating their conversation; removing a task after delivery loses that management record.
## Decision
The existing Schedule package owns one Host storage domain containing each task's original Session id, reminder record, `active` or `inactive` status, latest delivery receipt, and saved delivery history. The domain is authoritative for retained tasks. The Host scheduler restores timers only for active tasks; a due task uses the Session controller's existing resolution operation and queues an ordinary follow-up in the original Session. Querying and deleting tasks do not resolve an Agent. Stored records lacking status normalize to `active` without scanning or recreating historical Sessions.
The original `schedule` domain and whole-unit layout remain authoritative; v2 accepts v1. [Typed rule storage](2026-10-21-schedule-rule-storage.md) supersedes the original Session-owned management API, top-level binding writes, and two-state lifecycle; [Session targets](2026-09-17-standalone-schedules.md) owns Host-wide management and delivery targets. The seven normal timing kinds preserve committed targets. An explicit target wins; absent targets read the old Session binding or reserve a stable new-once identity. No startup migration runs.
The task domain declares the whole-unit layout. Tasks are authoritative, so the JSON backend rejects an unreadable file, malformed document, unsupported version, or invalid task as a complete load failure instead of interpreting it as deletion. Failed recovery leaves `schedule.json` unchanged, while an initially absent file opens as an empty domain; repairing the file preserves task identity. `Service.init` waits for both storage validation and runtime setup, management methods wait for the same initialization result, and an unloading owner releases late-acquired storage without starting dispatch. Dispatch admission is separate from initialization: an ancestor can close Agent admission after a task mutation commits but before runtime cleanup starts. That refusal is logged without automatic retry and does not turn the persisted mutation into a failed management result. Invalid storage and failed cleanup registration still reject startup.
This replaces the earlier Session-log authority, live-only activation, and read-only catalog decisions. The [Schedule reference](../../../../packages/schedule/schedule/README.md) owns explicit absolute-time validation, fixed-rate arithmetic, and the distinction between queue admission and model completion. Historical `schedule/change` creation and fold types remain restricted to After, At, and Every through `LegacyScheduleRecord`; a separate Host decoder accepts the current `ScheduleRecord`, including Daily, Weekly, and Cron. The Host record decoder requires a stored `title` that is non-empty after trimming, already trimmed, and at most 120 characters, and the strict task schema rejects the whole domain open instead of dropping such a task. The historical change decoder tolerates an absent `title` so an already-written Session log stays readable, and it applies the same three checks when the member is present. The storage domain remains version 1. Historical events do not populate that domain, and existing `at` tasks are not converted into daily or weekly rules. Loading a Session with active legacy reminders warns that they must be recreated.
A plugin-sourced `followup()` synchronously appends the message to the Session inbox. Successful Session flush acknowledges durable delivery. One task-record put stores `lastDelivery`, appends a delivery record with the occurrence target, acknowledgment time, actual message id, and instruction snapshot, and updates the one-shot's `inactive` status or the recurring task's next target and status. Task state and its saved history therefore share one commit. Inactive tasks remain stored and never schedule another delivery; explicit deletion stops future delivery and removes the row together with its saved records. These records acknowledge inbox delivery, not user receipt or model execution completion.
New tasks initialize an empty `deliveryHistory`. A task without that optional field exposes its existing latest receipt, if any, and marks earlier records unavailable. Reading never rewrites the old task or invents the lost history or instruction snapshot. Its next acknowledged delivery preserves that available receipt and appends the new one. Strict decoding rejects duplicate message ids and disagreement between the latest receipt and the last history entry. History follows append order, not wall-clock sorting, so clock rollback does not reverse acknowledged deliveries.
A recurring task contributes its latest due occurrence once, including after Host restart. Every remains creation-aligned until an interval edit establishes a new anchor; Daily retains a local time and explicit IANA zone, and Weekly adds a non-empty ISO weekday set stored as unique ascending numbers. Every, Daily, Weekly, and Cron use `renderRecurringReminderBatchFraming` and share one follow-up message and its real message id when due for the same Session. The fixed text both renderers emit is the [delivered-reminder origin line](2026-09-24-scheduled-message-framing.md) decision. A recurring task with no representable next target remains inactive with its last receipt. A stopped Host does not send messages.
Daily is a fourth mutually exclusive creation selector, Weekly a fifth, and Cron a sixth, none a conversion of `every_seconds` or `at`. Weekly selects every local date whose ISO weekday belongs to its stored set; the decoder rejects an unnormalized stored set, and the selector rejects an empty, repeated, out-of-range, or non-integer one. Their first targets are strictly future. Missing local times and dates are skipped; overlaps select the earlier instant once per date. The next target is after the delivery decision and on a local date later than the selected occurrence's date. Only UTC targets are restricted to years 0001–9999; local dates may cross into year 0 or 10000 at the edges. After Session restoration, the runtime rechecks due members against the current clock so a rollback does not admit future tasks.
The maintained `@js-temporal/polyfill` 0.5.1 resolves local dates and overlap/gap behavior using the Host's IANA data; Schedule does not own offset-sampling logic or add another package layer. Each daily or weekly record stores normalized `HH:mm:ss.SSS` time, its zone, its weekday set where applicable, and a committed next UTC instant. Decoding and restart do not recompute that instant. Valid zone aliases remain readable across canonical-name changes, while subsequent targets use current Host time-zone data.
Model `schedule_list`, Remote `list`, and the Session header's right-aligned reminder clock show only active tasks. The independent Automation tasks page opens from the sidebar and reads active and inactive Host tasks through the read-only Remote `catalog` method, without activating Sessions or reading their history. That clock is absent while the Session has no active reminder, opens a single task's detail directly when exactly one remains, and otherwise lists them so one can be chosen; both paths open one right-Sidebar task tab that renders the same detail component the Automation tasks page uses, so neither path selects the main panel. The tab names its task and original Session through its navigation parameters and carries that binding into every mutation, so opening or deleting from it never activates a Session. The page has one All, Enabled, and Inactive status filter row, retained inactive details, latest delivery metadata, and an original-Session control that sits in the detail tab strip beside the task actions. Its header's New action starts a new Session, where the reminder is created by asking the model; the page offers no creation form. Navigation waits for Session and archive metadata, explains unavailable targets, and never restores an archived Session implicitly. Task retention remains independent of original-Session availability. Every, Daily, Weekly, and Cron are recurring rules; the page groups tasks only by status. Daily and Weekly rule labels retain the saved local time, exact rule zone, and stored weekday set rather than substituting the browser zone used for next-target display. Explicit confirmed deletion reuses `delete` with the entry's original Session binding, requiring that the supplied binding match the stored task. This argument check is not independent caller authorization: model tools capture the current Agent's Session, while the global user interface selects the task's original binding. Cross-Session model modification policy remains a product decision, not a consequence of the storage layout. A payload-free change notification invalidates queries, and reconnect queries recover missed notifications. Deletion prevents subsequent dispatch but does not retract a queued message.
The second detail level separates Rules from Delivery records. Opening records requests `history` with the task's original Session binding and an explicit page limit of 1–100. An exclusive message-id cursor reads older receipts without changing position when new deliveries append. Catalogs retain only latest-receipt metadata rather than duplicating full histories in every task-list response. Missing tasks and unknown cursors are distinct failures, not empty successful history. The records view loads lazily, rejects stale responses, and keeps original-Session navigation separate from inspection.
Name, instruction, and timing updates share the dispatch and deletion FIFO. Comparing the complete observed record inside that queue prevents a stale draft from overwriting a saved rule or a target advanced by delivery. This avoids adding a persisted revision counter, at the cost of rejecting drafts after normal delivery changes the target. One task put replaces the rule, name, or instruction, preserving identity, original Session binding, status, latest receipt, and saved history. A request may omit the timing change, the name, or the instruction; an omitted field keeps its stored value, and a name or instruction change alone leaves the committed target untouched. Normalized no-ops leave the committed target and stored bytes unchanged. Changed one-shots retain their identity as At records; changed fixed intervals use a new accepted-save anchor; changed wall-clock rules re-resolve their first future target from the same accepted-save sample, and an equivalent normalized rule stays a no-op. A timing change may select a different recurrence kind, and the new rule computes its target exactly as creation would from that accepted-save sample. Deletion removes the row together with its saved records ([consequences of that reversal](2026-09-22-schedule-hard-delete-and-bounded-history.md)), so the runtime never schedules the task again and `history` no longer resolves for its original binding. Inactive tasks are not reopened.
The page uses the existing Host task domain and scheduler, not a mock engine or a Session projection. The name, the instruction, and the run-time rows edit one local draft for the shown task, and one Save commits that draft as a single update carrying the complete expected record; Cancel restores the stored values, a failed save retains the draft, an unsaved draft survives an authoritative refresh, and a committed save and a failed catalog refresh remain separate outcomes. Pause and execution-history operations remain unsupported. Lifecycle status and latest delivery acknowledgment do not describe model results.
The client presentation derives from existing persisted data instead of widening a persisted format. The `schedule_create` transcript card reads the created task out of the call's model-visible result JSON, which already serializes the canonical task value, rather than declaring `presentationMeta`: a persisted metadata channel would add a durable field for a card that Session-log replay reconstructs from the result alone, and previously recorded Sessions render the card without a format change. The Sidebar Session-row clock mark occupies the root-scoped `sidebar.session.row.leading` seat rather than requesting a per-Session provider, because a Session-scoped seat would bind every listed Session and thereby activate and retain it; the same root-scoped owner share feeds `sidebar.session.row.hover`, and both read the shared Host catalog snapshot `schedule/catalog()` without reading a Session log.
Session inbox persistence and the task put occur in separate persistence systems. Inbox persistence precedes the task put to avoid marking delivery before its message exists. A crash or task-write failure after inbox persistence can repeat a message; storing status, target, and receipt together does not make the two stores atomic. Dispatch failures retain the task and produce a diagnostic; there is no independent retry timer. This feature does not create or replace a Goal.
@@ -56,10 +40,4 @@ Session inbox persistence and the task put occur in separate persistence systems
## Consequences
**Keep the mock's hourly choice out of the stored vocabulary.** The approved mock lists 每小时整点 beside the daily, weekly and one-shot choices. Hourly and fixed-rate intervals are the same elapsed-time rule, so the card maps that menu slot onto the existing interval kind instead of adding a persisted kind. A dedicated hourly kind would need a new durable variant, its decoder, its target resolution, and its tool schema, all to express what an interval already expresses.
Task discovery and timers do not depend on loaded Sessions. The after, absolute-time, and fixed-rate selectors retain their semantics alongside Daily, Weekly, and Cron; reading existing saved tasks does not rewrite them. The Host must have its ordinary Session persistence and recovery services available, and the shipped Web composition mounts the Schedule service for the whole deployment. Explicit deletion stops future delivery and removes the task from `list` and `catalog` without deleting conversation messages; the removed row takes its saved receipts with it. History is pruned to the configured window and record cap when an acknowledgment is appended, loaded into Host memory, and rewritten with the task on each acknowledgment. Pagination limits the returned record count; the plugin configuration (`deliveryHistoryDays`, default 30, and `deliveryHistoryRecords`, default 200) limits storage growth. Earlier overwritten receipts and deliveries whose task write failed cannot be reconstructed. Pause and execution-history operations remain unsupported.
Required coverage includes startup from stored tasks, missing-status normalization, cold Session restoration, latest-only catch-up, inactive-task retention without repeat dispatch, real message receipts, deletion across restart, removal of a deleted task's saved deliveries, queue/persistence failures, and disposal. Wall-clock obligations include gaps and skipped dates, earlier-only overlaps, fractional seconds, UTC-range edges, committed-target and alias preservation, and post-restoration clock rollback. Weekly adds weekday normalization and validation, next-target selection across a gap and an overlap, and stored set preservation. Historical decoders must reject Daily, Weekly, and Cron while Host storage accepts them. Client coverage includes every recurring kind, exact rule time, zone, and weekday set, All/Enabled/Inactive status filters, retained inactive details and original-Session navigation, authoritative refresh after confirmed deletion and notification, empty lists, reconnect, and late responses. Presentation coverage includes the page's New action starting a Session, the transcript card's narrowing of persisted result JSON including an incomplete or replayed result, the header clock's direct open for exactly one task and its count label, the idle-only row mark with the hover-card two-task limit and omission line. History coverage includes legacy byte preservation, append and restart, immutable sent instructions, strict latest-receipt consistency, stable cursor pagination, binding checks, failed persistence, and late page replies during refresh or task changes. Cross-store crash duplication remains an explicit limitation rather than a completion claim.
Name, instruction, and timing coverage includes all supported rule kinds, complete-record conflicts, delivery/save ordering, cancellation, normalized no-ops, unchanged-history persistence, pending controls, draft retention, and collision-free task identity. The [built CLI process test](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) drives public Remote requests and reloads actual task-file bytes in a fresh Host. Its task and receipt seeds establish retained-data inputs, not real creation, delivery, or recorded-model evidence; those require ordinary Session operations and captured model requests.
Task discovery and timers do not require loaded Sessions. History remains in the same task row and shares its acknowledgment commit; reads never invent missing prompts, timestamps, or earlier deliveries. Historical Session-log After, At, and Every remain frozen and do not populate this domain. The [Schedule reference](../../../../docs/subsystems/schedule.md) owns timing, management, UI projection, and retention contracts. The [built CLI test](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) checks raw old rows, edit-time normalization, conflicts, and cold restart through public Remote requests; seeded receipts are retained-data evidence rather than delivery evidence.
@@ -4,36 +4,20 @@ Status: implemented
[English](2026-09-16-host-schedule-storage.md) | 中文
本 note 仍拥有宿主权威来源、整单元持久性和已保存收件箱回执。[带类型规则存储](2026-10-21-schedule-rule-storage.zh.md)和 [Session 目标](2026-09-17-standalone-schedules.zh.md)替代原管理与目标契约。
## Problem
定时消息必须能在重启后被发现,无须加载每个 Session。挂在 live Agent 上的 timer 无法投递目标 Session 仍为 cold 的任务。用户还需要在不激活对话的情况下查看待投递和已投递任务;投递后删除任务会丢失这条管理记录。
## Decision
现有 Schedule 包拥有一个 Host storage domain,保存每个任务的原始 Session id、提醒记录、`active` 或 `inactive` 状态,最近一次投递回执,以及已保存的投递历史。该 domain 是保留任务的权威来源。Host scheduler 仅为活动任务恢复 timer;到期任务使用 Session controller 现有的解析操作,在原 Session 中排入普通 follow-up。查询和删除任务不会解析 Agent。已存储但缺少状态的记录规范化为 `active`,不扫描或重建历史 Session。
原有 `schedule` 领域和整单元布局仍是权威来源;v2 接受 v1。[带类型规则存储](2026-10-21-schedule-rule-storage.zh.md)替代原按 Session 所有的管理 API、顶层绑定写入和两状态生命周期;[Session 目标](2026-09-17-standalone-schedules.zh.md)拥有宿主管理范围与执行目标。七种正常时间类型保留已提交发生时点。显式目标优先;缺少目标时读取旧 Session 绑定或预留稳定的首次新建后复用身份。不运行启动迁移。
任务 domain 声明整 unit 布局。任务是权威数据,因此 JSON 后端会把文件不可读、文档损坏、版本不受支持或任务非法作为整批加载失败,而不是解释为删除。恢复失败不会改写 `schedule.json`,初始不存在的文件则作为空 domain 打开;修复该文件后会保留任务身份。`Service.init` 等待存储校验和运行时初始化,管理方法等待同一初始化结果;拥有方卸载时释放迟到的存储资源,而不开始投递。投递调度准入与初始化分开:任务变更提交后、运行时清理开始前,祖先可能关闭 Agent 准入。此类拒绝会记录日志而不自动重试,不会将已持久化的变更变成失败的管理结果。存储非法和清理注册失败仍拒绝启动。
本决策替代先前的 Session 日志权威来源、仅 live 时激活和只读目录决策。[Schedule 参考](../../../../packages/schedule/schedule/README.zh.md)负责显式绝对时间校验、固定速率计算,以及区分排队接纳与模型完成。历史 `schedule/change` 的创建与 fold 类型通过 `LegacyScheduleRecord` 保持为 After、At 和 Every;独立的宿主解码器接受包含 Daily、Weekly 与 Cron 的当前 `ScheduleRecord`。宿主记录解码器要求已存储的 `title` 去除首尾空白后非空、本身已去除首尾空白且不超过 120 个字符,严格的 task schema 会拒绝整个 domain 的打开,而不是丢弃这样的任务。历史变更解码器容忍缺失的 `title`,以便已写入的 Session 日志仍可读取;该成员存在时,同样按这三项检查校验。storage domain 保持版本 1。历史事件不会填充该 domain,已有 `at` 任务也不会转换为每日或每周规则。加载含有活动旧提醒的 Session 时,会警告需要重新创建提醒。
插件来源的 `followup()` 同步将消息追加到 Session 收件箱。Session flush 成功后确认持久投递。一次任务记录 put 存储 `lastDelivery`,追加包含发生目标、确认时间、真实消息 id 和指令快照的发送记录,并更新一次性任务的 `inactive` 状态或重复任务的下一目标和状态。因此,任务状态与其保存的历史共用一次提交。未运行任务仍保留在存储中,且不会再次安排投递;显式删除会阻止后续投递,并把该行连同其已保存记录一并移除。这些记录确认收件箱投递,不表示用户收到消息或模型执行完成。
新任务初始化空的 `deliveryHistory`。缺少该可选字段的任务会展示已有的最近一次回执(如果存在),并标明更早记录不可用。读取不会重写旧任务,也不会虚构已丢失的历史或指令快照。下一次确认投递时,保留已有回执并追加新记录。严格解码拒绝重复消息 id,以及最近一次回执与历史末项不一致的情况。历史按追加顺序排列,不按墙钟排序,因此时钟回拨不会颠倒已确认投递的顺序。
重复任务只投递一次最新到期发生时点,Host 重启后也一样。Every 保持与创建时间对齐,直到修改间隔后建立新的起算时点;Daily 保留本地时间与显式 IANA 时区,Weekly 另存非空 ISO 星期集合(唯一且升序)。Every、Daily、Weekly 与 Cron 均使用 `renderRecurringReminderBatchFraming`,同一 Session 的到期任务共用一条 follow-up 消息及其真实消息 id。两个渲染器输出的固定文本见[投递提醒的来源行](2026-09-24-scheduled-message-framing.zh.md)决策。没有可表示的下一目标时,重复任务保留未运行状态及最近一次回执。停止的 Host 不会发送消息。
Daily 是互斥的第四个创建选择器,Weekly 是第五个,Cron 是第六个,三者都不是对 `every_seconds` 或 `at` 的转换。Weekly 选择本地日期 ISO 星期属于其所存集合的每个日期;解码器拒绝未规范化的已存集合,选择器拒绝空、重复、超出范围或非整数的集合。它们的首个目标严格晚于当前时间。缺失的本地时间或日期被跳过;重叠时间选择较早时点,每个日期一次。下一目标晚于投递判断时刻,且其本地日期晚于所选发生时点的日期。仅 UTC 目标限制在 0001–9999 年;边缘处的本地日期可以进入第 0 年或第 10000 年。Session 恢复后,运行时依据当前时钟重新核对到期成员,避免时钟回拨时接纳未来任务。
受维护的 `@js-temporal/polyfill` 0.5.1 使用宿主 IANA 数据解析本地日期及重叠或缺口;Schedule 不拥有偏移量采样逻辑,也不增加包层级。每日或每周记录保存规范化后的 `HH:mm:ss.SSS` 时间、时区、适用的星期集合及已提交的下一 UTC 时点。解码和重启不会重新计算该时点。规范名称变化后,有效时区别名仍可读取;后续目标使用宿主当前的时区数据。
模型 `schedule_list`、Remote `list` 和 Session 顶部右侧的提醒时钟仅显示活动任务。独立的自动化任务页面从侧边栏打开,通过只读 Remote `catalog` 方法读取活动和未运行 Host 任务,不激活 Session 或读取其历史。该时钟在该 Session 没有活动提醒时不显示;恰好有一个时直接打开该任务详情,否则列出提醒供选择。两条路径都打开同一个右侧边栏任务页签,该页签渲染自动化任务页面所用的同一详情组件,因此都不会切换主面板。页签通过导航参数指明任务及其原 Session,并把该绑定带入每个修改操作,因此从页签打开或删除都不会激活 Session。页面提供一行“全部/已开启/未运行”状态筛选,保留未运行任务详情、最近一次投递元数据和固定在位于详情页签条内、与任务操作并排的原 Session 入口。页头的“新建”操作会打开一个新会话,提醒由模型在该会话中创建;页面不提供创建表单。导航等待 Session 与归档元数据,解释不可用目标,且不会隐式恢复已归档 Session。任务保留与原 Session 可用性相互独立。Every、Daily、Weekly 和 Cron 均为重复规则;页面只按状态分组。Daily 与 Weekly 规则标签保留保存的本地时间、精确规则时区和所存星期集合,不替换为下一目标显示所用的浏览器时区。显式确认删除复用 `delete`,传入条目的原始 Session 绑定,要求传入绑定与已存任务一致。这项参数校验不是独立的调用者鉴权:模型工具捕获当前 Agent 的 Session,全局用户界面则选择任务的原始绑定。跨会话模型修改政策仍是产品决策,不由存储布局直接决定。无载荷的变更通知使查询失效,重新连接时重新查询以恢复漏掉的通知。删除阻止后续投递,但不撤回已排队消息。
第二层详情将“规则”与“发送记录”分开。打开发送记录时,`history` 请求携带任务的原始 Session 绑定,以及 1–100 的显式分页数量。排他的消息 id 游标用于读取更早回执,新投递追加后不会改变其定位。目录仅保留最近一次回执元数据,不在每次任务列表响应中复制完整历史。任务不存在和游标未知属于独立失败,不是查询成功的空历史。记录视图按需加载,拒绝晚到的过期响应,并将原 Session 导航与查看记录分开。
名称、指令和时间更新与投递、删除共用 FIFO。在该队列内比较完整的已观察记录,可防止旧草稿覆盖已保存规则或投递已推进的目标。这样无须增加持久版本计数器,代价是正常投递改变目标后也会拒绝旧草稿。一次任务 put 替换规则、名称或指令,保留身份、原始 Session 绑定、状态、最近一次回执和已保存历史。请求可以省略时间变更、名称或指令;省略的字段保留已存储值,仅修改名称或指令不会改变已提交目标。归一化后等价的修改保留已提交目标与存储字节。修改后的一次性任务以 At 记录保留身份;固定间隔改变后以接纳保存时刻重新起算;钟表规则改变后以同一接纳保存时刻重新解析首个未来目标,而归一化后等价的规则不产生变更。时间变更可以选择不同的重复类型,新规则按创建时相同的方式、以同一接纳保存时刻计算目标。删除会移除该行及其已保存记录([该反转的后果](2026-09-22-schedule-hard-delete-and-bounded-history.zh.md)),因此运行时不会再调度该任务,`history` 也不再按其原始绑定解析。未运行任务不会被重新启用。
页面使用现有 Host 任务 domain 和调度器,不使用 mock 引擎或 Session projection。名称、指令和运行时间行编辑当前任务的同一份本地草稿,一次保存把该草稿作为携带完整预期记录的单个更新提交;取消恢复已存储值,保存失败保留草稿,未保存的草稿会保留到权威刷新之后,保存已提交与目录刷新失败仍是不同结果。暂停和执行历史操作仍不受支持。生命周期状态与最近一次投递确认不描述模型结果。
客户端的呈现从已有持久化数据派生,而不扩展持久化格式。`schedule_create` transcript(文本记录)卡片从该调用对模型可见的结果 JSON 中读出创建的任务——该 JSON 已经序列化规范任务值——而不是声明 `presentationMeta`:持久化 metadata 通道会为一张仅凭结果即可在 Session 日志回放中重建的卡片增加持久字段,而早于该卡片录制的 Session 无需格式变更即可渲染它。侧栏 Session 行的时钟标记占用 root 作用域的 `sidebar.session.row.leading` slot,而不是请求逐 Session provider,因为 Session 作用域的 slot 会绑定列表中每个 Session,从而激活并保留它;同一个 root 作用域属主约定也供给 `sidebar.session.row.hover`,两者都读取共享的 Host 目录快照 `schedule/catalog()`,不读取 Session 日志。
Session 收件箱持久化和任务 put 发生在两个持久化系统中。收件箱持久化先于任务 put,以免消息尚不存在时就标记已投递。收件箱持久化后崩溃或任务写入失败可能重复发送消息;状态、目标和回执一起存储,并不使两个存储具有原子性。投递失败保留任务并输出诊断;没有独立的重试 timer。此功能不创建或替换 Goal。
@@ -56,10 +40,4 @@ Session 收件箱持久化和任务 put 发生在两个持久化系统中。收
## Consequences
**不把 mock 的「每小时整点」引入持久词表。** 设计稿把它与每天、每周、仅一次并列。每小时整点与固定间隔在语义上是同一种按经过时间计量的规则,因此详情里的该项直接映射到既有的间隔类型,而不是新增一个持久种类。若真要新增,需要新的持久变体、解码器、目标解析与工具 schema,而它表达的能力现有间隔已经覆盖。
任务发现和 timer 不依赖已加载的 Session。延迟、绝对时间和固定速率选择器在与 Daily、Weekly、Cron 并存时保留自身语义;读取已有任务不会重写它们。Host 必须提供普通 Session 持久化和恢复服务,而随发行版交付的 Web 组合为整个部署挂载 Schedule 服务。显式删除会阻止后续投递,并将任务从 `list` 和 `catalog` 中移除,不删除对话消息;被移除的行会带走其已保存回执。历史在追加确认时按配置的窗口与条数上限裁剪,随后加载到 Host 内存,并在每次确认时随任务一起重写。分页限制返回记录数量,不限制存储增长或指令字节数。此前被覆盖的回执,以及任务写入失败的投递记录,无法重建。暂停和执行历史操作仍不受支持。
必要覆盖范围包括从已存储任务启动、缺失状态规范化、冷 Session 恢复、仅补发最新发生时点、保留未运行任务且不重复投递、真实消息回执、重启后的删除结果、删除会移除已保存发送记录、排队或持久化失败,以及销毁。钟表规则的验证要求包括缺口和跳过的日期、仅选择较早时点的重叠、小数秒、UTC 范围边缘、已提交目标和别名保留,以及恢复后的时钟回拨。Weekly 另需覆盖星期集合的规范化与校验、跨缺口与重叠的下一目标选择,以及已存集合的保留。历史解码器必须拒绝 Daily、Weekly 与 Cron,而宿主存储接受它们。客户端覆盖范围包括每种重复规则、精确规则时间、时区和星期集合、全部/已开启/未运行状态筛选、保留未运行任务详情和原 Session 导航、确认删除和通知后的权威刷新、空列表、重新连接和晚到响应。呈现覆盖范围包括页面“新建”操作打开新会话、transcript 卡片从不完整或回放的结果 JSON 中收窄任务、页头时钟在恰好一个任务时直接打开并给出数量标签、仅空闲行标记及其悬浮卡片两个任务上限与遗漏行。历史覆盖范围包括旧文件字节保留、追加与重启、不可变的发送指令、最近回执一致性严格校验、稳定游标分页、绑定校验、持久化失败,以及刷新或切换任务期间晚到的分页响应。跨存储崩溃导致的重复投递仍是明确限制,不能被表述为完成保证。
名称、指令和时间编辑覆盖范围包括所有支持的规则类型、完整记录冲突、投递与保存的顺序、取消、规范化后的无变更、历史持久化不变、等待期间的控件、草稿保留,以及无碰撞的任务标识。[已构建 CLI 进程测试](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts) 驱动公开 Remote 请求,并在新 Host 中重新加载实际任务文件字节。任务和回执种子只是已保留数据的输入,不是真实创建、投递或模型录制证据;这些证据需要普通 Session 操作与捕获的模型请求。
任务发现和定时器无需已加载 Session。历史保留在同一任务行中,与确认一同提交;读取不虚构缺失指令、时间戳或更早投递。历史 Session 日志 After、At、Every 保持冻结,不填充此领域。[Schedule 参考](../../../../docs/subsystems/schedule.zh.md)拥有时间、管理、UI 投影和保留契约。[构建后 CLI 测试](../../../../apps/cli/tests/profiles/web/tests/schedule-timing.expected.e2e.ts)通过公开 Remote 请求检查旧原始行、编辑时规范化、冲突和冷重启;种入回执是保留数据证据,不是投递证据。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-09-17-standalone-schedules.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-09-17-standalone-schedules.md
/agent-note-standalone-schedules-and-session-targets:
en: ce8ed282ec843da0
zh: a5ca78422ea009ec
/agent-note-standalone-schedules-and-session-targets/problem:
en: 2a6769cd378455bb
zh: 84cfb0f2e1fde8e1
/agent-note-standalone-schedules-and-session-targets/decision:
en: 73ed15d2219f2898
zh: db8ea6ae79a95241
/agent-note-standalone-schedules-and-session-targets/alternatives-considered:
en: 1def5c19511fc59e
zh: 84f0f5d568272c39
/agent-note-standalone-schedules-and-session-targets/consequences:
en: bda079e488b5374b
zh: d5ffe96b33e8e65d
@@ -0,0 +1,35 @@
# Agent Note: Standalone schedules and Session targets
Status: implemented
English | [中文](2026-09-17-standalone-schedules.zh.md)
## Problem
Host tasks need global management and explicit delivery targets while remaining recognizable in their Workspace.
## Decision
The storage domain, importer, placeholder RRULE, and parallel API decisions are superseded by [typed rule storage and shared recurrence](2026-10-21-schedule-rule-storage.md). Keep the existing `schedule` domain and one management API; the target, execution, and notice decisions below remain current.
Targets are `session`, `new_once`, or `new`. `session` stores one existing Session id; create and edit check, without activating that Session, that it exists and does not belong to a delegated child. `new_once` reserves a Session id when the task is created or retargeted, creates that exact Session at first delivery, and then becomes `session`. `new` saves a reserved Session id in `pendingDelivery` before each create attempt, so a retry after a failed delivery uses the same Session. A created Session uses the target's working directory and Agent preset, or the Host defaults. When the target names a working directory, the Session joins the Workspace registered there, if any. While the Session has no title, it takes the task title; a `new` target adds the Session's creation minute in the timing rule's zone, for example `Weekday digest · 2026-10-12 09:00`, so the Sessions of successive deliveries stay distinguishable. A failed join or rename is logged and does not block delivery. `involvedSessionIds` lists the creating and editing Agent Sessions and each existing or reserved target Session in first-involvement order; Sessions that a `new` target creates are not listed.
The runtime keeps latest-only catch-up. It delivers the latest occurrence at or before the delivery decision and advances to the next future occurrence; an exhausted rule stays stored with `ended` status, and a paused task has no timer. Each delivery of one task, timed or manual, comes at least 60 seconds after the occurrence of the previous delivery, and the occurrence of a manual run is its run time; for a `new` target, whose every delivery creates a Session, a deployment can raise that interval through `newSessionIntervalSeconds`, which defaults to 60. The floor counts from the previous occurrence when the next stored occurrence keeps the interval, and from the previous acknowledgment otherwise, so acknowledgment latency does not accumulate and a late delivery does not shift later occurrences; the next on-time occurrence can then follow the late delivery by less than one interval. A task delivered to a reused Session, `session` or `new_once`, holds its execution slot until the target Agent is idle, and occurrences that become due meanwhile coalesce into one later delivery, so that Session has at most one pending delivery of the task; a `new` target holds no slot, and its launches run beside one another with only the delivery interval between them. Due tasks with a `session` target share one message per target Session, except After and At tasks. Manual run shares target resolution, the delivery interval, Session inbox persistence, the receipt, and the involvement update with timed delivery, but keeps the next occurrence and status. Both refuse an archived destination Session, including a reserved retry, because the archived-Session gate would block the turn that the message wakes. Session inbox persistence precedes the task receipt write, so a crash between the two stores can repeat a message. The implementation adds no scheduler, run, or ownership service.
After a committed create, update, or delete, Schedule queues a change notice on its own chain, so Session I/O never holds the mutation and delivery queue. Each involved Session other than the actor whose Agent is loaded receives a `schedule`-sourced message for its next model step that does not start a model turn, so notices queued while the Session is idle reach the model with its next input instead of each running as a model turn; the message names the change and carries the task id and title as JSON strings. A Session without a loaded Agent receives nothing and reads the current task when it next lists tasks. A notice failure is logged and does not roll back the committed change. Shutdown drains queued notices before storage closes.
## Alternatives considered
**Require a caller-supplied schedule id.** A user-facing title and canonical identity serve different purposes, but accepting ids would expose collision and validation policy. The Host generates identity and returns it for later operations.
**Keep creator Session ownership.** Ownership would keep list and mutation APIs scoped and would conflict with global management, retargeting, and Session creation policies. Historical involvement is metadata and notification routing, not authorization.
**Check spacing by sampling upcoming occurrences.** Each occurrence query enumerates from `DTSTART`, so a high-frequency rule with an early start blocked the Host thread before a sampled check could refuse it, and a sample cannot bound the complete sequence. Static rule checks before enumeration and the per-task delivery interval enforce the spacing instead.
**Add scheduler, run, and notification services.** The existing Schedule service, storage domain, runtime, and Session controller already own these responsibilities at the required scale. New layers would add indirection without changing durability.
**Leave created Sessions untitled and outside Workspaces.** Such a Session appears as one more untitled Session outside the Workspace that owns its directory, so the user cannot tell which task created it or, for a `new` target, which delivery it received. Joining the Workspace at the target directory and naming the Session after the task, with the creation minute for `new`, needs no stored field. A failure is only logged because delivery has priority over presentation.
## Consequences
Tasks outlive Agents and are managed by id. Archive admission reports active Session targets; explicit stop deletes tasks. Host availability, cross-store at-least-once delivery, best-effort notices, and unbounded per-delivery concurrency remain limitations. The [Schedule reference](../../../../docs/subsystems/schedule.md) owns the exact current contracts and the [management upgrade guide](../../../../docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.md) covers changed callers.
@@ -0,0 +1,35 @@
# Agent Note: 独立计划任务与 Session 目标
Status: implemented
[English](2026-09-17-standalone-schedules.md) | 中文
## Problem
宿主任务需要全局管理和显式执行目标,并在工作区中可辨认。
## Decision
存储领域、导入器、占位 RRULE 和并行 API 决策由[带类型规则存储与共享重复计算](2026-10-21-schedule-rule-storage.zh.md)替代。保留现有 `schedule` 领域和统一管理 API;下述目标、执行和通知决策保持有效。
目标分为 `session`、`new_once` 和 `new`。`session` 存储一个现有 Session id;创建和编辑会在不激活该 Session 的情况下检查它存在且不属于被委派的子 Agent。`new_once` 在创建任务或重新指定目标时预留 Session id,在首次投递时创建该精确 Session,然后转换为 `session`。`new` 在每次创建尝试前把预留的 Session id 保存在 `pendingDelivery` 中,因此投递失败后的重试使用同一 Session。新建 Session 使用目标中的工作目录和 Agent preset,未提供时使用 Host 默认值。目标指定工作目录时,该 Session 加入在该目录注册的 Workspace(若存在)。该 Session 尚无标题时以任务标题命名;`new` 目标再加上该 Session 的创建时间(精确到分钟,按规则 `DTSTART` 的时区),例如 `Weekday digest · 2026-10-12 09:00`,以便区分各次投递创建的 Session。加入或命名失败只记录日志,不阻止投递。`involvedSessionIds` 按首次参与顺序列出创建和编辑任务的 Agent Session,以及每个现有或预留的目标 Session;`new` 目标创建的 Session 不列入其中。
运行时保留仅补发最新发生时点的行为。它投递不晚于投递判断时刻的最新发生时点,并推进到下一个未来发生时点;耗尽的规则以 `ended` 状态保留在存储中,暂停的任务没有计时器。同一任务的每次投递,无论定时还是立即执行,都在上一次投递的发生时点之后至少 60 秒,立即执行的发生时点是其运行时间;`new` 目标的每次投递都会创建 Session,部署可通过 `newSessionIntervalSeconds` 加大该间隔,默认 60。下一个已存储发生时点满足该间隔时,最小投递间隔从上一次发生时点起算,否则从上一次确认时间起算,因此确认延迟不会累积,延迟的投递也不会推移之后的发生时点;下一个准时的发生时点随后可能在延迟投递之后不足一个间隔到来。投递到复用 Session(`session` 或 `new_once`)的任务在目标 Agent 空闲之前一直占用其执行槽位,期间到期的发生时点合并为之后的一次投递,因此该 Session 最多有该任务的一次待处理投递;`new` 目标不占用槽位,各次启动并行运行,彼此之间只隔投递间隔。目标为 `session` 的到期任务按目标 Session 共享一条消息,After 和 At 任务除外。立即执行与定时投递共用目标解析、投递间隔、Session 收件箱持久化、回执与相关 Session 更新,但保留下一发生时点和状态。二者都拒绝已归档的目的 Session,包括重试时复用的预留 Session,因为已归档会话门禁会阻止该消息唤醒的轮次。Session 收件箱持久化先于任务回执写入,因此两个存储之间崩溃可能重复消息。实现不增加 scheduler、run 或 ownership service。
create、update 或 delete 提交后,Schedule 在独立的链上排队一条变更通知,因此 Session I/O 不会占用变更与投递队列。除操作者之外、Agent 已加载的每个相关 Session 都会收到一条供下一个模型步骤读取的 `schedule` 来源消息,该消息不会启动模型轮次,因此 Session 空闲期间排队的通知会随其下一条输入到达模型,而不会各自作为一个模型轮次运行;消息说明变更类型,并以 JSON 字符串携带任务 id 和标题。没有已加载 Agent 的 Session 不会收到消息,会在下次列出任务时读取当前任务。通知失败会记录日志,但不会回滚已提交的变更。关闭时先排空已排队的通知,再关闭存储。
## Alternatives considered
**要求调用方提供计划任务 id。** 用户可见标题与规范身份用途不同,但接受 id 会暴露冲突与校验策略。Host 生成身份并返回,供后续操作使用。
**保留创建者 Session 所有权。** 所有权会让 list 与 mutation API 保持作用域限制,并与全局管理、重新指定目标和 Session 创建策略冲突。历史参与关系是元数据和通知路由,不是授权。
**通过抽样即将到来的发生时点检查间隔。** 每次发生时点查询都从 `DTSTART` 开始枚举,因此起始时间较早的高频规则会在抽样检查拒绝它之前阻塞 Host 线程,而且抽样无法约束完整序列。改为在枚举之前做静态规则检查,并用每个任务的投递间隔约束间隔。
**增加 scheduler、run 和 notification service。** 现有 Schedule service、存储领域、runtime 和 Session 控制器已按所需规模承担这些职责。新层级只会增加间接性,不改变持久性。
**让新建 Session 保持无标题且不属于任何 Workspace。** 这样的 Session 会作为又一个无标题 Session 出现在拥有其目录的 Workspace 之外,用户无法分辨是哪个任务创建了它,也无法分辨对于 `new` 目标它接收了哪一次投递。加入目标目录处的 Workspace,并以任务标题命名 Session(`new` 再加创建分钟),不需要存储字段。失败只记录日志,因为投递优先于呈现。
## Consequences
任务寿命长于 Agent,并按 id 管理。归档准入报告活动 Session 目标;显式停止删除任务。宿主可用性、跨存储至少一次投递、尽力通知和每次新建目标的无界并发仍是限制。[Schedule 参考](../../../../docs/subsystems/schedule.zh.md)拥有精确的当前契约,[管理升级指南](../../../../docs/upgrade-guide/v0.2.2-alpha.2/schedule-remote-host-tasks/guide.zh.md)说明调用方变更。
@@ -6,14 +6,14 @@
en: 17a73230ad22ec0b
zh: 5bcf27d7c0e86764
/agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/problem:
en: 98e82a0add324882
zh: c10e85a3f2a522f8
en: c49b11c393e59f35
zh: 03cab3ae79a6c878
/agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/decision:
en: 56328745115714b5
zh: f30d39f59aa06a13
en: 48272c9bbe2a0040
zh: 668799310bcd20ba
/agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/alternatives-considered:
en: 0c4eb01054be1141
zh: 95980f8097fa36fd
en: 7663bb52e1034eeb
zh: 2ef8f146c5642837
/agent-note-schedule-deletes-task-rows-and-bounds-delivery-history/consequences:
en: 05121f4b77b8ee12
zh: 1751c9b1a752ce6b
en: f911ddff2a9b81da
zh: 38ee18e3f6b10c26
@@ -6,15 +6,15 @@ English | [中文](2026-09-22-schedule-hard-delete-and-bounded-history.zh.md)
## Problem
The Schedule domain is one whole-unit JSON document that the backend rewrites on every mutation, so every retained byte in a task row grows every write. Saved delivery records were unbounded: each acknowledgment appended to the array, and a deleted task kept its row and records so the open detail could still read them. The document's size therefore followed a task's delivery count, and deletion added a state every reader had to skip.
The Schedule domain stores each task as one JSON document that the backend rewrites whole on every change of that task, so every retained byte in a task row grows every write of that task. Saved delivery records were unbounded: each acknowledgment appended to the array, and a deleted task kept its row and records so the open detail could still read them. The document's size therefore followed a task's delivery count, and deletion added a state every reader had to skip.
## Decision
Deletion is hard deletion. `ScheduleService.delete` removes the storage row through `tasks.delete`, so the task stops scheduling, leaves `list` and `catalog`, and `history` answers `schedule_not_found` for the same `(sessionId, id)`; the row's saved delivery records are removed with it. The task schema has no `deleted` field, and no client surface offers a recycle bin or a read of an already deleted task's records.
Deletion is hard deletion. The `delete` action of `ScheduleService.edit` removes the storage row through `tasks.delete`, so the task stops scheduling, leaves `list` and `catalog`, and `history` answers `schedule_not_found` for its id; the row's saved delivery records are removed with it. `deleteInactive` removes only ended tasks in one `tasks.deleteMany` batch and preserves active and paused tasks. The task schema has no `deleted` field, and no client surface offers a recycle bin or a read of an already deleted task's records.
Delivery history is bounded by plugin `Config`: `deliveryHistoryDays` (default 30, 1–3650) and `deliveryHistoryRecords` (default 200, 1–10000). `appendDelivery` applies both bounds on the only write path. It keeps the records whose `deliveredAt` is at or after the appended receipt's `deliveredAt` minus the configured day window, keeps the newest `deliveryHistoryRecords` of those, and always retains the appended latest receipt; a pruned window sets `earlierRecordsUnavailable` and `earlierRecordsPruned`, which later appends preserve. The latter flag is optional in stored rows and confirms actual removal; legacy unavailability alone does not imply pruning. The history response includes the current retention limits, and the Client shows the cleanup notice only for confirmed pruning after loading the final nonempty page.
The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision: one authoritative version-1 task domain, timer restoration for active tasks only, cold-Session delivery through the Session controller, the catalog and detail surfaces, and the historical-versus-Host decoder split. Its status vocabulary is `active` or `inactive`; `inactive` is the sole non-active name, and the client filter row reads All, Enabled, and Inactive. That note stays active: this supersession is partial, so it is neither archived nor frozen, and it remains the owner of everything above while the deletion and retention decisions it recorded are replaced here.
The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision: timer restoration for active tasks only, cold-Session delivery through the Session controller, the catalog and detail surfaces, and the historical-versus-Host decoder split. That note stays active: this supersession is partial, so it is neither archived nor frozen, and it remains the owner of everything above while the deletion and retention decisions it recorded are replaced here. [Standalone schedules and Session targets](2026-09-17-standalone-schedules.md) owns the authoritative task domain and its `active`, `paused`, or `ended` status. Native and Remote catalogs report these same three statuses across the Host. The Automation tasks page's status filter row reads All, Enabled, Paused, and Ended.
## Alternatives considered
@@ -24,10 +24,10 @@ The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note ke
**Measure the window from the task instead of from each receipt.** Anchoring the window to the task's creation or committed target would discard a newly written receipt of an old task. Measuring back from the appended receipt's `deliveredAt` keeps the window anchored to the data being kept.
**Keep history unbounded and let operators clean up.** The domain publishes one whole-unit document per write, so unbounded history makes the storage document's size a function of delivery counts. Retention is a bound the storage layout requires, not a retention preference.
**Keep history unbounded and let operators clean up.** The backend rewrites each task document whole on every write of that task, so unbounded history makes the task document's size a function of delivery counts. Retention is a bound the storage layout requires, not a retention preference.
## Consequences
Deletion now offers no recovery: a deleted task's saved deliveries cannot be read back, and a task that still needs its full history must be read before deletion. Configured retention also discards receipts the task once had; the retained flag records that a window was pruned rather than pretending the history is complete.
In exchange, the persisted task set has one deletion semantics, the storage document's size is bounded by configuration instead of by delivery counts, and `inactive` is the only non-active lifecycle name. The plugin `Config` is the place to raise the bounds when a deployment needs longer delivery history.
In exchange, the persisted task set has one deletion semantics, the size of each task document is bounded by configuration instead of by delivery counts, and deletion adds no lifecycle state. The plugin `Config` is the place to raise the bounds when a deployment needs longer delivery history.
@@ -6,15 +6,15 @@ Status: implemented
## Problem
Schedule domain 是后端每次变更都会重写的单个整 unit JSON 文档,因此任务行中保留的每个字节都会随每次写入增长。已保存的发送记录没有上限:每次确认都会向数组追加,而被删除的任务会保留其行与记录,以便已打开的详情仍能读取。于是文档大小随任务的投递次数变化,删除还引入了一个所有读取方都必须跳过的状态。
Schedule domain 把每个任务存储为一个 JSON 文档,后端在该任务每次变更时整体重写它,因此任务行中保留的每个字节都会随该任务的每次写入增长。已保存的发送记录没有上限:每次确认都会向数组追加,而被删除的任务会保留其行与记录,以便已打开的详情仍能读取。于是文档大小随任务的投递次数变化,删除还引入了一个所有读取方都必须跳过的状态。
## Decision
删除是硬删除。`ScheduleService.delete` 通过 `tasks.delete` 移除存储行,因此任务停止调度、离开 `list` 与 `catalog`,`history` 对相同的 `(sessionId, id)` 返回 `schedule_not_found`;该行已保存的投递记录随行一并移除。任务 schema 没有 `deleted` 字段,也没有任何界面提供回收站或读取已删除任务记录的能力。
删除是硬删除。`ScheduleService.edit` 的 `delete` 操作通过 `tasks.delete` 移除存储行,因此任务停止调度、离开 `list` 与 `catalog`,`history` 对其 id 返回 `schedule_not_found`;该行已保存的投递记录随行一并移除。`deleteInactive` 通过一次 `tasks.deleteMany` 批量写入仅删除已结束任务,保留活动和暂停任务。任务 schema 没有 `deleted` 字段,也没有任何界面提供回收站或读取已删除任务记录的能力。
投递历史受插件 `Config` 限制:`deliveryHistoryDays`(默认 30,1–3650)与 `deliveryHistoryRecords`(默认 200,1–10000)。`appendDelivery` 在唯一的写入路径上同时应用这两个上限。它保留 `deliveredAt` 不早于「本次追加回执的 `deliveredAt` 减去配置的天数窗口」的记录,在其中保留最新的 `deliveryHistoryRecords` 条,并始终保留本次追加的最近一次回执;发生裁剪时设置 `earlierRecordsUnavailable` 和 `earlierRecordsPruned`,后续追加会保留这两个标志。后者在存储行中可选,用于确认实际删除;仅有旧格式的不可用标志不表示发生过裁剪。历史响应携带当前保留上限,客户端仅在加载完最后一页且历史非空、确认裁剪时显示清理提示。
[Host-owned scheduled messages](2026-09-16-host-schedule-storage.zh.md) 笔记保留其余决策:唯一的权威版本 1 任务 domain、只为活动任务恢复定时器、通过 Session controller 投递到冷会话、目录与详情界面,以及历史解码器与宿主解码器的划分。其状态词汇为 `active` 或 `inactive`;`inactive` 是唯一的非活动名称,客户端筛选行为全部、活动和未运行。该笔记保持活动状态:这是一次部分取代,因此它既未归档也未冻结,仍是上述内容的归属笔记,而它记录的删除与保留决策由本笔记取代。
[Host-owned scheduled messages](2026-09-16-host-schedule-storage.zh.md) 笔记保留其余决策:只为活动任务恢复定时器、通过 Session controller 投递到冷会话、目录与详情界面,以及历史解码器与宿主解码器的划分。该笔记保持活动状态:这是一次部分取代,因此它既未归档也未冻结,仍是上述内容的归属笔记,而它记录的删除与保留决策由本笔记取代。[独立计划任务与 Session 目标](2026-09-17-standalone-schedules.zh.md) 拥有权威任务 domain 及其 `active`、`paused` 或 `ended` 状态。原生和 Remote 目录在宿主范围内报告相同的三种状态。自动化任务页面的状态筛选行为全部、已开启、已暂停和已结束。
## Alternatives considered
@@ -24,10 +24,10 @@ Schedule domain 是后端每次变更都会重写的单个整 unit JSON 文档
**以任务而非每条回执为窗口起点。** 把窗口锚定在任务的创建时间或已提交目标上,会丢弃旧任务刚写入的回执。从本次追加回执的 `deliveredAt` 向前计算,使窗口锚定在所要保留的数据上。
**保留无上限的历史,由运维清理。** 该 domain 每次写入都发布整个 unit 文档,因此无上限的历史会让存储文档的大小随投递次数增长。保留上限是存储布局所要求的约束,而不是保留策略偏好。
**保留无上限的历史,由运维清理。** 后端在该任务每次写入时整体重写其任务文档,因此无上限的历史会让任务文档的大小随投递次数增长。保留上限是存储布局所要求的约束,而不是保留策略偏好。
## Consequences
删除不再提供恢复能力:已删除任务的已保存投递无法再读回,仍需要完整历史的必须在删除前读取。配置的保留策略也会丢弃任务曾经拥有的回执;保留的标志记录窗口发生过裁剪,而不是假装历史完整。
换取的是:持久任务集合只有一种删除语义,存储文档大小由配置而非投递次数决定,且 `inactive` 是唯一的非活动生命周期名称。当某个部署需要更长的投递历史时,应提高插件 `Config` 中的上限。
换取的是:持久任务集合只有一种删除语义,每个任务文档的大小由配置而非投递次数决定,且删除不增加生命周期状态。当某个部署需要更长的投递历史时,应提高插件 `Config` 中的上限。
@@ -9,14 +9,14 @@
en: 27b4d1d25cd1c178
zh: 3ddc4d9a09b6182d
/agent-note-preset-scoped-schedule-tools/decision:
en: 3c4708981d34217d
zh: cd0c07dc0888f3db
en: 652fb37ad4e5a826
zh: f5c3cc1e9a79b4ca
/agent-note-preset-scoped-schedule-tools/alternatives-considered:
en: 5cfe619038339caa
zh: c2d2651d304d867c
/agent-note-preset-scoped-schedule-tools/consequences:
en: d7c7e6b8e6268559
zh: 801e5be70e00cc90
en: aceed1aa98ed9bec
zh: b9d99a25a8b25417
/agent-note-preset-scoped-schedule-tools/testing:
en: d42cb866907a96b5
zh: 6e66f8babe744bcb
en: 05080859ac790524
zh: 4b220c10da961608
@@ -10,9 +10,9 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md)
## Decision
`@deepseek-ai/dsh-tool-schedule` (`packages/schedule/tool-schedule`) contributes the four tools as a preset-level Consumer. It declares `inject = ['tools']` and registers the definitions on `ctx.tools` from inside `ctx.inject(['schedule'], …)`, so the mounting scope is the one that owns them and the registration waits for the Host Schedule service in that same scope. The shipped Web profile mounts the row in its `standard`, `cordis`, and `ptc` presets and omits it from `minimal`. Cordis effect ownership disposes the definitions with the mount, and a composition that never resolves `schedule` registers none of them. The [Web bundle](../../../../packages/bundle/web-app/README.md) owns the `schedule` and `ui-schedule` rows the shipped composition mounts; this record owns the reminder tools' preset placement.
`@deepseek-ai/dsh-tool-schedule` (`packages/schedule/tool-schedule`) contributes `schedule_create`, `schedule_list`, `schedule_view`, and `schedule_edit` as a preset-level Consumer. It declares `inject = ['tools', 'systemPrompt']` and registers the definitions and shared authorization instruction from inside `ctx.inject(['schedule'], …)`, so the mounting scope owns them and registration waits for the Host Schedule service in that same scope. The shipped Web profile mounts the row in its `standard`, `cordis`, and `ptc` presets and omits it from `minimal`. Cordis effect ownership disposes the definitions with the mount, and a composition that never resolves `schedule` registers none of them. The [Web bundle](../../../../packages/bundle/web-app/README.md) owns the `schedule` and `ui-schedule` rows the shipped composition mounts; this record owns the reminder tools' preset placement.
`@deepseek-ai/dsh-schedule` keeps the version-1 storage domain, the Host timer and serialized queue, Host delivery through the Session controller, the Automation page's backing reads, and the `ctx.schedule` interface. `dsh-tool-schedule` is the model-facing consumer of that interface: it checks selector and identity constraints before the service call, reads `exec.agent` for the Session binding, and maps failures that are not `ScheduleInputError` to `internal_error` so storage details never reach the model.
`@deepseek-ai/dsh-schedule` keeps the `schedule` storage domain, now writing v2 and reading v1, the Host timer and serialized queue, Host delivery, the Automation tasks page's backing reads, and the `ctx.schedule` interface. `dsh-tool-schedule` is the model-facing consumer of that interface: it maps RRULE and target inputs to service requests, reads `exec.agent` for the actor and `this_session` destination, and maps undeclared failures to `internal_error` so storage details never reach the model. Management addresses every Host task by id; the target alone selects the receiving Session.
## Alternatives considered
@@ -26,9 +26,9 @@ English | [中文](2026-09-24-preset-scoped-schedule-tools.zh.md)
- Each preset that mounts the row pays the four schemas' fixed token cost, and tool availability is read from the composition instead of inferred from the Host service's presence.
- A deployment can mount `dsh-schedule` for storage and delivery without granting its agents model-driven reminder management.
- `dsh-schedule` injects no `ctx.tools` and registers no model-facing tool.
- A delegated child inherits the preset's four reminder schemas. `subagentCallerRefusal` in `dsh-tool-schedule` returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }` from each tool when the caller's delegation depth is above zero. The [preset composition decision](../simplification/2026-10-09-preset-owned-subagent-composition.md) removes the redundant child filter; visibility does not authorize execution.
- A Session a delegated child owns can never receive a delivered reminder, so `ScheduleService.create` and `ScheduleService.update` refuse it with `subagent_session`. The refusal reads the delegation depth — the accounting the delegation cap itself enforces, carried by the persisted session header across a cold resume. The rule sits in the service, so other consumers reach it too — the Automation surface included.
- A delegated child inherits the preset's four reminder schemas. `runForCaller` in `dsh-tool-schedule` returns `{ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' }` from each tool when the caller's delegation depth is above zero. The [preset composition decision](../simplification/2026-10-09-preset-owned-subagent-composition.md) removes the redundant child filter; visibility does not authorize execution.
- A Session a delegated child owns can never receive a delivered reminder, so `ScheduleService.create` and target changes or arming through `ScheduleService.edit` refuse it with `subagent_session`. The refusal reads the delegation depth — the accounting the delegation cap itself enforces, carried by the persisted session header across a cold resume. The rule sits in the service, so other consumers reach it too — the Automation surface included.
## Testing
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every tool for a delegated child caller`. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins.
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` pins the four definitions and their error mapping, including `refuses every call from a registered delegated child whose scope mounts the tools`, and `packages/subagent/subagent/tests/schedule-tools.spec.ts` runs a delegated child through the tool executor and pins that refusal without a stored task. `apps/cli/tests/web-agent-presets.e2e.ts` asserts the `minimal` preset's tool list, and `snapshots/web/minimal-preset/tool-schemas.expected.json` records its tool table without reminder schemas. `packages/schedule/schedule/tests/subagent-ownership.spec.ts` pins the delegation-depth refusal, and `scripts/optional-bundles.spec.ts` asserts that both delegation rows in the three presets omit `toolFilter`. The Web preset e2e also checks equal parent/child tool schemas and refusal from all four reminder executors for fresh and seeded children. `snapshots/web/subagent-fork-schedule` records all four refusals in a seeded fork through the shipped Web composition and shares the standard preset's prompt and schema pins.
@@ -10,9 +10,9 @@ Status: implemented
## Decision
`@deepseek-ai/dsh-tool-schedule`(`packages/schedule/tool-schedule`)以 preset 级 Consumer 的身份贡献这四个工具。它声明 `inject = ['tools']`,并在 `ctx.inject(['schedule'], …)` 内通过 `ctx.tools` 注册这些定义,因此拥有它们的是挂载它的作用域,而注册会等待同一作用域中的宿主 Schedule 服务。发布版 Web profile 在其 `standard`、`cordis` 和 `ptc` preset 中挂载该行,`minimal` 不挂载。Cordis 的 effect 所有权随挂载卸载而释放这些定义,而始终未解析出 `schedule` 的组合不会注册其中任何一个。[Web bundle](../../../../packages/bundle/web-app/README.zh.md)负责随发行版交付的组合挂载的 `schedule` 与 `ui-schedule` 两行;本记录负责提醒工具的 preset 归属。
`@deepseek-ai/dsh-tool-schedule`(`packages/schedule/tool-schedule`)以 preset 级 Consumer 的身份贡献 `schedule_create`、`schedule_list`、`schedule_view` 和 `schedule_edit`。它声明 `inject = ['tools', 'systemPrompt']`,并在 `ctx.inject(['schedule'], …)` 内注册这些定义和共用授权指令,因此挂载作用域拥有它们,注册会等待同一作用域中的宿主 Schedule 服务。发布版 Web profile 在其 `standard`、`cordis` 和 `ptc` preset 中挂载该行,`minimal` 不挂载。Cordis 的 effect 所有权随挂载卸载而释放这些定义,而始终未解析出 `schedule` 的组合不会注册其中任何一个。[Web bundle](../../../../packages/bundle/web-app/README.zh.md)负责随发行版交付的组合挂载的 `schedule` 与 `ui-schedule` 两行;本记录负责提醒工具的 preset 归属。
`@deepseek-ai/dsh-schedule` 保留版本 1 storage domain、宿主定时器与串行队列、经由 Session controller 的宿主投递、自动化任务页面的读取来源,以及 `ctx.schedule` 接口。`dsh-tool-schedule` 是该接口面向模型的消费者:它在调用服务前校验选择器与身份约束,从 `exec.agent` 读取 Session 绑定,并把非 `ScheduleInputError` 的失败映射为 `internal_error`,使存储细节不会到达模型。
`@deepseek-ai/dsh-schedule` 保留 `schedule` 存储域,现写入 v2 并读取 v1,同时保留宿主定时器与串行队列、宿主投递、自动化任务页面的读取来源,以及 `ctx.schedule` 接口。`dsh-tool-schedule` 是该接口面向模型的消费者:它将 RRULE 与目标输入映射为服务请求,从 `exec.agent` 读取操作者与 `this_session` 目的地,并把未声明的失败映射为 `internal_error`,使存储细节不会到达模型。管理按 id 寻址宿主全部任务;仅目标选择接收 Session。
## Alternatives considered
@@ -26,9 +26,9 @@ Status: implemented
- 挂载该行的每个 preset 承担四个 schema 的固定 token 成本,工具可用性取自组合,而不是由宿主服务是否存在推断。
- 部署可以只为存储与投递挂载 `dsh-schedule`,而不授予其 Agent 由模型驱动的提醒管理能力。
- `dsh-schedule` 不注入 `ctx.tools`,也不注册任何面向模型的工具。
- 被委派的子 agent 继承 preset 的四个提醒 schema。调用方委派深度大于零时,`dsh-tool-schedule` 中的 `subagentCallerRefusal` 从每个工具返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' }`。[preset 组装决策](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md)移除了重复的子级过滤;可见性不授予执行权限。
- 被委派子 agent 拥有的 Session 永远收不到投递的提醒,因此 `ScheduleService.create` 与 `ScheduleService.update` 会以 `subagent_session` 拒绝它。该拒绝读取委派深度——委派封顶本身执行的记账,由持久化 session header 承载并跨冷恢复保留。这条规则在服务层,因此其它消费方(包括自动化任务页面)也会命中。
- 被委派的子 agent 继承 preset 的四个提醒 schema。调用方委派深度大于零时,`dsh-tool-schedule` 中的 `runForCaller` 从每个工具返回 `{ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' }`。[preset 组装决策](../simplification/2026-10-09-preset-owned-subagent-composition.zh.md)移除了重复的子级过滤;可见性不授予执行权限。
- 被委派子 agent 拥有的 Session 永远收不到投递的提醒,因此 `ScheduleService.create` 以及通过 `ScheduleService.edit` 改变目标或启用任务时会以 `subagent_session` 拒绝它。该拒绝读取委派深度——委派封顶本身执行的记账,由持久化 session header 承载并跨冷恢复保留。这条规则在服务层,因此其它消费方(包括自动化任务页面)也会命中。
## Testing
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every tool for a delegated child caller`。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。
`packages/schedule/tool-schedule/tests/tool-schedule.spec.ts` 固定这四个定义及其错误映射,包括 `refuses every call from a registered delegated child whose scope mounts the tools`;`packages/subagent/subagent/tests/schedule-tools.spec.ts` 通过工具执行器运行一个被委派的子 agent,并在没有已存任务时固定该拒绝。`apps/cli/tests/web-agent-presets.e2e.ts` 断言 `minimal` preset 的工具列表,`snapshots/web/minimal-preset/tool-schemas.expected.json` 记录其不含提醒工具 schema 的工具表。`packages/schedule/schedule/tests/subagent-ownership.spec.ts` 固定委派深度拒绝,`scripts/optional-bundles.spec.ts` 断言三个 preset 的两行委派行都不含 `toolFilter`。Web preset e2e 还检查父子工具 schema 相等,且四个提醒执行器对新建和带种子的子级均拒绝执行。`snapshots/web/subagent-fork-schedule` 通过出货 Web 组合记录带种子 fork 中的四次拒绝,并共享 standard preset 的提示和 schema 预期。
@@ -6,14 +6,14 @@
en: f524c3b0ee74c586
zh: ec4e85f0fd853532
/agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/problem:
en: c4156e2a8a3ad379
zh: 992b76509f83d61f
en: 57f2fb0a35f6a420
zh: 7174afde673c62d6
/agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/decision:
en: b9b203da394f58e5
zh: ac511458d60dab49
en: 136514e302d80f4c
zh: b34e140f41547d06
/agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/alternatives-considered:
en: 8074a2b9b9f5d782
zh: 1604b7ee5d34375e
en: 49cc4e396052fc09
zh: adb8b01f29ce76fb
/agent-note-delivered-reminders-are-framed-as-scheduled-messages-from-the-user/consequences:
en: 85e03b541bfce57c
zh: 77decbb804f6a0b9
en: 55c346fbd5feb417
zh: 29631345d447f643
@@ -6,17 +6,17 @@ English | [中文](2026-09-24-scheduled-message-framing.zh.md)
## Problem
Due reminders reach their original Session as user-role messages with producer kind `schedule`. Before this decision, both renderers opened that message with an instruction about how to treat its payload: one-shot delivery asked the model to present `reminder_prompt_json` as untrusted reminder content and not as new user instructions, and recurring batch delivery asked the same for every `reminder_prompt` in `reminders_json`. The message therefore asserted that its own content was untrusted instead of naming where it came from.
Due reminders reach their target Session as user-role messages with producer kind `schedule`. Before this decision, both renderers opened that message with an instruction about how to treat its payload: one-shot delivery asked the model to present `reminder_prompt_json` as untrusted reminder content and not as new user instructions, and recurring batch delivery asked the same for every `reminder_prompt` in `reminders_json`. The message therefore asserted that its own content was untrusted instead of naming where it came from.
## Decision
`renderReminderFraming` and `renderRecurringReminderBatchFraming` in [`packages/schedule/schedule/src/domain.ts`](../../../../packages/schedule/schedule/src/domain.ts) both emit one shared fixed line, `SCHEDULED_MESSAGE_FRAMING`: `This is a scheduled message from the user`. It is the block's second line, after the bracketed marker (`[SCHEDULE REMINDER]`, `[SCHEDULE REMINDER BATCH]`), and the dynamic field lines are unchanged: a one-shot message still appends `schedule_id_json`, `occurrence_at`, and `reminder_prompt_json`, and a recurring batch still appends `reminders_json`.
The fixed line states the origin of the message: a schedule bound to that Session. A model reading a user-role message whose fixed block carries it reads the following reminder payload (`reminder_prompt_json` in a one-shot message, `reminders_json` in a batch) as content the user scheduled, and the Host cannot attest that the user typed it: `schedule_create` and `schedule_update` let the model write the prompt, and a model-written prompt can carry text the model read from the web, files, or command output. The previous line marked that payload untrusted, and this decision drops that instruction, so the change accepts the residual risk that model-authored text arrives under a user-origin line. Reintroduction condition: a demonstrated injection through a model-written prompt restores a clause that scopes the payload as reminder text rather than a new instruction, and the five pinned framing assertions in the package specs plus `expectReminderFraming` in the Web e2e are the check that such a change is deliberate. Framing-line forgery is closed by encoding: the schedule id and prompt are JSON strings, the occurrence instant is a validated canonical RFC 3339 value, and each occupies one line, so a prompt carrying embedded newlines or an `occurrence_at:`-style line cannot add framing lines to the block. The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision, including delivery through the Session controller and the saved delivery records.
The fixed line states the origin of the message: a schedule that delivers to that Session. A model reading a user-role message whose fixed block carries it reads the following reminder payload (`reminder_prompt_json` in a one-shot message, `reminders_json` in a batch) as content the user scheduled, and the Host cannot attest that the user typed it: `schedule_create` and `schedule_edit` let the model write the prompt, and a model-written prompt can carry text the model read from the web, files, or command output. The previous line marked that payload untrusted, and this decision drops that instruction, so the change accepts the residual risk that model-authored text arrives under a user-origin line. Reintroduction condition: a demonstrated injection through a model-written prompt restores a clause that scopes the payload as reminder text rather than a new instruction, and the five pinned framing assertions in the package specs plus `expectReminderFraming` in the Web e2e are the check that such a change is deliberate. Framing-line forgery is closed by encoding: the schedule id and prompt are JSON strings, the occurrence instant is a validated canonical RFC 3339 value, and each occupies one line, so a prompt carrying embedded newlines or an `occurrence_at:`-style line cannot add framing lines to the block. The [Host-owned scheduled messages](2026-09-16-host-schedule-storage.md) note keeps the rest of its decision, including delivery through the Session controller and the saved delivery records.
## Alternatives considered
**Keep the untrusted-content instruction.** It asserted that the prompt was untrusted input, which the delivered message does not need: the prompt is written in the Session the schedule is bound to — by the model through `schedule_create` and `schedule_update`, or by the user in the Web task detail — and the delivery is an ordinary user-role message there.
**Keep the untrusted-content instruction.** It asserted that the prompt was untrusted input, which the delivered message does not need: the model writes the prompt through `schedule_create` and `schedule_edit`, a human caller writes it through the Web task detail or Remote `create` and `edit`, and the delivery is an ordinary user-role message in its target Session.
**Change only the recurring batch line.** One-shot and recurring delivery would then disagree about the origin of the same kind of message, and each later wording change would need both renderers edited separately. Both paths now read one constant.
@@ -24,6 +24,6 @@ The fixed line states the origin of the message: a schedule bound to that Sessio
Model-visible reminder text changes for both delivery paths, so a Session log recorded before this decision reconstructs the previous framing, and the Web notice that renders a delivered message shows the new line when expanded. Nothing else moves: no session event, storage field, client code, protocol, or durable format changes, and the delivered text remains reconstructable from the log.
The prompt text carries no authorship guarantee. It is written in the Session the schedule is bound to, by the model through `schedule_create` and `schedule_update` or by the user in the Web task detail, and a model-written reminder can quote text the model read from the web, files, or command output. The task's Session binding scopes which Session's model reaches the task; it is not caller authorization and says nothing about where the prompt content came from. The Decision holds the accepted risk and its reintroduction condition.
The prompt text carries no authorship guarantee. The model writes it through `schedule_create` and `schedule_edit`, a human caller writes it through the Web task detail or Remote `create` and `edit`, and a model-written reminder can quote text the model read from the web, files, or command output. Those tools reach every Host task by id from any Session whose preset mounts them, so the task's target Session is not caller authorization and says nothing about where the prompt content came from. The Decision holds the accepted risk and its reintroduction condition.
No recorded-session snapshot covers a delivered reminder, and this change adds none: no committed fixture contains a `schedule` message, and `snapshots/web/schedule-catalog` records catalog queries only. Two harness capabilities are missing for such a fixture: no scenario patch controls the wall clock that `packages/schedule/schedule/src/runtime.ts` reads for delivery, and the snapshot harness seeds Sessions rather than the schedule storage domain that holds Host tasks, so those rows exist only where a Web test writes them by hand. This change records the missing harness support instead of a fixture. The delivered text is pinned by the five full-string assertions in `packages/schedule/schedule/tests/{domain,daily,weekly,cron}.spec.ts` and by `expectReminderFraming` in `apps/web/tests/schedule-after.e2e.ts`, which asserts the line in the assembled request for the one-shot and recurring paths.
@@ -6,17 +6,17 @@ Status: implemented
## Problem
到期的提醒以生产者 kind 为 `schedule` 的 user-role 消息进入其原 Session。在本决策之前,两个渲染器都用一句关于如何处理其载荷的固定指令开篇:单次投递要求模型把 `reminder_prompt_json` 作为不可信的提醒内容呈现、而不是新的用户指令;周期批次投递对 `reminders_json` 中的每个 `reminder_prompt` 提出同样的要求。于是这条消息断言自身内容不可信,而没有说明它来自哪里。
到期的提醒以生产者 kind 为 `schedule` 的 user-role 消息进入其目标 Session。在本决策之前,两个渲染器都用一句关于如何处理其载荷的固定指令开篇:单次投递要求模型把 `reminder_prompt_json` 作为不可信的提醒内容呈现、而不是新的用户指令;周期批次投递对 `reminders_json` 中的每个 `reminder_prompt` 提出同样的要求。于是这条消息断言自身内容不可信,而没有说明它来自哪里。
## Decision
[`packages/schedule/schedule/src/domain.ts`](../../../../packages/schedule/schedule/src/domain.ts) 中的 `renderReminderFraming` 与 `renderRecurringReminderBatchFraming` 都输出同一条固定行,即模块常量 `SCHEDULED_MESSAGE_FRAMING`:`This is a scheduled message from the user`;它是该块的第二行,位于方括号标记(`[SCHEDULE REMINDER]`、`[SCHEDULE REMINDER BATCH]`)之后。动态字段行不变:单次消息仍追加 `schedule_id_json`、`occurrence_at`、`reminder_prompt_json`,周期批次仍追加 `reminders_json`。
这条固定行说明消息的来源:绑定到该 Session 的一条定时任务。模型读到固定块中带有它的 user-role 消息时,会把随后的提醒载荷(单次消息的 `reminder_prompt_json`、批次的 `reminders_json`)当作用户安排的内容,而 Host 无法证明该文本由用户键入:`schedule_create` 与 `schedule_update` 允许模型写入提示词,模型写入的提示词可以带上模型从网页、文件或命令输出中读到的文本。旧固定行把该载荷标记为不可信,本决策有意去掉这一指令,因此接受「模型生成的文本以用户来源行投递」这一残留风险。再引入条件:一旦出现经由模型写入提示词完成注入的实例,就恢复一句把载荷限定为提醒文本、而非新指令的说明;包内五处固定断言与 Web e2e 的 `expectReminderFraming` 是「此类改动必须是有意为之」的检查。固定行无法被动态字段伪造,这由编码保证:schedule id 与提示词是 JSON 字符串,发生时点是经校验的规范 RFC 3339 值,且各自只占一行,因此带有换行或形如 `occurrence_at:` 的提示词无法向该块增加固定行。[Host 拥有的定时消息](2026-09-16-host-schedule-storage.zh.md) 记下的其余决策不变,包括通过 Session controller 投递以及保存的投递记录。
这条固定行说明消息的来源:投递到该 Session 的一条定时任务。模型读到固定块中带有它的 user-role 消息时,会把随后的提醒载荷(单次消息的 `reminder_prompt_json`、批次的 `reminders_json`)当作用户安排的内容,而 Host 无法证明该文本由用户键入:`schedule_create` 与 `schedule_edit` 允许模型写入提示词,模型写入的提示词可以带上模型从网页、文件或命令输出中读到的文本。旧固定行把该载荷标记为不可信,本决策有意去掉这一指令,因此接受「模型生成的文本以用户来源行投递」这一残留风险。再引入条件:一旦出现经由模型写入提示词完成注入的实例,就恢复一句把载荷限定为提醒文本、而非新指令的说明;包内五处固定断言与 Web e2e 的 `expectReminderFraming` 是「此类改动必须是有意为之」的检查。固定行无法被动态字段伪造,这由编码保证:schedule id 与提示词是 JSON 字符串,发生时点是经校验的规范 RFC 3339 值,且各自只占一行,因此带有换行或形如 `occurrence_at:` 的提示词无法向该块增加固定行。[Host 拥有的定时消息](2026-09-16-host-schedule-storage.zh.md) 记下的其余决策不变,包括通过 Session controller 投递以及保存的投递记录。
## Alternatives considered
**保留「不可信内容」指令。** 它断言提示词是不可信输入,而投递的消息并不需要这一断言:提示词写在绑定该定时任务的 Session 内——由模型通过 `schedule_create` 与 `schedule_update` 写入,或由用户在 Web 任务详情中写入——投递本身就是该 Session 中的普通 user-role 消息。
**保留「不可信内容」指令。** 它断言提示词是不可信输入,而投递的消息并不需要这一断言:模型通过 `schedule_create` 与 `schedule_edit` 写入提示词,人工调用方通过 Web 任务详情或 Remote `create` 与 `edit` 写入它,投递本身就是目标 Session 中的普通 user-role 消息。
**只改周期批次那一行。** 单次与周期投递会对同类消息的来源给出不同说法,此后每次改措辞都要分别改两个渲染器。现在两条路径读同一个常量。
@@ -24,6 +24,6 @@ Status: implemented
两个投递路径的模型可见提醒文本都改变,因此在该决策之前记录的 Session 日志重建出的是旧的固定文本;Web 中渲染该投递消息的通知在展开时显示新的一行。其余不动:没有 session 事件、存储字段、客户端代码、协议或持久化格式变化,投递文本仍可从日志重建。
提示词文本不携带作者保证。它写在绑定该定时任务的 Session 内——由模型通过 `schedule_create` 与 `schedule_update` 写入,或由用户在 Web 任务详情中写入——模型创建的提醒可以把模型从网页、文件或命令输出中读到的文本原样写入。任务的 Session 绑定限定的是哪个 Session 的模型能访问该任务;它不是调用方鉴权,也不说明提示词内容的来源。本决策中记下该残留风险与再引入条件。
提示词文本不携带作者保证。模型通过 `schedule_create` 与 `schedule_edit` 写入它,人工调用方通过 Web 任务详情或 Remote `create` 与 `edit` 写入它;模型创建的提醒可以把模型从网页、文件或命令输出中读到的文本原样写入。这些工具可以从任何挂载它们的 preset 所属的 Session 按 id 访问 Host 的每个任务,因此任务的目标 Session 不是调用方鉴权,也不说明提示词内容的来源。本决策中记下该残留风险与再引入条件。
没有录制会话快照覆盖提醒投递,本次也没有新增:已提交夹具中没有 `schedule` 消息,`snapshots/web/schedule-catalog` 只记录任务查询。构成该夹具还缺两项 harness 能力:没有场景补丁能控制 `packages/schedule/schedule/src/runtime.ts` 读取的墙上时钟;快照 harness 播种的是 Session,而不是承载 Host 任务的 schedule storage domain,那些任务行只在 Web 测试里手工写入。因此本次记录缺失的 harness 支持,而不新增夹具。投递文本改由 `packages/schedule/schedule/tests/{domain,daily,weekly,cron}.spec.ts` 中五处整串断言,以及 `apps/web/tests/schedule-after.e2e.ts` 中在装配后请求上断言该行、覆盖单次与周期两条路径的 `expectReminderFraming` 固定。
@@ -9,11 +9,11 @@
en: abd0263d14861926
zh: e1736cd08e87f795
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/decision:
en: fdd39b7e8fa89d70
zh: 4a0dfc81509e5485
en: f1c2b98bf56cdba3
zh: 7e9444f8e73a4834
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/alternatives-considered:
en: 1737484c099fab52
zh: 303b144c52d167bd
en: 3964f7d653747b55
zh: b50636faea4917ef
/agent-note-shared-time-vocabulary-for-wall-clock-selectors/consequences:
en: 79d8d66071453d1f
zh: f940f0b6d74148d6
en: 9fdaa9da9c9952eb
zh: b941f68c9c1bb994
@@ -10,11 +10,11 @@ English | [中文](2026-09-24-shared-time-vocabulary.zh.md)
## Decision
`dsh-util-time` owns the time vocabulary that boundaries accept. `packages/util/time/src/instant.ts` holds the parsers, `src/duration.ts` holds the span type, and `src/index.ts` re-exports both and keeps `canonicalClientTimeZone` as the `string | undefined` wrapper the existing wire boundaries consume.
`dsh-util-time` owns the time vocabulary that boundaries accept. `packages/util/time/src/instant.ts` holds strict instant and zone parsers, `src/duration.ts` holds the span type, and `src/cron.ts` / `src/rrule.ts` hold bounded recurrence values. `src/index.ts` exports them and keeps `canonicalClientTimeZone` as the `string | undefined` wrapper the existing wire boundaries consume.
The library answers discriminated results and carries no failure vocabulary. `parseOffsetInstant`, `fourDigitYearEpoch`, `parseLocalCalendar`, and `canonicalizeTimeZone` answer an `accepted` arm or a `rejected` arm naming a stable reason (`not_rfc3339`, `out_of_range`, `not_a_calendar_date`, `invalid_numeric_offset`, `malformed`, `blank`, `padded`, `not_area_location`, `unsupported`, `not_canonical_shape`). Each caller maps a reason onto its own code and diagnostic, so the library never writes model-facing text. `formatFourDigitYearInstant` returns the canonical instant text or `undefined` outside the bound, `isFourDigitYearInstant` answers whether an epoch is representable at all, and `resolveLocalInstant` answers epoch milliseconds or `undefined` for a wall-clock value inside a forward transition's gap. The reason vocabulary is parallel between the two strict parsers: the same condition is `out_of_range` in both, so year 0 is refused by `parseOffsetInstant` and `parseLocalCalendar` alike, while `resolveLocalInstant` accepts any year a real `Temporal` date carries because its callers derive local dates at the UTC edges. `LocalCalendarTime.year` records that split.
Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they now call the shared parser and map its reason. Schedule still owns the durable record shapes, the fold and transition authority, the injection-resistant framing, and all recurrence arithmetic: the cron engine, the daily and weekly date walks, the latest-due search, and the schedule-specific accepted-decision bound.
Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `decodeInstant`, `parseAtInput`, and `futureInstant` remain Schedule entry points with their existing codes and diagnostics; they call the shared parser and map its reason. Pure Cron/RRULE parsing and bounded occurrence searches belong to the library, take explicit reference times, and validate committed targets with `fourDigitYearEpoch`. Schedule owns durable records, the fold and transition authority, injection-resistant framing, daily and weekly date walks, delivery limits, and domain errors. The shared values own no task state, wall clock, or timers.
`dsh-time-context` consumes it too and keeps its stricter policy. `deriveBrowserTimeZoneContext` reads each user-rpc zone through `canonicalizeTimeZone` and refuses an alias whose canonical answer differs from the reported value, so the request boundary still requires an identity another process resolves back to the same name. Time-context owns its three refusals and their messages; the shared entry only answers the canonical name or a reason, and its `unsupported` rejection carries the platform error the library caught, so that refusal keeps its `cause` in both consumers.
@@ -22,7 +22,7 @@ Schedule consumes it and keeps every domain decision. `canonicalizeTimeZone`, `d
The last copy of the canonical instant profile moves too. `packages/session/session-format-v0-to-v1/src/payload-validation.ts` validated a stored schedule instant with its own regular expression and round trip; the shared `fourDigitYearEpoch` owns that same profile, so the migration now asks it and keeps its own error type and message. Because that migration reads released logs, its accepted set is a compatibility promise: `packages/session/session-format-v0-to-v1/tests/validation.spec.ts` accepts the four-digit-year bounds and refuses each spelling a regular expression alone would admit (`0000`, `2026-02-30`, a four-digit fraction, a numeric offset, surrounding whitespace).
The maintained `@js-temporal/polyfill` 0.5.1 becomes a runtime dependency of `dsh-util-time` as well as of `dsh-schedule`. Local resolution continues to use it, so the Host's IANA data still decides gaps and overlaps and no caller owns offset sampling. `util/time`'s own description and README drop the `zero-dependency` phrase as ambiguous: the group's charter forbids harness dependencies so any group may depend on util, and does not ban external packages, which is why `packages/README.md` and the `util/` line in `AGENTS.md` keep the phrase while `packages/util/README.md` and this package's own description name what it loads.
The maintained `@js-temporal/polyfill` 0.5.1 is a runtime dependency of `dsh-util-time` as well as of `dsh-schedule`; `rrule` supplies RRULE enumeration behind the library's strict syntax and cost checks. Local resolution uses Temporal, so the Host's IANA data decides gaps and overlaps and no caller owns offset sampling. The util group's charter forbids harness dependencies so any group may depend on util; it permits external packages, which this package's own description and README identify.
Observable behavior does not change. Every accepted input resolves to the same epoch, every refused input raises the same `ScheduleInputError` or `ScheduleLogError` code and the same message, and the stored `scheduledAt` profile is unchanged, so no durable record and no recorded snapshot is re-recorded. Schedule's suites assert error codes and a few unrelated message substrings, so the assertion this change adds to `packages/schedule/schedule/tests/domain.spec.ts` is the only place that pins the three local-calendar message strings. `packages/util/time/tests/instant.spec.ts` covers the new entries directly, per-file 100% included.
@@ -38,13 +38,13 @@ Observable behavior does not change. Every accepted input resolves to the same e
**Hold the span in nanoseconds.** `Temporal` carries nanoseconds internally as a `bigint`, so a nanosecond span is representable. It was rejected for the same reason the boundaries stay in milliseconds: the count would have to be a `bigint`, which no `number` arithmetic, no `Date`, and no `JSON.stringify` accepts, so every consumer and every durable record would need a string or binary hop to move it. A nanosecond span as a `number` would instead be quantized to roughly 256 ns at the current epoch, which is a different value wearing the same name.
**Add formatting and DST arithmetic for other consumers too.** No current consumer needs model-facing formatting or offset arithmetic from this library: `dsh-time-context` owns its own formatter and zone policy text. Adding them now would give the library a public operation set with no consumer evidence, against the package rule that ties each abstraction to a current owner and need.
**Share model-facing formatting too.** `dsh-time-context` owns its formatter and zone policy text. Moving that presentation into the library would add consumer policy to the shared arithmetic, against the package rule that ties each abstraction to a current owner and need.
## Consequences
The time profile now has one home. A change to the accepted instant profile or the zone profile is made once and covered once, and a new boundary imports it instead of copying it. Schedule's `domain.ts` loses the five regular expressions that spelled the instant, calendar-date, local-time, and zone profiles, the `Intl` canonicalization, and the hand-rolled calendar conversion. It still imports the library's two bound constants for its date arithmetic at the UTC edges and delegates every representability guard to `isFourDigitYearInstant`, so the range itself has one owner.
The cost is a wider published surface and a heavier dependency graph: `dsh-util-time` gains a runtime dependency on `@js-temporal/polyfill`, so a consumer that imports only `canonicalClientTimeZone` now loads that module too. The library is also no longer a pure "validation and canonicalization only" package, which its README and package description had to state and which its Known Limitations section now records. Schedule keeps a thin mapping layer at each entry. The local-calendar and instant mappers switch over the library's closed reason unions with a `never` default, so a newly added reason fails the build there instead of silently taking a catch-all. The zone mapper instead branches only on `not_canonical_shape` — a reason the current IANA data never produces, so it is guarded by a `v8 ignore` rather than a `never` default — and folds `blank`, `padded`, `not_area_location`, and `unsupported` into one diagnostic. A reason added to `TimeZoneRejection` later would therefore compile there and silently take that generic message.
The cost is a wider published surface and a heavier dependency graph: the root entry resolves `@js-temporal/polyfill` and `rrule` even for consumers that only need a zone or span. The README records that cost and the bounded recurrence profiles. Schedule keeps a thin mapping layer at each entry. The local-calendar and instant mappers switch over the library's closed reason unions with a `never` default, so a newly added reason fails the build there instead of silently taking a catch-all. The zone mapper instead branches only on `not_canonical_shape` — a reason the current IANA data never produces, so it is guarded by a `v8 ignore` rather than a `never` default — and folds `blank`, `padded`, `not_area_location`, and `unsupported` into one diagnostic. A reason added to `TimeZoneRejection` later would therefore compile there and silently take that generic message.
A value type publishes what its consumers call, so the span exposes the constructor and the split that `dsh-time-context` uses and nothing else. A conversion, an arithmetic operation, or a `zero` identity lands with the caller that needs it; the seconds-valued fields at `dsh-schedule` and the DeepSeek file store are the spans that will ask for a second-unit conversion, and the bound and the freeze the class already carries are what make that addition a small one. The package README records the un-migrated boundaries as a known limitation.
@@ -10,11 +10,11 @@ Status: implemented
## Decision
`dsh-util-time` 拥有各边界所接收的时间词汇。解析器位于 `packages/util/time/src/instant.ts`,时间段类型位于 `src/duration.ts`,`src/index.ts` 转出两者,并保留 `canonicalClientTimeZone` 作为既有协议边界消费的 `string | undefined` 包装。
`dsh-util-time` 拥有各边界所接收的时间词汇。严格时刻与时区解析器位于 `packages/util/time/src/instant.ts`,时间段类型位于 `src/duration.ts`,有界重复规则值位于 `src/cron.ts` / `src/rrule.ts`。`src/index.ts` 导出这些入口,并保留 `canonicalClientTimeZone` 作为既有协议边界消费的 `string | undefined` 包装。
本库回答带判别值的结果,不持有失败词汇。`parseOffsetInstant`、`fourDigitYearEpoch`、`parseLocalCalendar` 与 `canonicalizeTimeZone` 回答 `accepted` 分支,或回答携带稳定原因的 `rejected` 分支(`not_rfc3339`、`out_of_range`、`not_a_calendar_date`、`invalid_numeric_offset`、`malformed`、`blank`、`padded`、`not_area_location`、`unsupported`、`not_canonical_shape`)。每个调用方把原因映射成自己的错误码与诊断文案,因此本库从不撰写面向模型的文本。`formatFourDigitYearInstant` 返回规范时刻文本,越界时返回 `undefined`;`isFourDigitYearInstant` 回答某个纪元是否可表示;`resolveLocalInstant` 回答纪元毫秒,对落在前向跳变缺口内的墙钟值回答 `undefined`。两个严格解析器的原因词汇彼此对称:同一条件在两者中都叫 `out_of_range`,所以年份 0 被 `parseOffsetInstant` 与 `parseLocalCalendar` 同样拒绝;而 `resolveLocalInstant` 接受真实 `Temporal` 日期携带的任何年份,因为它的调用方需要在 UTC 边界推导本地日期。`LocalCalendarTime.year` 记录了这一分工。
Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们现在调用共享解析器并映射其原因。Schedule 仍拥有持久记录结构、折叠与状态转移权威、抗注入的框架文本,以及全部重复规则运算:cron 引擎、每日与每周日期遍历、最近到期搜索,以及 Schedule 特有的决策时刻边界。
Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`decodeInstant`、`parseAtInput` 与 `futureInstant` 仍是 Schedule 的入口,保留既有错误码与诊断文案;它们调用共享解析器并映射其原因。纯 Cron/RRULE 解析与有界发生时点搜索归本库所有,接收显式参考时间,并通过 `fourDigitYearEpoch` 校验已提交时点。Schedule 拥有持久记录、折叠与状态转移权威、抗注入的框架文本、每日与每周日期遍历、投递限制及领域错误。共享值不拥有任务状态、墙钟或定时器。
`dsh-time-context` 同样消费它,并保留自己更严格的策略。`deriveBrowserTimeZoneContext` 通过 `canonicalizeTimeZone` 读取每条 user-rpc 时区,并拒绝规范答案与所报值不同的别名,因此请求边界仍然要求另一个进程能解析回同一名称。三条拒绝与它们的文案归 time-context 所有;共享入口只回答规范名称或一个原因;被拒绝的结果中只有 `unsupported` 会携带本库捕获到的平台错误,使该拒绝在两个消费方都保留其 `cause`。
@@ -22,7 +22,7 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec
最后一份规范时刻剖面副本也一并迁移。`packages/session/session-format-v0-to-v1/src/payload-validation.ts` 原本用自己的一段正则与往返比对校验持久记录里的调度时刻;共享的 `fourDigitYearEpoch` 拥有同一剖面,因此该迁移改为询问它,并保留自己的错误类型与文案。由于这个迁移要读取已发布的日志,其接受集是兼容性承诺:`packages/session/session-format-v0-to-v1/tests/validation.spec.ts` 接受四位年份两端,并拒绝只靠正则会放进来的每种拼写(`0000`、`2026-02-30`、四位小数、数字偏移、首尾空白)。
受维护的 `@js-temporal/polyfill` 0.5.1 在成为 `dsh-schedule` 运行时依赖之外,也成为 `dsh-util-time` 的运行时依赖。本地解析继续使用它,因此缺口与重叠仍由宿主 IANA 数据决定,也没有调用方需要自己实现偏移采样。`util/time` 自身的描述与 README 去掉了 `zero-dependency` 这一说法,因为它容易被误读:该组的约定禁止的是 harness 依赖(以便任何组都能依赖 util),并不禁止外部包;因此 `packages/README.md` 与 `AGENTS.md` 里的 `util/` 一行保留该说法,而 `packages/util/README.md` 与本包自己的描述写明它加载了什么。
受维护的 `@js-temporal/polyfill` 0.5.1 是 `dsh-util-time` 与 `dsh-schedule` 的运行时依赖;`rrule` 在本库的严格语法与成本检查之后提供 RRULE 枚举。本地解析使用 Temporal,因此缺口与重叠由宿主 IANA 数据决定,也没有调用方需要自己实现偏移采样。util 组的约定禁止 harness 依赖,以便任何组都能依赖 util;它允许外部包,本包自己的描述与 README 写明了这些依赖。
可观察行为不变。每个被接受的输入解析出相同的纪元值,每个被拒绝的输入抛出相同的 `ScheduleInputError` 或 `ScheduleLogError` 错误码与相同的消息,存储的 `scheduledAt` 剖面不变,因此没有持久记录或录制快照需要重录。Schedule 的测试断言错误码以及少量无关的消息子串,因此本次在 `packages/schedule/schedule/tests/domain.spec.ts` 新增的断言是唯一固定这三条本地日历消息的地方。`packages/util/time/tests/instant.spec.ts` 直接覆盖新增入口,包含逐文件 100% 覆盖。
@@ -38,13 +38,13 @@ Schedule 消费它,并保留全部域内决策。`canonicalizeTimeZone`、`dec
**用纳秒保存时间段。** `Temporal` 内部以 `bigint` 携带纳秒,所以纳秒时间段是可表示的。之所以否决,理由与边界保持毫秒相同:计数必须变成 `bigint`,而 `number` 算术、`Date` 与 `JSON.stringify` 都不接受它,于是每个消费方与每条持久记录都要多一次字符串或二进制转换。若改用 `number` 表示纳秒,在当前离线纪元量级上它会被量化到约 256 ns,那是同一个名字下的另一个值。
**同时为其他消费方加入格式化与 DST 运算。** 目前没有消费方需要本库提供面向模型的格式化或偏移运算:`dsh-time-context` 自己拥有格式化器与时区策略文本。现在加入只会给本库一个没有消费方证据的公开操作集合,违背"每项抽象都绑定当前所有者与需求"的包规则。
**同时共享面向模型的格式化。** `dsh-time-context` 拥有自己的格式化器与时区策略文本。把这些呈现迁入本库会向共享算术加入消费方策略,违背“每项抽象都绑定当前所有者与需求”的包规则。
## Consequences
时间剖面现在只有一个归宿。时刻剖面或时区剖面的变更只做一次、只覆盖一次,新边界导入它而不是复制它。Schedule 的 `domain.ts` 去掉了为时刻、日历日期、本地时间与时区剖面命名的五段正则、`Intl` 规范化与手写日历换算。它仍然导入本库的两个边界常量用于其 UTC 边界日期运算,并把每处可表示性守卫委托给 `isFourDigitYearInstant`,因此范围本身只有一个所有者。
代价是更宽的已发布接口与更重的依赖图:`dsh-util-time` 增加了对 `@js-temporal/polyfill` 的运行时依赖,因此只导入 `canonicalClientTimeZone` 的消费方也会加载该模块。本库也不再是纯"只做校验与规范化"的包——其 README 与包描述必须说明这一点,其"已知限制"一节现在也记录了它。Schedule 在每个入口保留一层薄映射。本地日历与时刻映射函数以 `never` 默认分支穷尽 switch 本库的封闭原因联合,因此新增原因会让这两个调用点构建失败,而不是静默走兜底分支。时区映射函数则只对 `not_canonical_shape` 分支——当前 IANA 数据不会产生该原因,因此它由 `v8 ignore` 守护而不是 `never` 默认分支——并把 `blank`、`padded`、`not_area_location` 与 `unsupported` 合并成一条诊断。因此日后给 `TimeZoneRejection` 新增原因时会通过编译并静默套用那条通用文案。
代价是更宽的已发布接口与更重的依赖图:根入口会解析 `@js-temporal/polyfill` 和 `rrule`,只需要时区或跨度的消费方也一样。README 记录了这些成本与有界重复规则子集。Schedule 在每个入口保留一层薄映射。本地日历与时刻映射函数以 `never` 默认分支穷尽 switch 本库的封闭原因联合,因此新增原因会让这两个调用点构建失败,而不是静默走兜底分支。时区映射函数则只对 `not_canonical_shape` 分支——当前 IANA 数据不会产生该原因,因此它由 `v8 ignore` 守护而不是 `never` 默认分支——并把 `blank`、`padded`、`not_area_location` 与 `unsupported` 合并成一条诊断。因此日后给 `TimeZoneRejection` 新增原因时会通过编译并静默套用那条通用文案。
值类型只发布消费方会调用的部分,因此这个时间段只暴露 `dsh-time-context` 用到的构造入口与拆解,其余不发布。某个换算、某个算术运算或 `zero` 恒等元都随第一个需要它的调用方落地;`dsh-schedule` 与 DeepSeek 文件存储里以秒为单位的字段就是将来会要求第二个单位换算的那些跨度,而类已经携带的范围约束与冻结正是让这次添加保持很小的原因。包 README 把这些尚未迁移的边界记为已知限制。
@@ -0,0 +1,37 @@
# Bilingual-pair consistency record for 2026-10-20-workspace-tree-state-per-pane.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-20-workspace-tree-state-per-pane.md
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open:
en: 3768a6ac42af3a0b
zh: ba3c0826b2a4d287
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/problem:
en: 3a7f14dd68a3ff14
zh: b21be07e8a7e6024
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision:
en: a15c7c13f167e5ac
zh: ff261e3705c47ff0
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision/the-tree-is-drawn-inside-each-file-tab-and-its-state-is-kept-per-pane:
en: 432aff475f1dfd21
zh: bbc058c1f967c067
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision/the-rows-are-a-controlled-component-factory-over-flat-entries:
en: a06955933f9f7f0e
zh: ccda2bd27175d36b
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision/the-plugin-that-mounts-the-tree-decides-where-a-file-lands:
en: 7cf8e3671900fe71
zh: 952f69cba9c44c10
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision/navigation-is-consumed-by-the-destination-tab:
en: e7b254df55d9768d
zh: d3303f20bb9ebdd6
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/decision/each-package-works-without-the-others:
en: dd160808a3ac77bc
zh: f63741f159717072
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/alternatives-considered:
en: 1c5501c71afc7748
zh: 3a2b0ec2d7923a12
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/consequences:
en: 586ec09cfcf60b82
zh: ef683318fbf68d71
/agent-note-the-workspace-tree-is-per-pane-state-drawn-inside-each-file-tab-and-the-plugin-mounting-it-decides-where-files-open/verification:
en: eae354783022bed8
zh: fe2563a3bb259d55
@@ -0,0 +1,74 @@
# Agent Note: The workspace tree is per-pane state drawn inside each file tab, and the plugin mounting it decides where files open
Status: implemented
English | [中文](2026-10-20-workspace-tree-state-per-pane.zh.md)
## Problem
Reading several workspace files needs a tree beside their previews without losing expansion, loaded levels, width, scroll, or keyboard position on every tab switch. The dock mounts only the selected tab's body, so a component instance cannot own the state shared by a pane's file tabs.
A floating panel holds one tab. A preview's file picker must replace that tab in its panel, while the files page must remain available and open content in the dock. A covering tree must close where content is navigated to, not where the initiating click happened.
## Decision
### The tree is drawn inside each file tab, and its state is kept per pane
`ui-sidebar-right` supplies `useTabInfo().panel` with the containing pane's `id` and `isFloating`; moving a tab updates those fields without changing `tab.id`. It supplies no pane lifetime. `ui-sidebar-files` owns each pane's tree state, visibility, width, listing, directory watches, scroll, and last revealed file. The navigator and toggle are Session-scoped Component Factories; `ui-sidebar-documentpreview` renders them inside the tab's content row and header, with stable positions across loading states. The docking kit does not acquire a files-specific overlay or layout rule.
A pane's records follow the tabs whose navigator last drew there, using each tab's `signal`. A replacement in the same pane retains the records. A moved tab uses its destination pane's records; a pane without records starts hidden at the default width. Tab-owned preview scroll is independent of that tree state. Records are released after their last associated tab closes or draws the navigator elsewhere.
Directory watches follow visible drawings rather than retained records. Hidden trees hold no Host directory watch; showing them again refreshes the root and expanded directories while retaining rows. A same-pane tab switch keeps the listing and watches across the replacement drawing. This extends the [directory watch lifetimes](../feature/2026-09-17-sidebar-file-and-directory-auto-refresh.md) from one tab to the pane's drawn tree.
The files face owns ancestor reveal, scrolling, row measurement, and focus across drawings, so replacing a drawing does not discard an ongoing interaction. [The navigator reference](../../../../packages/client/ui-sidebar-files/README.md#the-navigator) owns layout, workspace-command, and keyboard rules.
### The rows are a controlled Component Factory over flat entries
The root-scoped `sidebar.files.tree` Factory keeps reusable rows, its local `accessory` slot, and localized copy with the files plugin. Callers own data access, expansion, opening, and reveal. The workspace navigator adapts its pane's directory states to these inputs.
### The plugin that mounts the tree decides where a file lands
`FileNavigatorInput.onOpen(address)` is the containing plugin's callback. The navigator constructs the file address but neither chooses placement nor closes the initiating tree after the call. Its `page` input controls layout only. A callback keeps the same navigator usable for the files page and document previews without teaching its rows either host's opening policy.
The [preview and files-page callbacks](../../../../packages/client/ui-sidebar-files/README.md#the-navigator) express different lifetimes: the preview gives way to new content, while the files page remains a directory browser. [Right Sidebar placement](../../../../packages/client/ui-sidebar-right/README.md#ctxsidebarright) owns replacement and reveal; the navigator does not duplicate those policies.
### Navigation is consumed by the destination tab
The files face follows the existing navigation observable only for tabs attached to its navigator. It retains each tab's consumed revision independently of the drawing and releases that subscription on tab closure or plugin disposal. It does not require a layout inventory, navigation-origin field, or an opening result from the right Sidebar.
The face waits for the destination drawing and measures its current row, so the previous tab's width cannot decide whether content is covered. It consumes navigation even while hidden to prevent a later manual show from replaying an old close. [The navigator reference](../../../../packages/client/ui-sidebar-files/README.md#the-navigator) defines the navigation sources and revision exclusions.
### Each package works without the others
The packages compose through the right Sidebar's tab information, the files Factories, and the tab-type registry. The preview imports only the files Factory declarations; files has no preview dependency. Without a registered viewer, the files page still lists the workspace and disables file rows it cannot open. Without the files plugin, the unregistered Factory positions render nothing and the preview keeps its own header, body, and file-handoff slots.
## Alternatives considered
**A static tree package or a component in `ui-primitives`.** The [package-shape rule](../../../../docs/defensive-patterns/package-surface.md) excludes new static libraries. A primitive would also require each caller to supply the generic tree labels. The Factory keeps that copy and registration with files, at the cost of requiring that plugin to draw rows.
**A tree that owns directory reads or requires a complete path list.** A workspace is listed one expanded directory at a time. The tree therefore accepts partial entries and per-directory loading, failure, and truncation state. Owning reads inside each drawing would split the state and watch lifetimes that must survive tab switches.
**A pane lifetime signal.** Floating and docking can replace the pane while retaining the tab. A pane signal would end tree state too early and invite attaching tab-owned resources to the wrong lifetime; transferring the signal would make it outlive the pane id used as the state key. The tabs' existing signals provide the required release condition.
**A pane-level overlay that stays mounted.** It requires a layer above docked and floating tab hosts and changes to layout, focus, measurement, and drop targets to avoid intercepting input, including floating resize handles. Drawing inside tabs keeps these concerns in their existing owners.
**Keep visited bodies mounted or copy per-tab trees.** Retaining every body still creates independent trees and watches for tabs sharing a pane and retains each preview's rendered content. Copying state cannot transfer watches and needs a conflict rule when tabs move between panes.
**Keep watches for a pane's whole lifetime or release by inspecting its layout.** The main docked pane rarely disappears, so lifetime-bound watches remain after hiding. Inspecting tab kinds in the layout couples files to every navigator consumer and still does not express whether the tree is drawn.
**A focus request bit consumed by a component effect.** A request stored on the initiating pane can survive a reveal elsewhere and affect a later drawing; a hidden consumer has no element to focus. The face ties focus to its actual drawings instead.
**Carry a dragged tab's tree preference into its new pane.** This needs another transfer policy and conflicts with the state already owned by the destination pane. A new pane starts with the same defaults as every other new pane.
## Consequences
Tab remounts do not own or reset the pane's tree. Moving a tab selects the destination's state rather than copying the source's; hiding releases directory watches without deleting expansion and scroll. Navigation consumption is per tab, while display preferences remain per pane, so an open in another pane does not close the source tree.
The files page retains directory reload and directory-action controls; a preview retains its file controls and handoff. Opening policy remains with those hosts, not the reusable rows.
## Verification
- `packages/client/ui-sidebar-right/tests/tab-info.client.spec.tsx`, `service.client.spec.ts`, and `seat.client.spec.tsx` cover live pane information, replacement, reveal, and framework tab hooks.
- `packages/client/ui-sidebar-files/tests/` covers per-pane state, navigation consumption, drawing lifetimes, workspace roots, and file opening callbacks.
- `packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx`, `file-tree-interactions.client.spec.tsx`, and `file-tree-factory.client.spec.tsx` cover generic rows, independent accessories, and real Factory composition with locale and fallback.
- `apps/web/tests/file-browser.e2e.ts` and `apps/web/tests/file-browser-composition.e2e.ts` own browser evidence; the latter disables each of `ui-sidebar-documentpreview` and `ui-sidebar-files` in the shipped Web composition.
@@ -0,0 +1,74 @@
# Agent Note: 工作区目录树是按分栏保存的状态,在每个文件 tab 内绘制;挂载它的插件决定文件在哪里打开
Status: implemented
[English](2026-10-20-workspace-tree-state-per-pane.md) | 中文
## 问题
连续阅读多个工作区文件需要预览旁的目录树在每次切换 tab 后保留展开状态、已加载的层、宽度、滚动位置与键盘位置。停靠布局只挂载选中 tab 的正文,因此组件实例不能拥有分栏内各文件 tab 共用的状态。
一个浮窗只容纳一个 tab。预览的文件选择器必须在浮窗内替换该 tab,文件页则必须保持可用,并在停靠区打开内容。遮盖正文的目录树应在内容被导航到的地方关闭,而不是在发起点击的地方关闭。
## 决定
### 目录树在每个文件 tab 内绘制,其状态按分栏保存
`ui-sidebar-right` 通过 `useTabInfo().panel` 提供所在分栏的 `id` 与 `isFloating`;移动 tab 时更新这些字段,`tab.id` 保持不变。它不提供分栏生命周期。`ui-sidebar-files` 拥有各分栏的目录树状态、可见性、宽度、列举、目录监听、滚动与上次定位的文件。导航栏和开关是 Session 作用域的 Component Factory;`ui-sidebar-documentpreview` 在 tab 的内容行与头部渲染它们,加载状态变化时保持位置稳定。停靠套件不增加 files 专属的覆盖层或布局规则。
分栏记录跟随最近在该分栏绘制导航栏的 tab,以各 tab 的 `signal` 为依据。同一分栏内的替换保留记录。移走的 tab 使用目标分栏的记录;没有记录的分栏默认隐藏目录树、使用默认宽度。tab 拥有的预览滚动状态独立于目录树状态。最后一个关联 tab 关闭或在别处绘制导航栏后,记录被释放。
目录监听跟随可见的绘制,而不是保留的记录。隐藏的目录树不持有 Host 目录监听;再次显示时保留行并刷新根目录与已展开目录。同一分栏内切换 tab 时,替代绘制之间保留目录列表与监听。这把[目录监听生命周期](../feature/2026-09-17-sidebar-file-and-directory-auto-refresh.zh.md)从单个 tab 扩展为分栏中已绘制的目录树。
files face 负责跨绘制的祖先定位、滚动、行宽测量与焦点,因此替换绘制不会丢弃进行中的交互。[导航栏参考](../../../../packages/client/ui-sidebar-files/README.zh.md#the-navigator)定义布局、工作区命令与键盘规则。
### 各行是以扁平条目为输入的受控 Component Factory
root 作用域的 `sidebar.files.tree` Factory 将可复用的行、局部 `accessory` slot 和本地化文案留在 files 插件。调用方负责数据访问、展开、打开与定位。工作区导航栏把分栏的目录状态转换为这些输入。
### 挂载目录树的插件决定文件落在哪里
`FileNavigatorInput.onOpen(address)` 是容纳导航栏的插件提供的回调。导航栏构造文件地址,但不选择落位,也不在调用后关闭发起侧目录树。`page` 输入只控制布局。回调使同一导航栏能同时用于文件页与文档预览,不必让各行知道这两种宿主的打开策略。
[预览与文件页的回调](../../../../packages/client/ui-sidebar-files/README.zh.md#the-navigator)表达不同的生命周期:预览让位给新内容,文件页则保持为目录浏览器。[右侧 Sidebar 落位](../../../../packages/client/ui-sidebar-right/README.zh.md#ctxsidebarright)负责替换与揭示,导航栏不重复这些策略。
### 导航由目标 tab 消费
files face 仅跟随已关联到其导航栏的 tab 的现有导航可观察值。它独立于绘制保留各 tab 已消费的 revision,并在 tab 关闭或插件卸载时释放订阅。它不需要右侧 Sidebar 提供布局清单、导航来源字段或打开结果。
face 等待目标绘制并测量其当前行宽,因此上一个 tab 的宽度不能决定内容是否被覆盖。隐藏期间也消费导航,防止之后手动显示时重放旧的关闭操作。[导航栏参考](../../../../packages/client/ui-sidebar-files/README.zh.md#the-navigator)定义导航来源与 revision 排除规则。
### 每个包都可以单独工作
各包通过右侧 Sidebar 的 tab 信息、files Factory 和 tab 类型注册表组合。预览仅导入 files Factory 的声明;files 不依赖预览。没有已注册查看器时,文件页仍列出工作区,并禁用无法打开的文件行。没有 files 插件时,未注册的 Factory 位置不绘制内容,预览保留自己的头部、正文和文件交接 slot。
## 考虑过的替代方案
**静态目录树包或 `ui-primitives` 中的组件。** [包形态规则](../../../../docs/defensive-patterns/package-surface.zh.md)排除新增静态库。primitive 还要求各调用方传入通用目录树文案。Factory 使文案与注册留在 files,代价是绘制各行必须加载该插件。
**由目录树读取目录,或要求完整路径列表。** 工作区逐个展开的目录列出。因此目录树接收不完整条目,以及各目录的加载、失败与截断状态。在每次绘制中拥有读取会拆散必须跨 tab 切换保留的状态和监听生命周期。
**分栏生命周期信号。** 浮出和停靠可能替换分栏,但保留 tab。分栏信号会过早结束目录树状态,还会诱使调用方把 tab 资源绑到错误的生命周期;转移信号则让它比用作状态键的 pane id 活得更久。tab 已有的信号提供了所需的释放条件。
**始终挂载的分栏级覆盖层。** 它需要在停靠与浮动 tab 宿主之上增加一层,并修改布局、焦点、测量与拖放目标,避免拦截包括浮窗缩放手柄在内的输入。在 tab 内绘制则让这些职责留在原有所有者处。
**保留已访问正文或复制逐 tab 的目录树。** 保留所有正文仍会为同一分栏的不同 tab 创建独立目录树与监听,并保留各预览的已渲染内容。复制状态无法转移监听,还需要在 tab 跨分栏移动时决定冲突如何处理。
**让监听与分栏同寿,或检查布局后释放。** 主停靠分栏很少消失,因此按其生命周期持有的监听在隐藏后仍存在。检查布局中的 tab 类型会让 files 与每个导航栏消费方耦合,仍不能表达目录树是否正在绘制。
**由组件 effect 消费的聚焦请求位。** 保存在发起分栏的请求可能在揭示别处后留存,影响之后的绘制;隐藏的消费方也没有可聚焦元素。face 则把焦点与实际绘制绑定。
**把被拖动 tab 的目录树偏好带到新分栏。** 这需要另一套转移策略,并与目标分栏已经拥有的状态冲突。新分栏使用与其他新分栏相同的默认值。
## 后果
tab 重新挂载不拥有也不重置分栏目录树。移动 tab 时选择目标状态,不复制源状态;隐藏释放目录监听,但不删除展开与滚动状态。导航消费按 tab 保存,显示偏好仍按分栏保存,因此在另一分栏打开内容不会关闭源目录树。
文件页保留目录重新读取与目录操作控件;预览保留文件控件与交接操作。打开策略由这些宿主拥有,不属于可复用的行。
## 验证
- `packages/client/ui-sidebar-right/tests/tab-info.client.spec.tsx`、`service.client.spec.ts` 与 `seat.client.spec.tsx` 覆盖实时分栏信息、原位替换、揭示与框架 tab hook。
- `packages/client/ui-sidebar-files/tests/` 覆盖逐分栏状态、导航消费、绘制生命周期、工作区根目录与文件打开回调。
- `packages/client/ui-sidebar-files/tests/file-tree.client.spec.tsx`、`file-tree-interactions.client.spec.tsx` 与 `file-tree-factory.client.spec.tsx` 覆盖通用行、独立附件,以及带 locale 和 fallback 的真实 Factory 组合。
- `apps/web/tests/file-browser.e2e.ts` 与 `apps/web/tests/file-browser-composition.e2e.ts` 负责浏览器验证;后者在随包发布的 Web 组合中分别禁用 `ui-sidebar-documentpreview` 与 `ui-sidebar-files`。
@@ -0,0 +1,19 @@
# Bilingual-pair consistency record for 2026-10-21-schedule-rule-storage.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-10-21-schedule-rule-storage.md
/agent-note-schedule-rule-storage-and-shared-recurrence:
en: 34817514a06a4351
zh: a9e33a1c4d5845d1
/agent-note-schedule-rule-storage-and-shared-recurrence/problem:
en: 22eed4a004cbb1c5
zh: dc7b6f8ed9c074cf
/agent-note-schedule-rule-storage-and-shared-recurrence/decision:
en: 50bfa3e81af7c2b0
zh: e9bd5fae6e611030
/agent-note-schedule-rule-storage-and-shared-recurrence/alternatives-considered:
en: fbfcd35c35fb637a
zh: df9dd646e6d18e3c
/agent-note-schedule-rule-storage-and-shared-recurrence/consequences:
en: 61213641597c18bb
zh: 393a79013e311311
@@ -0,0 +1,25 @@
# Agent Note: Schedule rule storage and shared recurrence
Status: implemented
English | [中文](2026-10-21-schedule-rule-storage.zh.md)
## Problem
Host tasks already use the versioned `schedule` domain. A second domain, importer, and placeholder RRULE duplicate timing and storage authority. Cron and RRULE should be supported timing types rather than separate generations of the task API.
## Decision
Use `schedule` version 2 with `compatibleVersions: [1]`, retaining its backend routing, envelope, and whole-unit layout. Extend the existing accepted-version policy to authoritative JSON and SQLite units; reads leave storage unchanged, and the next write commits the current stamp with its data. Add `rrule` to the six existing record kinds and evaluate every kind normally. Remove the standalone store importer, import marker, placeholder RRULE, and parallel Session-bound management API. Move reusable Cron and RRULE parsing and bounded occurrence arithmetic into `dsh-util-time`; Schedule owns records, targets, delivery admission, history, and errors.
An explicit target wins. Without one, read an existing `sessionId` as a Session target; otherwise reserve a stable `new_once` target. Optional new metadata receives read defaults without rewriting storage. Every successful edit writes the current row format without `sessionId`. Custom timing accepts either RRULE or a five-field Cron expression with an explicit zone; UI labels name neither syntax. Model guidance continues to teach RRULE.
This partially supersedes [standalone schedules](2026-09-17-standalone-schedules.md): its target, execution, notification, and Host-wide management decisions remain. It restores the domain and layout in [Host schedule storage](2026-09-16-host-schedule-storage.md), while replacing that note's Session-bound management API. Both notes remain active and link to this decision.
## Alternatives considered
Changing the domain or layout would require routing and copy logic without changing the feature. Converting Cron into RRULE can change day-of-month/day-of-week and time-zone semantics. A generic value migration engine is deferred until an incompatible storage version requires one; the existing domain envelope already identifies the version.
## Consequences
Missing creation metadata cannot recover historical timestamps. A default target must retain its reserved Session identity across reads and retries. Old receipts need their original destination retained before retargeting. A current unit stamp can contain older untouched rows, so future compatible readers must retain those defaults until a complete rewrite allows removal. Old binaries reject a newer stamp. Session inbox persistence and task acknowledgment remain separate commits, so delivery remains at least once.
@@ -0,0 +1,25 @@
# Agent Note: 调度规则存储与共享重复时间计算
Status: implemented
[English](2026-10-21-schedule-rule-storage.md) | 中文
## 问题
Host 任务已经使用带版本的 `schedule` 域。第二个域、导入器和占位 RRULE 会重复定义时间与存储的权威来源。Cron 和 RRULE 应当是并列的时间规则类型,而非两代任务 API。
## 决策
使用 `schedule` 版本 2 和 `compatibleVersions: [1]`,保留后端路由、封套和整单元布局。将现有接受版本策略扩展到权威 JSON 和 SQLite 单元;读取保持存储不变,下一次写入将当前版本戳与数据一同提交。在现有六种记录类型旁添加 `rrule`,所有类型均正常求值。移除独立存储的导入器、导入标记、占位 RRULE 和并行的 Session 绑定管理 API。将可复用的 Cron、RRULE 解析及有界时间计算移至 `dsh-util-time`;Schedule 负责记录、目标、投递准入、历史和领域错误。
显式目标优先。缺少目标时,将已有 `sessionId` 读取为 Session 目标;否则保留稳定的 `new_once` 目标。新增可选元数据使用读取默认值,不重写存储。每次成功编辑都写入不含 `sessionId` 的当前行格式。自定义时间同时接受 RRULE 和带显式时区的五字段 Cron 表达式;界面标签不提示任何语法名称。模型指引继续推荐 RRULE。
本决策部分替代[独立定时任务](2026-09-17-standalone-schedules.zh.md),保留其目标、执行、通知和宿主级管理决策。它恢复[宿主任务存储](2026-09-16-host-schedule-storage.zh.md)的领域与布局,并替代按 Session 绑定的管理 API。两个 note 保持活动并链接到本决策。
## 考虑过的替代方案
更换域或布局需要增加路由和复制逻辑,却不改变功能。将 Cron 转换为 RRULE 可能改变月内日期、星期和时区语义。通用值迁移引擎留待不兼容存储版本确有需要时再引入;现有域封套已经标识版本。
## 影响
缺失的创建元数据无法恢复历史时间戳。默认目标必须在读取和重试间保持预留 Session 标识。重新指定目标前,旧回执需要保留原始投递目标。当前单元版本戳可包含未改动的旧行,因此未来兼容读取器必须保留这些默认规则,直至完整重写后才能移除。旧程序拒绝更新的版本戳。Session 收件箱持久化与任务确认仍是两次独立提交,因此投递仍然至少一次。
@@ -18,8 +18,8 @@
en: ca63fb903b447c2d
zh: 3014adbdb0a890ee
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/implementation-and-responsibilities/client-and-sidebar:
en: 5cb8326d8a5b0407
zh: a31173f990276856
en: 5be003d933357fee
zh: 0aec7cea1b06a7ce
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/watch-requests-and-notifications:
en: 025ba83ae78824df
zh: 264d74d2bdfe3d27
@@ -42,8 +42,8 @@
en: d688642e5f272d48
zh: 96088fbc0471aeae
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/directory-node-tree-and-lifecycle:
en: 2ea8615be8d5229b
zh: 0c73fa4ebb06445e
en: eb011d181eeb83e3
zh: 7d2cb793fd1737b5
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/user-flows:
en: eb4005a334103895
zh: e2c207faffa64e57
@@ -57,8 +57,8 @@
en: 4f343f7a6c4d3ba4
zh: a4390843a20f8dde
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/readiness-races-and-refresh-coalescing:
en: caadd187479e9074
zh: 3deedd8093f60703
en: baff3282e8925728
zh: 2052ca0afadd7a1b
/agent-note-on-demand-watching-and-automatic-refresh-for-sidebar-previews-and-file-trees/alternatives-considered:
en: 8a8c19229647c760
zh: 2de283fc2c815e65
@@ -60,10 +60,11 @@ Notifications invoke existing reload/list operations; a failed reload does not r
| Package-private `ResourceGroup` | [resource-group.ts](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/resource-group.ts) | Observes members through existing `resources.source(address)`; `add` joins a resource, `set` reconciles full membership, and `close` releases all members without changing the generic Resource service |
| `DocumentBodyOwner`, `HtmlBody`, `createReadHtmlRelative` | [Renderer inputs](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts), [HTML body](../../../../packages/client/ui-sidebar-documentpreview/src/client/html/HtmlBody.tsx), [Related-file reader](../../../../packages/client/ui-sidebar-documentpreview/src/client/html/read-relative.ts) | Renderers declare read members through `addResource` and publish the current dependency list through `setResources`; HTML adds CSS/JS resources from Host-reported paths after each read returns and releases unreferenced members after parsing |
| Document renderers | [DocumentContent](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) and renderer directories in the same package | Do not watch directly; keep consuming text, bytes, or renderer revisions; `failed()` ends renderer loading without recording a successful version. Check cancellation of previous work, release of old objects, and retention of existing view preferences during refresh |
| `filesFace`, `FilesInjected` | [Files face](../../../../packages/client/ui-sidebar-files/src/client/face.ts) | Remain the existing business entry point, directly owning each Tab's root node; bind directory reads and change streams and forward expand, collapse, refresh, and automatic-refresh operations without a new `FilesController` |
| `filesFace`, `FilesInjected` | [Files face](../../../../packages/client/ui-sidebar-files/src/client/face.ts) | Remain the existing business entry point, directly owning each pane's root node while a navigator draws the pane's tree ([per-pane state](../architecture/2026-10-20-workspace-tree-state-per-pane.md)); bind directory reads and change streams and forward expand, collapse, refresh, and automatic-refresh operations without a new `FilesController` |
| Package-private `DirectoryNode` | [directory-node.ts](../../../../packages/client/ui-sidebar-files/src/client/directory-node.ts) | Represents one open directory, owning its stream, read state, and open children; handles local refresh, expansion, recursive closure, and propagation of automatic-refresh state; `setExpanded` updates pending restoration from the latest expansion preferences |
| `createFilesStore`, `FilesTabState`, `LevelState` | [Files store](../../../../packages/client/ui-sidebar-files/src/client/store.ts) | Retain expansion, scrolling, and displayed directory data; distinguish initial loading from refresh over existing content to avoid unmounting subtrees on every background read; hold no watcher or AbortController |
| `FilesBody`, `Level`, `Entry` | [FilesBody.tsx](../../../../packages/client/ui-sidebar-files/src/client/FilesBody.tsx) | Delegate expansion, collapse, refresh, and panel unmount to injected callbacks; render node results without scanning the entire tree into a watch set, using existing framework hooks and store reads |
| `createFilesStore`, `FilesPaneState`, `FilesTreeState`, `LevelState` | [Files store](../../../../packages/client/ui-sidebar-files/src/client/store.ts) | Retain expansion and displayed directory data; distinguish initial loading from refresh over existing content to avoid unmounting subtrees on every background read; hold no watcher or AbortController |
| `FileNavigator` | [FileNavigator.tsx](../../../../packages/client/ui-sidebar-files/src/client/FileNavigator.tsx), [workspace-tree.ts](../../../../packages/client/ui-sidebar-files/src/client/workspace-tree.ts) | Read per-pane state through framework hooks; convert listed levels into entries and directory states; pass expansion, collapse, and drawing lifetimes to the injected Files face, which owns listing, refresh, and watches |
| `FileTree` | [FileTree.tsx](../../../../packages/client/ui-sidebar-files/src/client/FileTree.tsx) | Draw entries, directory states, and expansion from props; report row actions through `onToggle` and `onOpen`. The root-scoped `sidebar.files.tree` Factory reads localized copy and its local `accessory` Component through framework seats, without owning listings or watches |
| Files registration | [Files client/index.ts](../../../../packages/client/ui-sidebar-files/src/client/index.ts) | Add a directory-change callback to the existing `filesFace`; keep async effects in injection, without importing another feature plugin's runtime exports |
## Watch requests and notifications
@@ -176,13 +177,14 @@ Pause and play use existing icons; manual reload retains its circular arrow. No
```text
Files.open
→ FilesBody → Session.cwd + Tab
→ filesFace.start → DirectoryNode.open
→ FileNavigator → Session.cwd + pane
→ filesFace.hold → DirectoryNode.open
→ changes(sessionId, path)
→ Host.watch(depth: 0) → ready
→ DirectoryNode → list(sessionId, path)
→ createFilesStore.levels[path]
→ Level / Entry
→ createFilesStore.byPane[paneId].tree.levels[path]
→ FileNavigator → workspace-tree.ts: workspaceEntries / workspaceDirectories
→ renderFactorySlot('sidebar.files.tree', input) → Level / Entry
Entry.expand
→ filesFace.toggle
@@ -204,7 +206,7 @@ The directory panel obtains invalidations and listings through injected Remote c
## Directory-node tree and lifecycle
The Files runtime is itself an on-demand directory tree. It does not first construct the whole Workspace tree or separately derive a flat watcher set. Existing `filesFace` owns each Tab's root; `DirectoryNode` owns reads, observation, and release recursively, without another controller class.
The Files runtime is itself an on-demand directory tree. It does not first construct the whole Workspace tree or separately derive a flat watcher set. Existing `filesFace` owns each pane's root; `DirectoryNode` owns reads, observation, and release recursively, without another controller class.
| Node responsibility | Behavior |
|---|---|
@@ -239,14 +241,14 @@ The parent's watch still detects deletion, renaming, or replacement of a collaps
| First open | Subscribe to the file Resource and read contents | Open the root node, which subscribes and lists |
| Expand child | No effect | The parent opens the child; the child subscribes and reads direct entries, progressively restoring still-present descendants from preferences |
| Collapse child | Open file previews keep their watches | Release that directory and its hidden descendants; expansion preferences and displayed cache may remain |
| Switch Tab or unmount panel | The Tab pin retains file metadata; an unmounted body does not reread, and refreshes on return according to pending Resource changes and toggle state | Retain expanded nodes and watchers for the Tab lifetime; do not introduce another panel-visibility lifetime |
| Switch Tab or hide the tree | The Tab pin retains file metadata; an unmounted body does not reread, and refreshes on return according to pending Resource changes and toggle state | Switching between a pane's file tabs keeps expanded nodes and watchers, because the next tab draws the tree in the same commit; hiding the tree or showing a tab without it closes them while the store keeps expansion and displayed levels, which the next drawing lists again in place |
| Manual refresh | Reuse the current preview reload without rebuilding the Resource system | Recursively refresh open children from the root, without entering collapsed directories or rebuilding all watchers |
| Last holder closes | Resource abort ends the file stream; the Host awaits watcher closure | Tab closure ends every directory stream, cancels reads, and forgets Tab state |
| Last holder closes | Resource abort ends the file stream; the Host awaits watcher closure | Once no navigator is mounted in a pane and no open tab last drew one there, every directory stream ends, reads are cancelled, and the pane's state is forgotten |
| Connection recovers | Stat again after the new stream's ready frame, discovering changes even without event replay | List every still-watched directory after its new stream's ready frame |
Files watches follow Tab lifetimes. Collapse closes the corresponding subtree; Tab closure releases the root and its entire active tree. Temporarily hiding the panel does not rebuild nodes, keeping implementation within the existing entry point and directory objects. The store retains expansion preferences; nodes use them for progressive restoration only when reopened, without a second global expansion set.
Files watches follow each pane's drawn tree. Collapse closes the corresponding subtree; the end of the pane's last drawing releases the root and its entire active tree, and the pane's state is forgotten once no open tab last drew the tree there. The store retains expansion preferences and displayed levels; nodes use them for progressive restoration only when reopened, without a second global expansion set.
`ResourceRegistry` continues sharing identical complete file Resource addresses. Parent-child ownership prevents duplicate active branches inside one Tab. This version adds no global watcher deduplication across Sessions, windows, or path aliases. Ordinary file rows do not each subscribe to file watches; only files opened as preview Resources acquire independent file observation.
`ResourceRegistry` continues sharing identical complete file Resource addresses. Parent-child ownership prevents duplicate active branches inside one pane. This version adds no global watcher deduplication across Sessions, windows, or path aliases. Ordinary file rows do not each subscribe to file watches; only files opened as preview Resources acquire independent file observation.
## User flows
@@ -281,8 +283,8 @@ Observation, reads, and presentation need a few explicit ordering rules, not dis
- Events mean that a target may have changed, not exact replay of a user operation. Duplicate Chokidar events and consecutive writes may coalesce; files deduplicate versions, and directories coalesce pending refreshes.
- Each directory has at most one active list. Further invalidation during that request or its completion marks a pending reread, which runs afterwards rather than building an arbitrary queue of refresh jobs.
- File refresh reuses read generations and renderer revisions. Consecutive notifications must not let old requests overwrite new content or endlessly reload an already handled version.
- Background directory refresh retains the displayed listing without a display-unused `refreshing` flag. Only a directory without displayable entries enters `loading`, avoiding subtree flicker and repeated watcher reconstruction.
- After collapse, deletion, or Tab closure, late cancelled reads cannot recreate state or restore watchers. Cancellation closes the Host watcher even while the generator is suspended at a yielded frame; stream and plugin teardown await closure.
- Background directory refresh retains the displayed listing and marks it `refreshing`; the display ignores the mark, while locating a file waits on it for the directory to be listed again. Only a directory without displayable entries enters `loading`, avoiding subtree flicker and repeated watcher reconstruction.
- After collapse, deletion, the end of a drawing, or the pane's state being forgotten, late cancelled reads cannot recreate state or restore watchers. Cancellation closes the Host watcher even while the generator is suspended at a yielded frame; stream and plugin teardown await closure.
- Temporary file disappearance while its parent remains does not end observation. Ordinary file changes and watcher failures remain distinct; same-path file watches cover atomic saves and delete/recreate.
- Existing file reads are not transaction snapshots: writes can occur between stat and content reading. Later notifications trigger refresh; automatic refresh does not promise an atomic snapshot for every read.
@@ -60,10 +60,11 @@ Sidebar 的 Document Preview 和 Files 面板都需要反映磁盘上的最新
| 包内 `ResourceGroup` | [resource-group.ts](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/resource-group.ts) | 通过现有 `resources.source(address)` 观察成员;`add` 加入资源,`set` 更新完整成员列表,`close` 释放全部成员,不改变通用 Resource 服务 |
| `DocumentBodyOwner`、`HtmlBody`、`createReadHtmlRelative` | [渲染器输入](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts)、[HTML body](../../../../packages/client/ui-sidebar-documentpreview/src/client/html/HtmlBody.tsx)、[关联文件读取](../../../../packages/client/ui-sidebar-documentpreview/src/client/html/read-relative.ts) | 渲染器通过 `addResource` 声明读取到的成员,通过 `setResources` 提交本次依赖列表;HTML 在每次读取返回后按 Host 报告的路径加入 CSS/JS 资源,解析结束后释放不再引用的成员 |
| 各文档渲染器 | [DocumentContent](../../../../packages/client/ui-sidebar-documentpreview/src/client/document/contract.ts) 及同包各渲染器目录 | 不接 watch;继续消费文本、字节或 renderer revision;`failed()` 结束渲染器加载但不记录成功版本。检查刷新时取消旧任务、释放旧对象及保留现有视图偏好 |
| `filesFace`、`FilesInjected` | [Files face](../../../../packages/client/ui-sidebar-files/src/client/face.ts) | 继续作为已有业务入口,直接持有各 Tab 根节点;绑定目录读取和变化流,转发展开、折叠、刷新及自动刷新开关,不新增 `FilesController` |
| `filesFace`、`FilesInjected` | [Files face](../../../../packages/client/ui-sidebar-files/src/client/face.ts) | 继续作为已有业务入口,在导航栏绘制分栏目录树期间直接持有各分栏的根节点([按分栏保存状态](../architecture/2026-10-20-workspace-tree-state-per-pane.zh.md));绑定目录读取和变化流,转发展开、折叠、刷新及自动刷新开关,不新增 `FilesController` |
| 包内 `DirectoryNode` | [directory-node.ts](../../../../packages/client/ui-sidebar-files/src/client/directory-node.ts) | 表示一个已打开的目录,拥有本目录变化流、读取状态和已打开子节点;负责局部刷新、展开、递归关闭,以及向子节点传递自动刷新状态;`setExpanded` 按最新展开偏好更新待恢复节点 |
| `createFilesStore`、`FilesTabState`、`LevelState` | [Files store](../../../../packages/client/ui-sidebar-files/src/client/store.ts) | 保留展开、滚动和目录显示数据;区分首次加载与已有内容上的刷新,避免每次后台重读都把子树卸载;不保存 watcher 或 AbortController |
| `FilesBody`、`Level`、`Entry` | [FilesBody.tsx](../../../../packages/client/ui-sidebar-files/src/client/FilesBody.tsx) | 将展开、折叠、刷新和面板卸载交给注入回调;按节点展示结果渲染,不扫描整棵树生成监听集合,展示仍只读已有框架钩子与存储 |
| `createFilesStore`、`FilesPaneState`、`FilesTreeState`、`LevelState` | [Files store](../../../../packages/client/ui-sidebar-files/src/client/store.ts) | 保留展开和目录显示数据;区分首次加载与已有内容上的刷新,避免每次后台重读都把子树卸载;不保存 watcher 或 AbortController |
| `FileNavigator` | [FileNavigator.tsx](../../../../packages/client/ui-sidebar-files/src/client/FileNavigator.tsx)、[workspace-tree.ts](../../../../packages/client/ui-sidebar-files/src/client/workspace-tree.ts) | 通过框架钩子读取各分栏状态;将已列出的层级转换为条目与目录状态;将展开、折叠和绘制生命周期交给注入的 Files face,由它负责列出目录、刷新与监听 |
| `FileTree` | [FileTree.tsx](../../../../packages/client/ui-sidebar-files/src/client/FileTree.tsx) | 根据属性绘制条目、目录状态与展开状态,通过 `onToggle` 和 `onOpen` 报告行操作。root 作用域的 `sidebar.files.tree` Factory 通过框架席位读取本地化文案与局部 `accessory` 组件,不持有目录列表或监听 |
| Files 注册入口 | [Files client/index.ts](../../../../packages/client/ui-sidebar-files/src/client/index.ts) | 给现有 `filesFace` 增加目录变化流回调;异步副作用留在注入实现,不引入另一个功能插件的运行时导出 |
## 监听接口与事件内容
@@ -176,13 +177,14 @@ Document Preview 和 Files 各自保留原 reload 按钮。独立自动刷新开
```text
Files.open
→ FilesBody → Session.cwd + Tab
→ filesFace.start → DirectoryNode.open
→ FileNavigator → Session.cwd + pane
→ filesFace.hold → DirectoryNode.open
→ changes(sessionId, path)
→ Host.watch(depth: 0) → ready
→ DirectoryNode → list(sessionId, path)
→ createFilesStore.levels[path]
→ Level / Entry
→ createFilesStore.byPane[paneId].tree.levels[path]
→ FileNavigator → workspace-tree.ts: workspaceEntries / workspaceDirectories
→ renderFactorySlot('sidebar.files.tree', input) → Level / Entry
Entry.expand
→ filesFace.toggle
@@ -204,7 +206,7 @@ Process → create / remove / rename
## 目录节点树与生命周期
Files 的运行时对象本身就是一棵按需打开的目录树,不先建立整棵 Workspace 树,也不另算一个扁平的 watcher 集合。现有 `filesFace` 持有各 Tab 根节点,读取、监听和释放逐层交给 `DirectoryNode`,不另抽控制器类。
Files 的运行时对象本身就是一棵按需打开的目录树,不先建立整棵 Workspace 树,也不另算一个扁平的 watcher 集合。现有 `filesFace` 持有各分栏的根节点,读取、监听和释放逐层交给 `DirectoryNode`,不另抽控制器类。
| 节点职责 | 具体行为 |
|---|---|
@@ -239,14 +241,14 @@ workspace/ watch
| 首次打开 | 打开文件 Resource 监听并读取正文 | 打开根节点,由根节点建立监听并读取列表 |
| 展开子目录 | 无影响 | 父节点打开对应子节点;子节点监听并读取直接子项,按偏好逐层恢复仍存在的后代 |
| 折叠子目录 | 已打开的文件预览继续监听 | 释放该目录及其当前不可见后代的监听;可保留展开偏好和显示缓存 |
| 切走 Tab 或面板卸载 | Tab pin 继续持有文件元数据流;正文组件不在时不主动重读,切回来按待处理 Resource 变化与开关状态补刷新 | 此版沿用 Tab 生命周期,保留已展开目录节点和监听;不另外引入面板显隐生命周期 |
| 切走 Tab 或隐藏目录树 | Tab pin 继续持有文件元数据流;正文组件不在时不主动重读,切回来按待处理 Resource 变化与开关状态补刷新 | 在分栏的文件 tab 之间切换时保留已展开目录节点和监听,因为下一个 tab 在同一次提交中绘制目录树;隐藏目录树或显示不带目录树的 tab 时关闭它们,存储保留展开状态与已显示的层级,下一次绘制时就地重新列出 |
| 手动刷新 | 重用当前预览 reload,不重建整套 Resource | 从根节点递归刷新已打开子节点,不进入折叠目录,也不重建全部 watcher |
| 关闭最后一个持有者 | Resource abort,文件流结束,Host 等待 watcher 关闭 | Tab 关闭时终止全部目录流、取消读取并删除 Tab 状态 |
| 关闭最后一个持有者 | Resource abort,文件流结束,Host 等待 watcher 关闭 | 分栏中没有挂载的导航栏、也没有最近一次在那里绘制导航栏的打开 tab 时,终止全部目录流、取消读取并删除该分栏的状态 |
| 连接恢复 | 新流 ready 后重新 stat,即使断线期间没有可回放事件也能发现变化 | 新流 ready 后重新 list 所有仍需观察的目录 |
Files 监听跟随 Tab 生命周期;折叠关闭对应子树,关闭 Tab 则释放根节点与整棵活动树。暂时隐藏面板不额外拆除和重建节点,这使改动集中在现有入口和目录对象。存储保留展开偏好,节点只在重新展开时用这份偏好逐层恢复,不维护第二份全局展开集合。
Files 监听跟随各分栏已绘制的目录树;折叠关闭对应子树,分栏最后一次绘制结束时释放根节点与整棵活动树,没有打开的 tab 最近一次在该分栏绘制目录树时,还会删除其状态。存储保留展开偏好与已显示的层级,节点只在重新展开时用这份偏好逐层恢复,不维护第二份全局展开集合。
同一个完整文件 Resource 地址的共享继续由 `ResourceRegistry` 完成。目录节点的父子所有权保证一个 Tab 内同一分支不会重复打开;第一版不增加跨 Session、跨窗口或路径别名的全局 watcher 去重系统。目录下的普通文件项不各自订阅文件 watch,只有真正打开为预览 Resource 的文件才取得独立文件监听。
同一个完整文件 Resource 地址的共享继续由 `ResourceRegistry` 完成。目录节点的父子所有权保证一个分栏内同一分支不会重复打开;第一版不增加跨 Session、跨窗口或路径别名的全局 watcher 去重系统。目录下的普通文件项不各自订阅文件 watch,只有真正打开为预览 Resource 的文件才取得独立文件监听。
## 用户可见动线
@@ -281,8 +283,8 @@ Files 监听跟随 Tab 生命周期;折叠关闭对应子树,关闭 Tab 则
- 事件表示“目标可能变化”,不是一次用户操作的精确回放。Chokidar 的重复通知和连续写入可以合并;文件按版本去重,目录按待刷新状态合并。
- 同一目录最多有一次有效 list 在途;在途或读取收尾期间再次失效,只记录需要补读,随后读取最新状态,不累计任意长度的刷新任务队列。
- 文件自动刷新复用读取代次和 renderer revision。连续通知不能让旧请求覆盖新内容,也不能因同一已处理版本而无限 reload。
- 目录后台刷新保留当前列表,不另存没有显示用途的 `refreshing` 标记;只有没有可显示列表时才进入 `loading`,避免子树闪烁和监听反复重建。
- 目录折叠、删除或 Tab 关闭后,已取消读取的晚到结果不得重新创建状态或恢复监听。即使生成器停在已产出的帧上,取消也会关闭 Host watcher;流与插件拆除等待关闭完成。
- 目录后台刷新保留当前列表并标记 `refreshing`;显示不受该标记影响,定位文件据此等待目录重新列出;只有没有可显示列表时才进入 `loading`,避免子树闪烁和监听反复重建。
- 目录折叠、删除、绘制结束或分栏状态被删除后,已取消读取的晚到结果不得重新创建状态或恢复监听。即使生成器停在已产出的帧上,取消也会关闭 Host watcher;流与插件拆除等待关闭完成。
- 父目录保持存在时,文件短暂消失不结束监听;正常文件变化与监听自身失败分别处理。同路径文件监听覆盖原子保存与删除重建。
- 原有文件读取并非事务快照,stat 与正文读取之间仍可能发生写入;后续通知触发刷新,自动刷新不保证每次读取都获得原子快照。
@@ -6,14 +6,14 @@
en: 8be4b1d210d5d8bf
zh: e9124b48467818b3
/agent-note-archive-admission-reads-the-stored-tasks/problem:
en: 093de39b40f7cc97
zh: 50c712bde174bc96
en: 4e5bdccf5388d0e5
zh: 29e68a698f1fa746
/agent-note-archive-admission-reads-the-stored-tasks/decision:
en: afbf818442c0794a
zh: 4749e63d9757bbbb
en: fa45f421aab1315c
zh: d8982ea5833d3770
/agent-note-archive-admission-reads-the-stored-tasks/alternatives-considered:
en: 099360f2c97a50ea
zh: eac4746c4602f152
en: b38b58e4d91b66ac
zh: f9c7253ffa94d76c
/agent-note-archive-admission-reads-the-stored-tasks/consequences:
en: cb2883b34c2c73fa
zh: 9bb1489c9711cf99
en: b034eb6ea31341b9
zh: f78029ff55addc4e
@@ -8,20 +8,20 @@ English | [中文](2026-09-22-archive-admission-reads-stored-tasks.zh.md)
Archive admission asks every provider what still runs for a Session before the archive is written, and a stop-archive then asks those providers to end it ([archiving a Session with running work](2026-09-21-archive-stops-running-session-work.md)). The Schedule provider answered from its owned runtime's fold of the live Session log, so only a Session with a live Agent reported the `schedule` family, and the stop deleted through the management `delete` path.
Host tasks are stored in the Schedule domain document and outlive their Session's Agent ([the storage decision](../architecture/2026-09-16-host-schedule-storage.md)), so that fold no longer exists: `ScheduleRuntime.activeRecords()` is gone, and the stored task table is the only place a due reminder can be seen. A cold Session whose stored rows were still armed therefore reported nothing, archived without the confirmation dialog the running case asks for, and nobody was told which reminder the Host would keep.
Host tasks are stored in the Schedule domain and outlive their Session's Agent ([the storage decision](../architecture/2026-09-16-host-schedule-storage.md)), so that fold no longer exists: `ScheduleRuntime.activeRecords()` is gone, and the stored task table is the only place a due reminder can be seen. A cold Session whose stored rows were still armed therefore reported nothing, archived without the confirmation dialog the running case asks for, and nobody was told which reminder the Host would keep.
## Decision
The Schedule provider answers archive admission from the stored Host task rows, and a stop deletes them. `workspace/session-activity` reads `list({ sessionId })` — the stored rows whose binding is that Session and whose status is active — reports them as the `schedule` family, one item per task with its stored id and title, and prepends that family to `next()` so every other provider keeps its entries. `workspace/session-stop` removes those rows directly inside one slot of the same serialized queue the tools use, so a stop is ordered behind a create whose write is still in flight and cannot miss the row that create is about to commit; it attempts every row, because a row left armed would still fire, and it notifies observers for the rows that landed before the first failure reaches the caller. Session liveness is never consulted: an idle or cold Session whose stored rows are armed refuses the archive, and the confirmation dialog names exactly those reminders. Both listeners are registered in one effect named `schedule.archiveAdmission()`, so unloading the plugin withdraws them together.
The Schedule provider answers archive admission from the stored Host task rows, and a stop deletes them. `workspace/session-activity` reads the stored tasks whose status is active and whose `session` or reserved `new_once` target has the matching Session id, reports them as the `schedule` family, one item per task with its stored id and title, and prepends that family to `next()` so every other provider keeps its entries. `workspace/session-stop` removes those rows in one `deleteMany` batch inside one slot of the same serialized queue the tools use, so a stop is ordered behind a create whose write is still in flight and cannot miss the row that create is about to commit. A successful nonempty batch announces `schedule/changed`, re-drives the timer once, and queues deletion notices for other loaded involved Agents. Session liveness is never consulted: an idle or cold Session whose stored rows are armed refuses the archive, and the confirmation dialog names exactly those reminders. Both listeners are registered in one effect named `schedule.archiveAdmission()`, so unloading the plugin withdraws them together.
## Alternatives considered
**Report the `schedule` family from live Sessions only.** The stored tasks are authoritative and outlive their Session's Agent, so consulting liveness would let a cold Session with armed rows archive silently, and its due row then dispatches into a turn the gate ends as `blocked`, consuming the occurrence without a model step. The admission answer costs one table read either way.
**Report the `schedule` family from live Sessions only.** The stored tasks are authoritative and outlive their Session's Agent, so consulting liveness would let a cold Session with armed rows archive silently; its due delivery then rejects the archived destination. The admission answer costs one table read either way.
**Delete each row through the public management `delete` path.** Re-entering the serialized queue from inside the slot that already holds it deadlocks, so the stop removes the rows itself: the same durable change, with one notification and one timer re-drive per stop instead of one per row.
**Delete each row through the `delete` action of public `edit`.** Re-entering the serialized queue from inside the slot that already holds it deadlocks, so the stop removes the rows itself: the same durable change, with one `schedule/changed` notification and one timer re-drive per stop instead of one per row.
**Keep a runtime-side mirror of the Session's active tasks.** A mirror duplicates the authoritative document, drifts after a restart, and disappears with the Agent — the exact case admission must still answer for.
**Keep a runtime-side mirror of the Session's active tasks.** A mirror duplicates the authoritative store, drifts after a restart, and disappears with the Agent — the exact case admission must still answer for.
## Consequences
Admission costs one stored-table read, and a Session with no live Agent can refuse the archive: a Session that looks quiet may now ask for confirmation because its stored reminders are armed. A stop deletes rows one at a time — the domain table offers no batch delete — so a failure partway leaves the earlier deletes committed; observers hear about those, every row was attempted, and the first failure still reaches the caller. One residue follows. A crash between the archive write and the stop leaves stored rows armed in an archived Session: unarchiving shows them again, and when such a row's target passes the Schedule runtime selects it on its own timer and resolves the Session's Agent itself — that resolution is ungated, and only `agent/pre-step` refuses the model step — so a one-shot dispatches a follow-up into a turn the gate ends as `blocked` and that occurrence is consumed without a model step. The seam itself is unchanged: the workspace package still knows no Schedule vocabulary, and this provider owns only reminders.
Admission costs one stored-table read, and a Session with no live Agent can refuse the archive: a Session that looks quiet may now ask for confirmation because its stored reminders are armed. A stop uses one domain `deleteMany` batch. A normal write failure preserves every row; an `unknown-state` failure may have removed rows and quarantines the domain until it is reopened. Either failure announces `schedule/changed` so observers reread and then reaches the caller. A crash between the archive write and the stop can leave stored rows armed in an archived Session; delivery rejects with `schedule/target-archived` before enqueue, without writing a receipt or consuming the occurrence. The seam itself is unchanged: the workspace package still knows no Schedule vocabulary, and this provider owns only reminders.
@@ -8,20 +8,20 @@
归档准入在写入归档前询问每个提供方:该 Session 还有什么在跑;随后「停止并归档」再要求它们结束这些工作([归档仍有工作在跑的 Session](2026-09-21-archive-stops-running-session-work.zh.md))。Schedule 提供方原先回答的是其归属 runtime 对活会话日志的 fold,因此只有带活 Agent 的 Session 才报告 `schedule` 族,停止也走管理 `delete` 路径。
宿主任务存储在 Schedule 领域文档中,且比其 Session 的 Agent 活得更久([存储决策](../architecture/2026-09-16-host-schedule-storage.zh.md)),因此那个 fold 已不存在:`ScheduleRuntime.activeRecords()` 已经移除,已存储的任务表是到期提醒唯一能被看见的地方。存储行仍被武装的冷 Session 因此什么也不报告,归档时不会弹出运行态才会弹出的确认对话框,也没有人被告知宿主会继续保留哪条提醒。
宿主任务存储在 Schedule 领域中,且比其 Session 的 Agent 活得更久([存储决策](../architecture/2026-09-16-host-schedule-storage.zh.md)),因此那个 fold 已不存在:`ScheduleRuntime.activeRecords()` 已经移除,已存储的任务表是到期提醒唯一能被看见的地方。存储行仍被武装的冷 Session 因此什么也不报告,归档时不会弹出运行态才会弹出的确认对话框,也没有人被告知宿主会继续保留哪条提醒。
## 决策
Schedule 提供方从已存储的宿主任务行回答归档准入,并由停止删除这些行。`workspace/session-activity` 读取 `list({ sessionId })`——绑定到该 Session 且状态为活动的已存储行——把它们作为 `schedule` 族报告,每条任务一项、携带其已存储 id 与 title,并把该族前插到 `next()` 的结果之前,使其他提供方保留各自条目。`workspace/session-stop` 在与工具相同的串行队列的一个槽位里直接删除这些行,因此停止会排在写入尚未完成的创建之后,不会漏掉那个创建即将提交的行;它会尝试每一行,因为留下的行仍会触发;对已经落地的行先通知观察者,再把首个失败交给调用方。是否存活从不参与判断:存储行仍被武装的空闲或冷 Session 会拒绝归档,确认对话框会准确列出这些提醒。两个监听器注册在同一个名为 `schedule.archiveAdmission()` 的 effect 中,卸载插件即一并撤回。
Schedule 提供方从已存储的宿主任务行回答归档准入,并由停止删除这些行。`workspace/session-activity` 读取状态为活动且 `session` 或预留的 `new_once` 目标的 `sessionId` 与该 Session 匹配的已存储任务,把它们作为 `schedule` 族报告,每条任务一项、携带其已存储 id 与 title,并把该族前插到 `next()` 的结果之前,使其他提供方保留各自条目。`workspace/session-stop` 在与工具相同的串行队列的一个槽位里通过一次 `deleteMany` 批量写入删除这些行,因此停止会排在写入尚未完成的创建之后,不会漏掉那个创建即将提交的行。非空批量写入成功后发出 `schedule/changed`,重算计时器一次,并向其他已加载的相关 Agent 排入删除通知。是否存活从不参与判断:存储行仍被武装的空闲或冷 Session 会拒绝归档,确认对话框会准确列出这些提醒。两个监听器注册在同一个名为 `schedule.archiveAdmission()` 的 effect 中,卸载插件即一并撤回。
## 已考虑的备选
**只由活着的 Session 报告 `schedule` 族。** 已存储的任务才是权威,且比其 Session 的 Agent 活得更久,因此以存活为条件会让存储行被武装的冷 Session 静默归档,其到期行随后投递进一个被门禁以 `blocked` 收口的回合,在没有模型步的情况下消耗掉这次触发。两种做法在准入上都只需一次读表。
**只由活着的 Session 报告 `schedule` 族。** 已存储的任务才是权威,且比其 Session 的 Agent 活得更久,因此以存活为条件会让存储行被武装的冷 Session 静默归档;其到期投递随后因目标已归档而被拒绝。两种做法在准入上都只需一次读表。
**每行都走公开的管理 `delete` 路径删除。** 在已经持有该槽位的串行队列内部再次进入队列会自锁,因此停止自己删行:同样的持久化变更,每次停止一次通知、一次计时器重算,而不是每行各一次。
**每行都通过公开 `edit` 的 `delete` 操作删除。** 在已经持有该槽位的串行队列内部再次进入队列会自锁,因此停止自己删行:同样的持久化变更,每次停止一次 `schedule/changed` 通知、一次计时器重算,而不是每行各一次。
**在 runtime 侧保留该 Session 活动任务的镜像。** 镜像会重复权威文档、在重启后漂移、并随 Agent 一起消失——而这正是准入必须仍能回答的情形。
**在 runtime 侧保留该 Session 活动任务的镜像。** 镜像会重复权威存储、在重启后漂移、并随 Agent 一起消失——而这正是准入必须仍能回答的情形。
## 后果
准入的代价是一次读已存储的表,而没有活 Agent 的 Session 也能拒绝归档:看起来安静的 Session 现在可能因为其已存储提醒仍被武装而要求确认。停止逐行删除——领域表不提供批量删除——因此删到一半失败时,先前删除已提交;观察者会被告知这些,每一行都已被尝试,首个失败仍交给调用方。由此剩下一处残余:在归档写入与停止之间崩溃,会在已归档的 Session 里留下仍被武装的已存储行;取消归档时它们再次出现;当这类行的目标时刻过去,Schedule runtime 会按自己的定时器选中它并自行 resolve 该 Session 的 Agent——这一步没有门禁,只有 `agent/pre-step` 拒绝模型步——一次性提醒于是把 follow-up 投递进一个被门禁以 `blocked` 收口的回合,该次触发在没有模型步的情况下被消耗。接缝本身未变:workspace 包仍然不认识 Schedule 词汇,而这个提供方只拥有提醒。
准入的代价是一次读已存储的表,而没有活 Agent 的 Session 也能拒绝归档:看起来安静的 Session 现在可能因为其已存储提醒仍被武装而要求确认。停止使用一次领域 `deleteMany` 批量写入。正常写入失败保留全部行;`unknown-state` 失败可能已移除行,并隔离领域直到重新打开。两种失败均发出 `schedule/changed`,让观察方重读,再交给调用方。在归档写入与停止之间崩溃,仍可能在已归档的 Session 中留下仍被武装的已存储行;投递在入队前以 `schedule/target-archived` 拒绝,不写入回执,也不消耗该次发生时点。接缝本身未变:workspace 包仍然不认识 Schedule 词汇,而这个提供方只拥有提醒。
@@ -0,0 +1,25 @@
# Bilingual-pair consistency record for 2026-09-28-apply-patch-file-editing.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-09-28-apply-patch-file-editing.md
/agent-note-apply-patch-file-editing:
en: 2ff887cb8deab0eb
zh: b503b00d8690955c
/agent-note-apply-patch-file-editing/problem:
en: de9b76d89795ccec
zh: 588d45b7d9ca9582
/agent-note-apply-patch-file-editing/decision:
en: 96c7c9c4d2a6800d
zh: 0618c4eb26378f98
/agent-note-apply-patch-file-editing/alternatives-considered:
en: ba041bf84ae114a0
zh: 314c4a01afeaf37e
/agent-note-apply-patch-file-editing/consequences:
en: 5b9a417d461eafb6
zh: b5adcaf93e5dcc4a
/agent-note-apply-patch-file-editing/testing:
en: 82ae0a96fbae53bc
zh: 9a8194bdb134ae8c
/agent-note-apply-patch-file-editing/deferred:
en: b783059f9706a718
zh: 84d9dc6ea5f01bca
@@ -0,0 +1,47 @@
# Agent Note: Apply patch file editing
Status: implemented
English | [中文](2026-09-28-apply-patch-file-editing.zh.md)
## Problem
A model editing several files or separated regions needs multiple literal-edit calls or a shell script. Shell and Python edits do not expose filesystem mutation intents, so a working directory without Git cannot reliably present those edits in the turn Review tab. A patch tool expresses related edits in one call while retaining guarded filesystem operations. #5121 asks for the capability and its effectiveness evaluation; #4556 supplies the broader motivation for efficient file editing.
## Decision
`apply_patch` accepts one Codex-style patch for add, update, delete, and move operations, including multiple files and hunks. The pure [dsh-fs-patch library](../../../../packages/fs/fs-patch/README.md) follows Codex `rust-v0.158.0` parsing, sequential matching, whitespace tolerance, and `NormalizeToLf` reconstruction; the matcher receives LF text only, so Codex `PreserveLineEndings` is not implemented.
The [filesystem service](../../../../packages/fs/fs/README.md) exposes `patchText`, `deleteFile`, and `moveFile`; local, sandboxed, and SSH providers implement them. `fs/delete-intent` requires the same present observation as `fs/edit-intent`, while move destinations use `fs/write-intent`. Version guards and sandbox enforcement remain with the provider. A move publishes its destination before deleting its source, and `sourceDeleted` distinguishes a completed move from a published destination whose source could not be removed.
The [tool executor](../../../../packages/fs/tool-fs/README.md) resolves paths and simulates expected state during whole-patch preflight, including repeated paths and moves, without writing files; a refused preflight commits nothing. Commit reobtains observation guards for each operation and stops at the first failure or cancellation without rollback. After an I/O or cancellation failure, a `stat` comparison checks whether every affected target retains its prior version; changed state or a failed comparison produces `unknown`, which requires rereading before retry. Reports retain completed, failed, unknown, and skipped operations, including a partially published move.
Commit reports return `isError: false` so completed diff metadata survives a stopped patch; their operation statuses and stopped flag expose the failure. Syntax and preflight rejection produce tool errors. Successful move summaries use `M <destination>`. Applied diff paths use canonical absolute `processPath` for client navigation, while operation records retain display paths and unresolved paths keep their patch spelling.
[Review capture](../../../../packages/deliverables/workspace-changes/README.md) uses filesystem intent listeners, not argument parsing. `tools/pre-execute` associates the execution with its turn recorder; prepended write, edit, and delete listeners first await the policy decision, then await capture before provider mutation. Moves capture both endpoints. Each turn retains its first baseline and compares actual final bytes, so repeated edits yield one net diff and reverted changes disappear. Existing size, count, time, location, and Session-lifetime limits remain.
`tool-fs.applyPatch` defaults to `false`, so every shipped composition keeps the model request it had before the tool existed; the `tool-fs` rows that enable `edit` (`dsh-base` and the Web `standard`, `ptc`, and `cordis` presets) state `applyPatch: false`, and a deployment turns the tool on by changing that one line, or by a profile patch on the `tool-fs` id where no preset owns the row. The tool consults the `fs/*` intent waterfalls like `write` and `edit`, so the mounted observation policy requires a prior read and rejects stale versions for every patch operation. The schema names its argument `input` as the Codex tool does: across 2,226 recorded DS-Bench and DeepSWE rollouts, 14% of `apply_patch` calls arrived with that key and were rejected while the argument was named `patch`. The tool registers its schema, guidance, native/PTC execution, and tool presentation through plugin effects; the agent loop is unchanged.
## Alternatives considered
**Keep using shell or Python for patches.** This leaves non-Git changes without filesystem intent capture and does not provide the requested model-facing editing tool.
**Reuse Codex markers with an independently strict matcher.** This reduces initial implementation work but makes familiar patches fail differently. A pinned Codex parser and matcher make deviations reviewable; Harness policies stay explicit.
**Make the whole patch transactional.** Cross-file rollback adds recovery state and can overwrite concurrent external edits. Preflight and ordered commits reject known failures early and expose partial results without promising rollback.
**Expand Review while adding the tool.** Rename presentation, persistent storage, SSH capture, and capture-failure policy are independent product decisions; existing whole-file capture and rendering cover this integration.
**Register the tool by default wherever `write` and `edit` are both enabled.** This would add a schema and a guidance section to every default model request and change every recorded request expectation before the tool's effect on ordinary sessions is measured; the explicit switch keeps the baseline composition unchanged and lets comparison runs opt in.
## Consequences
One call can express related edits. Default model requests are unchanged; a composition that enables the switch includes another tool schema and its guidance, so its recorded request expectations differ from the baseline. Preflight cannot prevent a later conflict, cancellation, or storage failure; callers inspect operation statuses before retrying. Permissive upstream matching remains pinned and tested rather than tightened. Provider implementations and external subclasses must support three additional operations, and partial moves require handling both endpoints.
## Testing
Parser and matcher fixtures cover the pinned syntax, whitespace, repeated contexts, and EOF behavior. Provider and executor tests cover observation, version and sandbox refusals, repeated paths, partial moves, cancellation, and uncertain outcomes. The real-tool Review matrix runs with no repository and with Git unavailable, checking all operation kinds, first-to-last baselines, rejected edits, partial publication, reverted changes, capture ordering, malformed syntax, and path aliases. Real model Session recordings cover successful updates, read-policy rejection and retry, and partial execution; deterministic cancellation stays in executor tests.
## Deferred
A controlled editing-task evaluation comparing final-file correctness, task success, tokens, tool calls, retries, latency, and Review coverage against `edit` on identical initial states. SSH Review, closing-prose file references for `apply_patch`, and Codex `PreserveLineEndings`.
@@ -0,0 +1,47 @@
# Agent Note: apply_patch 文件编辑
Status: implemented
[English](2026-09-28-apply-patch-file-editing.md) | 中文
## 问题
模型编辑多个文件或分离区域时,需要多次字面量编辑调用或 shell 脚本。shell 和 Python 编辑不发出文件系统修改 intent,因此没有 Git 的工作目录无法在轮次 Review tab 中可靠呈现这些修改。补丁工具用一次调用表达相关编辑,同时保留受保护的文件系统操作。#5121 要求实现能力并评测效果;#4556 提供高效文件编辑的更广泛动机。
## 决策
`apply_patch` 接收一份 Codex 风格补丁,支持新增、更新、删除和移动,以及多个文件和 hunk。[dsh-fs-patch 纯库](../../../../packages/fs/fs-patch/README.zh.md)遵循 Codex `rust-v0.158.0` 的解析、顺序匹配、空白容忍和 `NormalizeToLf` 重建。匹配器只接收 LF 文本,因此不实现 Codex `PreserveLineEndings`。
[文件系统服务](../../../../packages/fs/fs/README.zh.md)提供 `patchText`、`deleteFile` 和 `moveFile`;本地、沙箱和 SSH 提供方均实现它们。`fs/delete-intent` 与 `fs/edit-intent` 要求相同的存在观察,移动目标使用 `fs/write-intent`。版本防护和沙箱约束仍由提供方负责。移动先发布目标,再删除源;`sourceDeleted` 区分已完成的移动与目标已发布但源未能删除的情况。
[工具执行器](../../../../packages/fs/tool-fs/README.zh.md)在整份补丁预检时解析路径并模拟预期状态,包括重复路径和移动,不写入文件;预检拒绝时没有提交。提交时为每条操作重新获取观察防护,在首次失败或取消时停止,不回滚。I/O 或取消失败后,`stat` 比较检查所有受影响目标是否仍保持先前版本;状态变化或比较失败会产生 `unknown`,要求重试前重新读取。报告保留已完成、失败、未知和跳过的操作,包括部分发布的移动。
提交报告返回 `isError: false`,让已完成的 diff 元数据在补丁中止后仍被保留;操作状态和 stopped 标记暴露失败。语法和预检拒绝产生工具错误。成功移动的摘要使用 `M <destination>`。已应用 diff 的路径采用规范绝对 `processPath`,供客户端导航使用;操作记录保留显示路径,未解析的路径保留补丁原始写法。
[Review 采集](../../../../packages/deliverables/workspace-changes/README.zh.md)使用文件系统 intent 监听器,不解析参数。`tools/pre-execute` 将执行关联到轮次记录器;前置的 write、edit 和 delete 监听器先等待策略决策,再等待捕获完成,然后提供方才修改文件。移动捕获两端。每轮保留首次基线,比较实际最终字节,因此重复编辑形成一份净 diff,还原的变化不再显示。现有大小、数量、时间、位置和 Session 生命周期限制保持适用。
`tool-fs.applyPatch` 默认为 `false`,因此所有随发行版交付的组合保持该工具出现之前的模型请求;启用 `edit` 的 `tool-fs` 行(`dsh-base` 以及 Web 的 `standard`、`ptc`、`cordis` preset)显式写出 `applyPatch: false`,部署只需改这一行即可开启,或在没有 preset 拥有该行时通过针对 `tool-fs` id 的 profile patch 开启。该工具像 `write` 和 `edit` 一样咨询 `fs/*` intent waterfall,因此已挂载的观察策略对每个补丁操作要求先读并拒绝过期版本。schema 沿用 Codex 的参数名 `input`:在 2,226 条 DS-Bench 与 DeepSWE 录制轨迹中,14% 的 `apply_patch` 调用带着这个键发出,而参数名为 `patch` 时它们都被拒绝。工具通过插件 effect 注册 schema、指导文本、native/PTC 执行与调用展示;不修改 agent loop(智能体循环)。
## 考虑过的替代方案
**继续使用 shell 或 Python 打补丁。** 这使非 Git 修改缺少文件系统 intent 采集,也不能提供所需的模型文件编辑工具。
**复用 Codex 标记但采用独立的严格匹配器。** 这能减少初期实现工作,但会让熟悉的补丁以不同方式失败。固定 Codex 解析器和匹配器使偏差可审查;Harness 策略继续显式存在。
**将整份补丁做成事务。** 跨文件回滚增加恢复状态,还可能覆盖并发外部修改。预检和顺序提交可以提早拒绝已知失败,并公开部分结果,而不承诺回滚。
**加入工具时同时扩展 Review。** 重命名展示、持久存储、SSH 采集和捕获失败策略是独立产品决策;既有整文件采集和展示覆盖本次接入。
**在同时启用 `write` 与 `edit` 的地方默认注册该工具。** 这会在尚未衡量该工具对普通会话的影响之前,给每个默认模型请求增加一个 schema 和一段指导文本,并改变所有录制请求的预期;显式开关保持基线组合不变,让对比评测自行选择开启。
## 后果
一次调用可以表达相关编辑。默认模型请求保持不变;开启该开关的组合会包含额外的工具 schema 及其指导文本,因此其录制请求的预期与基线不同。预检不能阻止之后的冲突、取消或存储失败;调用方在重试前检查操作状态。上游宽松匹配保持固定版本并受到测试约束,不会被收紧。提供方实现和外部子类必须支持三个新增操作,部分移动要求处理两端状态。
## 测试
解析器和匹配器 fixture 覆盖固定版本的语法、空白、重复上下文与 EOF 行为。提供方和执行器测试覆盖观察、版本和沙箱拒绝、重复路径、部分移动、取消和未知结果。真实工具 Review 矩阵分别在无仓库和 Git 不可用环境运行,检查所有操作类型、首末基线、被拒编辑、部分发布、还原变化、采集顺序、无效语法与路径别名。真实模型 Session 录制覆盖成功更新、读取策略拒绝后重试与部分执行;确定性取消保留在执行器测试中。
## 延期工作
受控编辑任务评测:在相同初始状态下与 `edit` 比较最终文件正确性、任务成功率、token、工具调用、重试、延迟和 Review 覆盖。SSH Review、`apply_patch` 的收尾文案文件引用,以及 Codex `PreserveLineEndings`。
@@ -29,6 +29,9 @@
/agent-note-frontend-large-session-performance-budgets/calibration/history-selector-invalidation:
en: 2d2f78f4cf6aad8a
zh: aec6af5f7c66de16
/agent-note-frontend-large-session-performance-budgets/calibration/streaming-assistant-visibility:
en: 5dc3c84b80be0e8e
zh: 4bbd16e1f455ef85
/agent-note-frontend-large-session-performance-budgets/alternatives-considered:
en: 4d2a4a64ccd14507
zh: 8a4aaf4d4abea13d
@@ -102,6 +102,23 @@ These local runs both failed the independent open budget: their open medians wer
Post-GC browser heap was 80.70/80.71 MiB. GNU time reported maximum RSS of 535.78/561.80 MiB for each benchmark command and its children; this is not input-phase memory or an aggregate browser-memory measurement. Moving the composer's selection reveal into an animation frame was rejected: profiling showed the style flush moved to another geometry read, without improving typing. The product fix removes the invalidation source instead.
### Streaming Assistant visibility
Chat retains visibility per Assistant block. Same-kind text and reasoning appends inspect only the incoming delta until the block becomes visible, then reuse that result. This avoids repeated `trim()` calls on accumulated strings without changing whitespace, first-token timing, or visible anchors. Replacements recalculate visibility, retry resets it, and final messages rebuild it. Copying the block array remains proportional to its length; this does not make every Assembler operation constant-time.
The [conversation-fold worker](../../../../benchmarks/conversation-fold/conversation-fold.worker.client.ts) measures a single 256 KiB block split into 4,096 or 16,384 deltas, using ordinary text or reasoning whose first half is whitespace. Five fresh compiled Node children per case reuse the existing benchmark registrations, production Assembler and Chat builder. Timing includes every append, one final flush, and reading every output character. Fixture preparation and GC are excluded; retained heap is the post-GC increment with the Assembler, live entries and published state still reachable.
Local macOS arm64 measurements on Node 26.8.2 give these elapsed medians. The time limits use reference allowances of 12/32 ms and the existing shared scale and headroom; they are not new hosted-runner calibration.
| Workload | Deltas | Repeated accumulated trim | Cached visibility | Time limit |
|---|---:|---:|---:|---:|
| Ordinary text | 4,096 | 42.25 ms | 7.32 ms | 30 ms |
| Half-leading-whitespace reasoning | 4,096 | 252.75 ms | 7.96 ms | 30 ms |
| Ordinary text | 16,384 | 206.71 ms | 23.06 ms | 80 ms |
| Half-leading-whitespace reasoning | 16,384 | 1114.18 ms | 23.08 ms | 80 ms |
All four cases reject accumulated trimming and pass with cached visibility. Retained heap remains approximately 2.8/9.9 MiB for the two fragment counts, below the 20 MiB limit derived from a 16 MiB allowance. Maximum worker RSS across these samples falls from 185.70 to 89.36 MiB; it is a whole-process diagnostic, not aggregate application memory. This endpoint measures local assembly with one final publication, excluding network, browser rendering and Trajectory. Separate browser regressions cover settlement, cancellation, retry, reload, reopening and blank reasoning without asserting a browser speedup.
## Alternatives considered
**Use the Node fold as paint evidence.** Rejected because it never performs DOM mutation, layout, or browser scheduling. The focused reconnect case likewise makes no GUI speed claim.
@@ -102,6 +102,23 @@ Trajectory 激活在动画帧上采样可见搜索框与 `[data-trajectory-scrol
强制 GC 后的浏览器 heap 为 80.70/80.71 MiB。GNU time 为两次基准命令及其子进程报告的最大 RSS 为 535.78/561.80 MiB;这不是输入阶段内存,也不是浏览器总内存测量。曾尝试将输入框的选区显示推迟到动画帧,但分析显示样式刷新转移到另一处几何读取,没有改善键入,因此未采用。产品修复直接移除样式失效的来源。
### 流式 Assistant 可见性
Chat 保存每个 Assistant 块的可见状态。同类型文本和推理追加只检查新增片段,直到该块可见,之后复用结果。这避免对累计字符串重复调用 `trim()`,同时保留空白、首 token 时间及可见锚点。块替换重新计算可见性,重试清空状态,最终消息重建状态。块数组复制仍与其长度成正比,因此并非每次 Assembler 操作都是常数时间。
[conversation-fold worker](../../../../benchmarks/conversation-fold/conversation-fold.worker.client.ts) 测量单个 256 KiB 块,拆成 4,096 或 16,384 个片段,内容为普通文本或前半段为空白的推理。每个用例使用五个全新的已编译 Node 子进程,复用现有基准注册、生产 Assembler 和 Chat builder。计时包含每次追加、一次最终 flush 及逐字符读取输出。夹具准备和 GC 不计时;保留堆内存为 GC 后的增量,此时 Assembler、实时条目和已发布状态仍可达。
macOS arm64、Node 26.8.2 上的本地测量得到以下耗时中位数。时间上限使用 12/32 ms 参考额度及现有共享缩放与余量,不代表新的托管运行器校准。
| 工作负载 | 片段数 | 累计文本重复 trim | 缓存可见性 | 时间上限 |
|---|---:|---:|---:|---:|
| 普通文本 | 4,096 | 42.25 ms | 7.32 ms | 30 ms |
| 前半段为空白的推理 | 4,096 | 252.75 ms | 7.96 ms | 30 ms |
| 普通文本 | 16,384 | 206.71 ms | 23.06 ms | 80 ms |
| 前半段为空白的推理 | 16,384 | 1114.18 ms | 23.08 ms | 80 ms |
四个用例都拒绝累计文本重复 trim,并在缓存可见性后通过。两个片段规模的保留堆内存仍约为 2.8/9.9 MiB,低于 16 MiB 额度经余量计算后的 20 MiB 上限。这些样本中的 worker 最大 RSS 从 185.70 降至 89.36 MiB;它是整个进程的诊断值,不是应用总内存。该终点只测量一次最终发布的本地组装,不包含网络、浏览器渲染和 Trajectory。独立浏览器回归覆盖结算、取消、重试、刷新、重开及空白推理,不据此声称浏览器提速。
## 考虑过的替代方案
**用 Node 折叠作为绘制证据。** 拒绝,因为它不执行 DOM 修改、布局或浏览器调度。聚焦重连用例同样不声称 GUI 提速。
@@ -0,0 +1,43 @@
# Bilingual-pair consistency record for 2026-10-29-event-triggered-automation-tasks.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/proposed/feature/2026-10-29-event-triggered-automation-tasks.md
/agent-note-event-triggered-automation-tasks:
en: fe57a78907eab083
zh: 4ac96eeb365ac012
/agent-note-event-triggered-automation-tasks/problem:
en: 491a791a201d0b2c
zh: 5a98f693ac4b5e77
/agent-note-event-triggered-automation-tasks/proposal:
en: 7906d9f791e0ba02
zh: 3a083d451344f072
/agent-note-event-triggered-automation-tasks/proposal/layers:
en: 8bf2fc8ccb162c59
zh: e993b9ae72f8d9a2
/agent-note-event-triggered-automation-tasks/proposal/sessions:
en: 7ec83684c8c19e31
zh: 27df2725836e5f7b
/agent-note-event-triggered-automation-tasks/proposal/configuration:
en: 21be7e27081aff54
zh: 7973f7f0d064db35
/agent-note-event-triggered-automation-tasks/proposal/mechanisms:
en: 2403ec84b12279ec
zh: 7e245af54dcf4a1a
/agent-note-event-triggered-automation-tasks/proposal/product-scope:
en: c003c908f407ccb2
zh: 6113569a44d52202
/agent-note-event-triggered-automation-tasks/proposal/event-triggers-as-infrastructure:
en: 4c62e16718896e9b
zh: 9c61ea9b6e1f4f22
/agent-note-event-triggered-automation-tasks/proposal/delivery-order:
en: 79cf498bf3566051
zh: 4537f1bd3df527b4
/agent-note-event-triggered-automation-tasks/alternatives-considered:
en: 21df079f7d7c3f4d
zh: 67f4ab221aacf2cf
/agent-note-event-triggered-automation-tasks/acceptance-criteria:
en: 504feb2cc59f4457
zh: c78cd50f2f336562
/agent-note-event-triggered-automation-tasks/risks:
en: 35edb8d5b6a1cfa4
zh: cb8dbc339c6055be
@@ -0,0 +1,153 @@
# Agent Note: Event-triggered automation tasks
Status: proposed
English | [中文](2026-10-29-event-triggered-automation-tasks.zh.md)
## Problem
Automation tasks run only on time rules today. The Host stores each rule, and every due time queues the task's instruction as a follow-up message in the task's original Session ([Host-owned scheduled messages](../../implemented/architecture/2026-09-16-host-schedule-storage.md)); the model creates and edits tasks through preset-scoped tools ([Preset-scoped Schedule tools](../../implemented/architecture/2026-09-24-preset-scoped-schedule-tools.md)). Work that should start when something else changes, such as a pull request's checks failing, a reviewer requesting changes, or a message arriving, cannot be expressed as a task, so users check those sources by hand across Sessions.
Reacting to changes brings two problems that time rules do not have.
- **Cost and noise.** Most observations of a source contain nothing worth a model turn. If every observation reaches the model and silence depends on the model replying with a marker, each poll costs a full turn, and a model that holds a messaging tool reports "nothing new" anyway.
- **Untrusted input.** Event content is written by other people: comments, reviews, messages. A turn started by that content must not edit, push, or send anything before the user has seen it.
## Proposal
An automation task becomes an instruction, a source with parameters, and a Session mode. Time is one source among several, so a scheduled task is an automation task whose source is time. Each observation passes three layers, and only the last one calls a model: a source event passes the trigger's filter and becomes a candidate, the candidate is delivered to a Session where the model judges it, and only a notify call produces a notice for the user. This partially supersedes the two notes linked above: tasks stop being bound to their original Session, and task records stop meaning inbox delivery only.
```mermaid
flowchart TD
Task["Task: instruction, source parameters, Session mode<br/>written by the model, shown read-only"]
Prov["Source providers: plugins, code<br/>time, GitHub; later mail, IM, memory"]
Trig["Event trigger: shared code, state per task<br/>compare with stored state, match parameters, merge"]
Rec[("Run records")]
Src{"Source"}
Exec["Run the instruction in the target Session<br/>with its permissions"]
RO["Read-only turn in the task's own Session<br/>the model judges the candidate"]
Note["Notice: action card, unread mark,<br/>system notification"]
Quiet["No notice"]
Acc["User accepts: the action runs in the Session<br/>that created the task, with its permissions"]
Task --> Trig
Prov -- "source events" --> Trig
Trig -- "each change or failure" --> Rec
Trig -- candidate --> Src
Src -- time --> Exec
Src -- "other sources" --> RO
RO -- notify --> Note
RO -- "no notify call" --> Quiet
Note --> Acc
```
| Layer | Decides | Model call | Output |
|---|---|---|---|
| Source provider | What changed in the source | No | Events |
| Event trigger | Whether the change matters to this task | No | A run record; a candidate or nothing |
| Agent | Whether the user needs to act, and what to propose | Only for delivered candidates | A notice through notify, or nothing |
### Layers
**Source providers** are code, packaged as plugins; they provide event sources and are unrelated to model, SSH, or credential providers. A provider owns one kind of source: it polls or subscribes, reports changes as events with a subject, a one-line summary, detail, and links, and declares the JSON schema of the parameters a task can set. One provider serves every task of its kind. Time is the first provider, and today's schedule rules become its parameters. Any installed plugin can register a provider, including one written in Creator mode; a task can name only a registered provider.
**The event trigger** is shared code, registered per source kind and version; each task holds only its parameters and the source state it last observed. For each observation it compares the new state with the stored one, and an observation without a change only updates the last-checked time. A check that turns from passing to failing is a change, a check that stays failing is not, and a pass followed by a new failure is a change again. For a change, the trigger matches the task's conditions, which are parameter fields such as conclusion is failure, author is the user, or commenter is not a bot; merges changes to the same subject inside the provider's merge window, so one push that fails three checks becomes one event; stores the new state with the task; and either delivers a candidate to the Session or drops the change. Each change and each failure writes a run record, listed in the task's Records tab next to today's delivery records: candidate delivered, filtered with its reason, or failed. Consecutive failures with the same cause share one record with a count. Delivery ends the trigger's work: it does not wait for the turn or read a receipt. One queue per task orders its evaluations.
**The agent** receives the candidate as a message in the target Session, together with the task's instruction in the user's words. What the turn may do depends on the source.
- **Time**: the turn runs the instruction with the Session's permissions, and its reply is the result, as scheduled tasks behave today.
- **Other sources**: the turn gets the read-only tool set described under Mechanisms. It can read files and the source's state, such as check logs and pull request diffs, but has no tool that edits, pushes, or sends. One new tool, **notify** (`automation_notify`), takes a title, a summary, and a proposed action and produces a notice: an [action card](../../../../packages/experimental/action-cards/README.md) with the proposed action in the Session, the Session's unread mark, and a desktop system notification. The model decides whether to call it. A turn without notify produces no notice; there is no end tool, and nothing checks how the turn ended. When the user accepts the card, the Host sends a follow-up to the Session that handles the task, as described under Sessions; the follow-up names the task and the event and quotes the proposed action as the automation's proposal, not as the user's words, and that turn runs with that Session's permissions.
### Sessions
A task delivers to its target Session in one of three modes: a specified Session, a new Session per trigger, or a new Session on the first trigger that later triggers reuse. Time tasks keep today's target, the Session they were created in. Event tasks separate judging from handling. The read-only turn runs in the task's own Session, created on the first trigger and reused afterwards, because it needs the instruction, the event, and the task's earlier decisions rather than the long history of the conversation the task came from. When the model creates a task in a conversation, it writes the facts the judgment needs into the instruction, such as which check is known to be flaky. When the user accepts a card, the proposed action goes to the Session the task was created in, where the code and its history are. The automation page's New action already creates tasks in a new Session, which then handles them; a task enabled from an official template, which a later step adds, continues in its own Session. The user can change the mode on the task.
No task runs while the Host is stopped. On restart, each task compares the current source state with its stored state once and does not replay intermediate changes. Time keeps today's rule: a recurring task runs its latest missed occurrence once.
### Configuration
Configuration has two layers. Provider code decides what can be observed and how; task parameters decide what one task watches. The model writes the parameters from the user's words through the task tools, and the provider's schema validates them. A task carries no scripts or other code, so observing something new means changing or installing a provider plugin. The automation page shows source parameters read-only, and they change through conversation; the time editor stays.
### Mechanisms
- **Event-turn tool set.** Sandbox read-only mode limits only the filesystem, so it cannot stop a push or an outbound request. An event turn is offered a fixed tool set instead of the Session's: file reads and searches, the source provider's read operations, and `automation_notify`. Shell, file writes, web fetch, and MCP tools are absent. The tool set is recorded in the Session log, and a user message queued during the turn starts a normal turn after it ends.
- **Notify card.** The automation package registers an action-card kind, and `automation_notify` creates its card through the action-card service; the tool exists only in event turns, so no skill load precedes it. Accepting runs the kind's handler, which queues the follow-up through the Host, so the handling Session need not be open. A newer card replaces an unanswered older one in the same Session, as the service does today; the older card is in that Session's history, so the newer turn sees it and carries over what is still open. A refused card returns an error to the turn.
- **Unread mark.** The client derives the unread mark from turn completion. A task's own Session is marked as an automation Session, and for such a Session the client shows the mark only for notices, so a turn without notify leaves no mark.
- **Logging.** The delivered candidate, the turn's tool set, and the notify call are Session events, so replay rebuilds the turn; the TypeScript and Python SDK expected outputs and a recorded-session snapshot cover them.
- **Storage.** Source, parameters, Session mode, trigger state, and run records extend the Host task domain in a new record version with an adjacent migration. A version-1 task reads as a time task, is not rewritten until it changes, and gets no invented records. Run records have their own count and age bounds, separate from delivery records.
- **Provider configuration.** Polling intervals and request budgets are validated Config fields of each provider in cordis.yml.
### Product scope
- No new entry point and no page redesign: scheduled and event-triggered tasks share the automation page.
- The task list adds a source-type filter next to the status filter.
- Task details add the source with its parameters, read-only, and the Session mode, editable.
- A task's Records tab also lists filtered and failed evaluations.
- Notifications reuse the Session unread mark and action cards; the desktop app adds a system notification.
### Event triggers as infrastructure
The trigger layer is shared infrastructure for DSH, not a feature of the automation page. A feature that watches something and hands changes to an agent becomes a task on this layer instead of building its own polling, state, records, and notifications.
- **DSH's own state as sources**: a Session turn ending in an error, a background job settling, and, once memory lands, a memory consolidation pass finishing or memory entries changing.
- **Features on those sources**: plugin recommendations, where a workflow the user repeats by hand shows up after consolidation and the agent proposes a plugin on an action card, and task recommendations, where a review of the day's Sessions proposes follow-up work. Each is a template task with a DSH source, an instruction, and the same notify step. The plugin recommendations package, which proposes cards from conversation turns today, can move onto such a source once consolidation lands.
- **What every consumer keeps**: change detection and condition matching in code, run records, Session modes, read-only event turns, and notify as the only way a task reaches the user.
### Delivery order
1. Task–Session decoupling with the three Session modes.
2. The trigger layer with time as its first provider and the task-domain migration; existing scheduled tasks behave as before.
3. The GitHub provider for pull request checks, reviews, and comments; the event-turn tool set and `automation_notify`; action cards leave experimental status or ship with the automation bundle.
4. Mail and IM providers and official templates, then DSH's own sources.
## Alternatives considered
**Judge every observation in a resident Session.** The model reads each poll and replies with a silence marker when nothing changed. It lost because each observation costs a full turn over the Session's context, polls spaced beyond the prefix cache lifetime read that context uncached, and silence depends on the model following an instruction while it holds a messaging tool. Here code drops unchanged and unmatched observations, and only a notify call reaches the user.
**Judge in the Session that created the task.** That conversation already holds the code and its history, so the instruction would need no extra facts. It lost because most candidates produce no notice, and each of them would add a turn over the conversation's whole context, read uncached once the prefix cache has expired, and queue behind or interrupt the user's own work there. Only accepted work goes to that Session.
**Let the agent choose the Session for each event.** The choice could differ from one event to the next, so the user could not predict where a notification appears, and deciding whether the history is needed requires reading it first.
**Condition scripts per task.** A task would carry a script that fetches and decides. It lost because the script runs with the user's credentials without the review a plugin installation gets, and each task would carry its own fetch logic instead of sharing a provider.
**Notify from code when code can decide.** A failed check could notify without a model. It lost because the notification would carry only the raw status. With one path, the agent reads the logs first and the notification states the cause; change-only delivery keeps these turns rare.
**One model call outside any Session.** A single call per event costs less and leaves no Session record. It lost because the call cannot read files or logs before deciding, and acting on its result needs a Session anyway.
**Event turns with the Session's permissions.** Acting directly would save one click. It lost because event content comes from other people, and a read-only turn keeps that text from driving edits, pushes, or messages before the user accepts.
**A read-only sandbox for event turns.** It lost because sandbox read-only mode limits only the filesystem, and a turn in it can still push or send requests.
**An end tool and a check on how the turn ended.** A second tool would record why a turn produced no notice, and the trigger would wait for that outcome. It lost because nothing acts on that reason: delivery ends the trigger's work, and a turn without notify is already silent.
**Parameter forms on the automation page.** Each provider would need its own form, validation, and display. Parameters written by the model and shown read-only cover creation and change through conversation, and the provider schema keeps a generated form possible later.
**A separate notification entry.** An inbox page or tab would separate the notification from the Session that holds its context. The unread mark and the system notification lead to that Session, and the automation page keeps the records.
## Acceptance criteria
- Existing scheduled tasks behave the same after time becomes a provider: the same due times, the same catch-up rule, and the same delivery into the Session.
- A version-1 task loads as a time task without being rewritten and without invented records.
- A GitHub task on a pull request's checks delivers one candidate when a check turns from passing to failing, none while it stays failing, and another after a pass followed by a new failure.
- One push that fails three checks produces one candidate.
- An observation without a change writes no record and starts no turn; a change that fails the conditions writes a filtered record and starts no turn; consecutive failures with the same cause write one record with a count.
- A run record ends at delivery: it records the candidate, not what the turn did.
- An event turn is offered no shell, file-write, web-fetch, or MCP tool, and its tool set appears in the Session log; after the user accepts its card, the next turn runs with the Session's permissions.
- A notify call produces the card, the unread mark, and the desktop system notification together.
- An event turn without a notify call leaves no unread mark and sends no system notification.
- An event task's read-only turns run in the task's own Session, and accepting its card sends the proposed action to the Session the task was created in.
- Each Session mode delivers as defined: a specified Session receives every trigger, a new Session opens per trigger, or one Session opens on the first trigger and is reused.
- Replaying the Session log rebuilds an event turn's candidate, tool set, and notify call.
- After a restart, a task compares the current source state with its stored state once and does not replay intermediate changes.
- The task list filters by source type, task details show source parameters read-only, and the Session mode can be changed.
## Risks
- The read-only turn sees the instruction, the event, and the task's earlier decisions, not the conversation the task came from. Facts the judgment needs from that conversation must be written into the instruction when the task is created; a user who switches the task to its original Session gets the history back at the cost of reading the long context on each delivery.
- A notification appears in the task's own Session, not in the conversation that created the task; accepting its card moves the work to that conversation.
- The agent may notify too often or stay silent when it should not. Accepted and dismissed cards show over-notification, but a missed notice leaves no trace in the run records, which end at delivery.
- Source parameters cannot be edited by hand; every change goes through the model.
- A fix on an event waits for the user to accept the card instead of running unattended.
- A source without a provider plugin cannot be watched.
- Tasks run only while the Host runs: nothing runs while the app is closed or the machine sleeps.
- Event tasks depend on action cards, which are experimental and mounted only by the Personalized recommendations bundle today.
- The read-only tool set limits judgment to what files and the provider's read operations show; for a source whose provider offers no read operations, the agent judges from the event alone.
@@ -0,0 +1,153 @@
# Agent Note: 事件触发的自动化任务
Status: proposed
[English](2026-10-29-event-triggered-automation-tasks.md) | 中文
## 问题
目前自动化任务只能按时间规则运行。Host 保存每条规则,每到一个到期时间,就把任务的指令作为一条后续消息排进任务的原会话([Host 拥有的定时消息](../../implemented/architecture/2026-09-16-host-schedule-storage.zh.md));模型通过按 preset 提供的工具创建和修改任务([按 preset 提供的 Schedule 工具](../../implemented/architecture/2026-09-24-preset-scoped-schedule-tools.zh.md))。有些工作应当在别处发生变化时开始,例如 PR(Pull Request)的检查失败、评审人要求修改、收到一条消息,这些都无法建成任务,用户只能在多个会话之间手动查看这些来源。
响应变化会带来两个时间规则没有的问题。
- **成本和噪音。** 对来源的大多数观察里,没有值得花一个模型轮次处理的内容。如果每次观察都交给模型,并依靠模型回复一个标记来保持安静,每次轮询都要花一个完整轮次;手里有发消息工具的模型仍然会报告“没有新情况”。
- **不可信的输入。** 事件内容由其他人写成:评论、评审、消息。由这类内容启动的轮次,在用户看到之前不能修改、推送或发送任何东西。
## 提案
自动化任务改为由指令、带参数的来源和会话模式组成。时间是多种来源中的一种,因此定时任务就是来源为时间的自动化任务。每次观察依次经过三层,只有最后一层调用模型:来源事件经过触发器过滤成为候选事件(candidate),候选事件投递到会话,由模型在会话中判断,只有调用通知工具才会为用户产生一条通知(notice)。本提案部分取代上面链接的两篇笔记:任务不再绑定原会话,任务记录也不再只表示收件箱投递。
```mermaid
flowchart TD
Task["Task: instruction, source parameters, Session mode<br/>written by the model, shown read-only"]
Prov["Source providers: plugins, code<br/>time, GitHub; later mail, IM, memory"]
Trig["Event trigger: shared code, state per task<br/>compare with stored state, match parameters, merge"]
Rec[("Run records")]
Src{"Source"}
Exec["Run the instruction in the target Session<br/>with its permissions"]
RO["Read-only turn in the task's own Session<br/>the model judges the candidate"]
Note["Notice: action card, unread mark,<br/>system notification"]
Quiet["No notice"]
Acc["User accepts: the action runs in the Session<br/>that created the task, with its permissions"]
Task --> Trig
Prov -- "source events" --> Trig
Trig -- "each change or failure" --> Rec
Trig -- candidate --> Src
Src -- time --> Exec
Src -- "other sources" --> RO
RO -- notify --> Note
RO -- "no notify call" --> Quiet
Note --> Acc
```
| 层 | 判断什么 | 是否调用模型 | 输出 |
|---|---|---|---|
| 来源提供方(source provider) | 来源里发生了什么变化 | 否 | 事件 |
| 事件触发器(event trigger) | 这个变化与本任务是否相关 | 否 | 一条运行记录;一个候选事件,或者没有 |
| agent(智能体) | 用户是否需要处理,以及建议怎么处理 | 只对已投递的候选事件 | 通过通知工具产生通知,或者没有 |
### 分层
**来源提供方**是代码,以插件形式提供;它们提供事件来源,与模型、SSH 或凭据的提供方无关。一个来源提供方负责一类来源:它轮询或订阅来源,把变化报告为事件(包含对象、一行摘要、详细内容和链接),并声明任务可设置参数的 JSON schema。同类的所有任务共用同一个来源提供方。时间是第一个来源提供方,现有的定时规则成为它的参数。任何已安装的插件都可以注册来源提供方,包括在创造模式中写出的插件;任务只能指定已注册的来源提供方。
**事件触发器**是共享的代码,按来源类型和版本注册;每个任务只保存自己的参数和上次观察到的来源状态。每次观察时,它把新状态与保存的状态比较;没有变化的观察只更新最近检查时间。检查从通过变为失败算一次变化,持续失败不算,通过之后再次失败又算一次变化。对一次变化,触发器先匹配任务的条件(参数中的字段,例如结论为失败、作者是用户本人、评论者不是 bot),再在来源提供方的合并窗口内合并同一对象的多次变化(一次推送导致三项检查失败,只算一个事件),然后把新状态和任务一起保存,向会话投递一个候选事件,或者丢弃这次变化。每次变化和每次失败都写一条运行记录,列在任务的运行记录页签中,与现有的投递记录并列:已投递候选事件、已过滤(附原因)或失败。同一原因的连续失败共用一条记录并计数。投递之后触发器的工作就结束了,不等待该轮次,也不读取回执。每个任务用一个队列排定自己的判定顺序。
**agent** 在目标会话中以一条消息收到候选事件,消息附带以用户原话写成的任务指令。轮次能做什么取决于来源。
- **时间**:轮次按会话的权限执行指令,回复就是结果,与现在的定时任务一致。
- **其他来源**:轮次使用“机制”一节所述的只读工具集。它可以读文件和来源的状态,例如检查日志和 PR diff,但没有修改、推送或发送的工具。新增一个工具 **通知**(`automation_notify`),接收标题、摘要和建议的操作,产生一条通知:会话中出现带有建议操作的[操作卡片](../../../../packages/experimental/action-cards/README.zh.md)、会话显示未读标记、桌面端发送系统通知。是否调用由模型决定。没有调用通知的轮次不产生通知;没有结束工具,也不检查轮次如何结束。用户接受卡片后,Host 向处理该任务的会话(见“会话”一节)发送一条后续消息:消息写明任务和事件,并把建议的操作作为自动化提出的建议引用,而不是作为用户的话;该轮次按该会话的权限执行。
### 会话
任务按三种模式之一投递到目标会话:指定的会话、每次触发新建会话、首次触发时新建会话并在之后的触发中复用。定时任务沿用现在的目标,即创建它的会话。事件任务把判断和处理分开。只读轮次在任务自己的会话中运行,首次触发时新建,之后复用,因为它需要的是指令、本次事件和该任务之前的判断,而不是任务来源会话的长历史。模型在会话中创建任务时,把判断需要的事实写进指令,例如哪项检查已知不稳定。用户接受卡片后,建议的操作发往创建任务的会话,代码和相关历史都在那里。自动化页的“新建”本来就在一个新会话中创建任务,之后由该会话处理;从官方模板启用的任务(后续步骤加入)在自己的会话中继续执行。用户可以在任务上修改模式。
Host 停止期间不运行任何任务。重启后,每个任务把当前来源状态与保存的状态比较一次,不重放中间的变化。时间沿用现有规则:周期任务只补跑最近一次错过的时间点。
### 配置
配置分两层。来源提供方的代码决定能观察什么、如何观察;任务参数决定一个任务观察什么。模型根据用户原话,通过任务工具写入参数,由来源提供方的 schema 校验。任务不携带脚本或其他代码,因此要观察新的东西,就修改或安装来源提供方插件。自动化页以只读方式显示来源参数,参数通过对话修改;时间编辑器保留。
### 机制
- **事件轮次的工具集。** 沙箱的只读模式只限制文件系统,挡不住推送或外发请求。因此事件轮次使用固定的工具集,而不是会话的工具集:读文件和搜索、来源提供方的读取操作,以及 `automation_notify`。没有 shell、写文件、网页抓取和 MCP 工具。工具集记录在会话日志中;轮次进行中排队的用户消息,在该轮次结束后作为普通轮次执行。
- **通知卡片。** 自动化包注册一种操作卡片类型,`automation_notify` 通过操作卡片服务创建这类卡片;该工具只在事件轮次中提供,因此调用前不需要加载 Skill。接受卡片时执行该类型的处理器,由处理器通过 Host 排入后续消息,所以处理任务的会话不必处于打开状态。同一会话中,新卡片会替换尚未处理的旧卡片,与操作卡片服务现在的行为一致;旧卡片在该会话的历史中,新的轮次能看到它,并把仍未处理的内容带到新卡片里。被拒绝的卡片会把错误返回给该轮次。
- **未读标记。** 客户端根据轮次完成推导未读标记。任务自己的会话标记为自动化会话,对这类会话,客户端只为通知显示未读标记,因此没有调用通知的轮次不留下标记。
- **日志。** 已投递的候选事件、轮次的工具集和通知调用都是会话事件,回放可以重建该轮次;TypeScript 和 Python SDK 的期望输出以及一个录制会话快照覆盖这些内容。
- **存储。** 来源、参数、会话模式、触发器状态和运行记录以新的记录版本扩展 Host 任务域,并提供相邻迁移。版本 1 的任务按时间任务读取,在发生修改前不重写,也不补造记录。运行记录有自己的数量和时长上限,与投递记录分开。
- **来源提供方配置。** 轮询间隔和请求额度是每个来源提供方在 cordis.yml 中经过校验的 Config 字段。
### 产品范围
- 不新增入口,不重做页面:定时任务和事件触发的任务共用自动化页。
- 任务列表在状态筛选旁增加来源类型筛选。
- 任务详情增加来源及其参数(只读)和会话模式(可修改)。
- 任务运行记录同时列出已过滤和失败的判定。
- 通知复用会话的未读标记和操作卡片;桌面端新增系统通知。
### 事件触发作为基础设施
触发层是 DSH 共用的基础设施,而不是自动化页的一项功能。需要观察某样东西并把变化交给 agent 的功能,都作为这一层上的任务实现,不再各自实现轮询、状态、记录和通知。
- **DSH 自身状态作为来源**:会话轮次以错误结束、后台作业结束;memory 落地后,还包括一次 memory 整理完成,或 memory 条目发生变化。
- **基于这些来源的功能**:插件推荐,即 memory 整理后发现用户反复手动执行的流程,由 agent 在操作卡片上推荐插件;任务推荐,即回顾当天的会话,提出后续要做的事。每一项都是一个模板任务,由一个 DSH 来源、一条指令和同样的通知步骤组成。插件推荐包现在从对话轮次中提出卡片,memory 整理落地后可以改为基于这类来源。
- **每个使用方都保留的规则**:变化检测和条件匹配由代码完成、运行记录、会话模式、只读的事件轮次,以及只有通知能让任务触达用户。
### 交付顺序
1. 任务与会话解耦,支持三种会话模式。
2. 上线触发层和任务域迁移,以时间作为第一个来源提供方;现有定时任务行为不变。
3. GitHub 来源提供方,覆盖 PR 的检查、评审和评论;事件轮次工具集和 `automation_notify`;操作卡片结束实验状态,或随自动化 bundle 一起提供。
4. 邮件和 IM 来源提供方以及官方模板,然后是 DSH 自身的来源。
## 考虑过的替代方案
**在常驻会话中判断每次观察。** 模型读取每次轮询的结果,没有变化时回复一个静默标记。没有采用,原因是:每次观察都要在会话的完整上下文上花一个轮次;轮询间隔超过前缀缓存的有效期时,每次都要在没有缓存的情况下读取整个上下文;而且模型手里有发消息工具时,能否保持安静取决于它是否遵守指令。本方案由代码丢弃没有变化和不匹配的观察,只有调用通知才会触达用户。
**在创建任务的会话中判断。** 该会话已经有代码和相关历史,指令里不需要额外写事实。没有采用,原因是大多数候选事件不产生通知,每一次都会在该会话的完整上下文上增加一个轮次,前缀缓存过期后要在没有缓存的情况下读取整个上下文,用户正在那里工作时还要排队或打断。只有被接受的工作才会进入该会话。
**由 agent 为每个事件选择会话。** 每次的选择可能不同,用户无法预料通知出现在哪里;而且要判断是否需要历史,得先读取历史。
**每个任务自带条件脚本。** 任务携带一个脚本,由脚本获取数据并作出判断。没有采用,原因是脚本以用户的凭据运行,却没有经过安装插件时的审查;而且每个任务都要自带获取逻辑,无法共用来源提供方。
**代码能判断时由代码直接通知。** 检查失败可以不经模型直接通知。没有采用,原因是这样的通知只包含原始状态。只保留一条路径时,agent 会先读日志,通知中写明失败原因;只在变化时投递,这类轮次很少。
**在会话之外调用一次模型。** 每个事件调用一次模型,成本更低,也不留下会话记录。没有采用,原因是这次调用在判断前无法读取文件或日志,而且要根据结果采取行动仍然需要会话。
**事件轮次沿用会话的权限。** 直接行动可以省去一次点击。没有采用,原因是事件内容来自其他人,只读轮次能防止这些文字在用户接受之前驱动修改、推送或发消息。
**事件轮次使用只读沙箱。** 没有采用,原因是沙箱的只读模式只限制文件系统,处于该模式的轮次仍然可以推送或发出请求。
**结束工具和对轮次结束方式的检查。** 第二个工具可以记录某一轮为什么没有产生通知,触发器则要等待这个结果。没有采用,原因是没有任何环节会使用这个原因:投递之后触发器的工作就结束了,而没有调用通知的轮次本来就是静默的。
**在自动化页提供参数表单。** 每个来源提供方都需要各自的表单、校验和展示。由模型写入参数并以只读方式展示,已经覆盖通过对话创建和修改;来源提供方的 schema 让以后生成表单仍然可行。
**单独的通知入口。** 收件箱页面或标签页会把通知与持有其上下文的会话分开。未读标记和系统通知都指向该会话,自动化页保留记录。
## 验收标准
- 时间改为来源提供方后,现有定时任务行为不变:到期时间相同、补跑规则相同、投递到会话的方式相同。
- 版本 1 的任务按时间任务加载,不重写,也不补造记录。
- 观察 PR 检查的 GitHub 任务,在检查从通过变为失败时投递一个候选事件,持续失败期间不再投递,通过之后再次失败时再投递一个。
- 一次推送导致三项检查失败,只产生一个候选事件。
- 没有变化的观察不写记录,也不启动轮次;不满足条件的变化写一条已过滤记录,不启动轮次;同一原因的连续失败只写一条带计数的记录。
- 运行记录到投递为止:记录候选事件,不记录该轮次做了什么。
- 事件轮次不提供 shell、写文件、网页抓取或 MCP 工具,其工具集出现在会话日志中;用户接受卡片后,下一轮次按会话的权限执行。
- 一次通知调用同时产生卡片、未读标记和桌面端系统通知。
- 没有调用通知的事件轮次不留下未读标记,也不发送系统通知。
- 事件任务的只读轮次在任务自己的会话中运行;接受卡片后,建议的操作发往创建任务的会话。
- 每种会话模式按定义投递:指定的会话接收每次触发,或每次触发新建一个会话,或首次触发时新建一个会话并在之后复用。
- 回放会话日志可以重建事件轮次的候选事件、工具集和通知调用。
- 重启后,任务把当前来源状态与保存的状态比较一次,不重放中间的变化。
- 任务列表可以按来源类型筛选,任务详情以只读方式显示来源参数,会话模式可以修改。
## 风险
- 只读轮次看到的是指令、本次事件和该任务之前的判断,看不到任务来源的会话。判断需要的、来自那个会话的事实,必须在创建任务时写进指令;用户把任务改成投回原会话,就能拿回历史,代价是每次投递都要读取很长的上下文。
- 通知出现在任务自己的会话里,而不是创建任务的对话里;接受卡片后,工作转到那个对话。
- agent 可能通知过于频繁,或者在应该提醒时保持静默。被接受和被忽略的卡片能看出通知过多,但漏掉的通知不会在运行记录中留下痕迹,因为运行记录到投递为止。
- 来源参数不能手动编辑,每次修改都要经过模型。
- 针对事件的修复要等用户接受卡片,不会在无人值守时执行。
- 没有来源提供方插件的来源无法观察。
- 任务只在 Host 运行时执行:应用关闭或机器休眠期间不运行任何任务。
- 事件任务依赖操作卡片,而它目前是实验包,只由个性化推荐 Bundle 装入。
- 只读工具集把判断限制在文件和来源提供方读取操作能看到的内容;来源提供方不提供读取操作时,agent 只能根据事件本身判断。
+1
View File
@@ -131,6 +131,7 @@ External packages installed for runtime use or embedded in distributed Host or b
| [`react-dom`](https://github.com/facebook/react) | MIT |
| [`readable-stream`](https://github.com/nodejs/readable-stream) | MIT |
| [`resolve.exports`](https://github.com/lukeed/resolve.exports) | MIT |
| [`rrule`](https://github.com/jakubroztocil/rrule) | BSD-3-Clause |
| [`semver`](https://github.com/npm/node-semver) | ISC |
| [`serve-static`](https://github.com/expressjs/serve-static) | MIT |
| [`sharp`](https://github.com/lovell/sharp) | Apache-2.0 |
@@ -174,7 +174,7 @@ describe('Python SDK dsh profile keyless smoke', () => {
expect(modelRequests[0]?.output_config).toEqual({ effort: 'max' })
expect(modelRequests[0]?.max_tokens).toBe(1234)
const expectedTools = ['read', 'write', 'edit', 'web_fetch', 'web_search', 'subagent', 'subagent_fork',
'present', 'ask_user_question', 'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update', 'plugin_manager']
'present', 'ask_user_question', 'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view', 'plugin_manager']
const requestText = JSON.stringify(modelRequests[0])
if (ptc) {
expect(toolNames).toEqual(['run_code'])
@@ -1,4 +1,4 @@
/** Reminder activation must share SDK ownership and initialized model limits after process restart. */
/** Schedule authoring and restart delivery must honor the shipped SDK composition. */
import { createServer } from 'node:http'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
@@ -30,7 +30,8 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t
if (restarting) restored.push(request)
const content = requests.length === 1 ? {
type: 'tool_use', id: 'create-reminder', name: 'schedule_create',
input: { title: 'Check SDK', prompt: 'Report the SDK reminder', after_seconds: 86400 },
input: { title: 'Check SDK', prompt: 'Report the SDK reminder',
rrule: 'DTSTART:20300102T000000Z\nRRULE:FREQ=DAILY;COUNT=1', target: 'this_session' },
} : { type: 'text', text: 'ready' }
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse(content, requests.length === 1 ? 'tool_use' : 'end_turn'))
@@ -70,3 +71,64 @@ it('delivers an overdue reminder with the SDK route and lets the client resume t
const session = await second.resumeSession('saved')
expect(await session.run('Continue after the reminder')).toMatchObject({ finalResponse: 'ready' })
})
it('refuses new Session destinations before storing tasks in the shipped SDK profile', async () => {
const root = await mkdtemp(join(tmpdir(), 'sdk-schedule-targets-'))
const requests: Record<string, unknown>[] = []
const calls = ['new', 'new_once', 'this_session'].flatMap(target => [
{ type: 'tool_use', id: `create-${target}`, name: 'schedule_create',
input: { title: `SDK ${target}`, prompt: 'Check SDK',
rrule: 'DTSTART:20300102T000000Z\nRRULE:FREQ=DAILY;COUNT=1', target } },
{ type: 'tool_use', id: `list-${target}`, name: 'schedule_list', input: {} },
])
const server = createServer((incoming, response) => {
let body = ''
incoming.setEncoding('utf8')
incoming.on('data', (chunk: string) => { body += chunk })
incoming.on('end', () => {
const content = calls[requests.length] ?? { type: 'text', text: 'ready' }
requests.push(JSON.parse(body) as Record<string, unknown>)
response.writeHead(200, { 'content-type': 'text/event-stream' })
response.end(messagesResponse(content, content.type === 'tool_use' ? 'tool_use' : 'end_turn'))
})
})
const clients: DeepSeekHarness[] = []
onTestFinished(async () => {
try { await Promise.all(clients.map(client => client.close())) } finally {
try {
await new Promise<void>((resolve, reject) => {
server.close((error) => { if (error === undefined) resolve(); else reject(error) })
})
} finally { await rm(root, { recursive: true, force: true }) }
}
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
const address = server.address()
if (address === null || typeof address === 'string') throw new Error('model fixture has no port')
const env = { ...process.env, DSH_PERMISSION_MODE: 'danger-full-access', DSH_TELEMETRY_DISABLED: '1',
DEEPSEEK_API_KEY: 'keyless-schedule-fixture', DEEPSEEK_BASE_URL: `http://127.0.0.1:${String(address.port)}` }
clearAmbientProxyEnv(env)
const client = new DeepSeekHarness({ cwd: root, dshHome: join(root, '.dsh'),
model: 'deepseek-v4-pro', initializeTimeoutMs: 30_000, env })
clients.push(client)
expect((await client.session('schedule-owner').run('Check the supported schedule destinations')).finalResponse).toBe('ready')
expect(requests).toHaveLength(calls.length + 1)
const results = calls.map((call, index) => {
const messages = requests[index + 1]?.messages as {
content: { type: string; tool_use_id?: string; content?: { type: string; text?: string }[] }[]
}[]
const result = messages.flatMap(message => message.content)
.find(block => block.type === 'tool_result' && block.tool_use_id === call.id)
const text = result?.content?.find(block => block.type === 'text')?.text
if (text === undefined) throw new Error(`SDK model request has no result for ${call.id}`)
return JSON.parse(text) as Record<string, unknown>
})
for (const index of [0, 2]) {
expect(results[index]).toMatchObject({
code: 'invalid_rule', message: expect.stringContaining('choose an existing Session target') as string,
})
expect(results[index + 1]).toMatchObject({ items: [], shown: 0, total: 0 })
}
expect(results[4]).toMatchObject({ title: 'SDK this_session', target: { kind: 'session', sessionId: 'schedule-owner' } })
expect(results[5]).toMatchObject({ items: [results[4]], shown: 1, total: 1 })
})
@@ -1,14 +1,18 @@
/** Built CLI, public Remote requests, and persisted task files; seeded receipts are not delivery evidence. */
/**
* Built CLI, public Remote requests, and persisted task files; seeded receipts are not delivery evidence.
* Existing rows load without writes; edits keep the envelope and store the current target shape.
*/
import { randomUUID } from 'node:crypto'
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { DailyScheduleRecord, ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type { DailyScheduleRecord, ScheduleCatalogEntry, ScheduleTask } from '@deepseek-ai/dsh-schedule'
import { expect, it } from 'vitest'
import { withDefaultWeb, webGet, webRequest } from './default-web-process.ts'
const id = 'retained-remote-task' as DailyScheduleRecord['id']
const sessionId = 'unloaded-owner' as ScheduleCatalogEntry['sessionId']
const sessionId = 'unloaded-owner' as SessionId
const record: DailyScheduleRecord = {
id, kind: 'daily', title: 'Retained instruction', prompt: 'Retained instruction\nwith a second line',
time: '09:00:00.125', timeZone: 'Asia/Shanghai', scheduledAt: '2099-01-01T01:00:00.125Z',
@@ -20,15 +24,33 @@ const task = {
sessionId, record, status: 'active', lastDelivery,
deliveryHistory: { earlierRecordsUnavailable: false, records: [{ ...lastDelivery, prompt: record.prompt }] },
}
const taskPath = (root: string) => join(root, 'home', 'storages', 'schedule.json')
async function seed(root: string, bytes: string): Promise<void> {
await mkdir(join(root, 'home', 'storages'), { recursive: true })
await writeFile(taskPath(root), bytes)
const source = `${JSON.stringify({ unit: { name: 'schedule', version: 1 }, global: null, tables: { tasks: { [id]: task } } }, null, 2)}\n`
const sourcePath = (root: string) => join(root, 'home', 'storages', 'schedule.json')
const receipt = { ...lastDelivery, targetSessionId: sessionId }
const historyRequest = { request: { id, limit: 20 } }
const expectedHistory = {
ok: true,
value: {
id, records: [{ ...receipt, prompt: record.prompt }], earlierRecordsUnavailable: false,
earlierRecordsPruned: false, retention: { days: 30, records: 200 },
},
}
function encoded(value: unknown): string {
return `${JSON.stringify({ unit: { name: 'schedule', version: 1 }, global: null, tables: { tasks: { [id]: value } } }, null, 2)}\n`
/** Catalog entry retains the stored daily rule and has no invented creation or change times. */
const retainedEntry = (title: string) => expect.objectContaining({
id, title, prompt: record.prompt, scheduledAt: record.scheduledAt, target: { kind: 'session', sessionId },
involvedSessionIds: [sessionId], status: 'active', lastDelivery: receipt,
kind: 'daily', time: record.time, timeZone: record.timeZone,
}) as object
/** Seed the existing domain or the exact bytes a preceding Host edited. */
async function seed(root: string, bytes = source): Promise<void> {
await mkdir(join(root, 'home', 'storages'), { recursive: true })
await writeFile(sourcePath(root), bytes)
}
async function readStore(root: string): Promise<string> {
return readFile(sourcePath(root), 'utf8')
}
async function connect(url: string, signal: AbortSignal) {
@@ -48,71 +70,84 @@ async function connect(url: string, signal: AbortSignal) {
}
}
it('edits a retained task through built Remote bindings and preserves its identity and seeded history after cold startup', async (test) => {
let persisted = encoded(task)
let updated = record
const historyRequest = { request: { sessionId, id, limit: 20 } }
const expectedHistory = {
ok: true,
value: {
id, records: task.deliveryHistory.records, earlierRecordsUnavailable: false,
earlierRecordsPruned: false, retention: { days: 30, records: 200 },
},
}
it('edits an existing task through built Remote bindings and keeps its identity and seeded history after cold startup', async (test) => {
let persisted: string | undefined
let renamed: ScheduleCatalogEntry | undefined
await withDefaultWeb(test, async ({ root, url }) => {
const rpc = await connect(url, test.signal)
expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [{ ...record, sessionId, status: 'active', lastDelivery }] })
const catalog = await rpc('schedule/catalog', {})
expect(catalog).toEqual({ ok: true, value: [retainedEntry(record.title)] })
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
const target = new Date(Date.now() + 12 * 60 * 60 * 1_000)
target.setUTCMilliseconds(125)
updated = { ...record, time: target.toISOString().slice(11, 23), timeZone: 'UTC', scheduledAt: target.toISOString() }
const change = { kind: 'daily', daily: { time: updated.time, time_zone: 'UTC' } }
expect(await rpc('schedule/update', { request: { sessionId, id, expected: record, change } }))
.toEqual({ ok: true, value: { id, updated: true, record: updated } })
persisted = await readFile(taskPath(root), 'utf8')
expect(JSON.parse(persisted)).toEqual({
unit: { name: 'schedule', version: 1 },
global: null,
tables: { tasks: { [id]: { ...task, record: updated } } },
const { value: [retained] } = catalog as { value: ScheduleCatalogEntry[] }
const rename = {
request: { id, action: 'update', patch: { title: 'Renamed instruction' }, expectedUpdatedAt: retained?.updatedAt ?? null },
}
const edited = await rpc('schedule/edit', rename)
expect(edited).toEqual({ ok: true, value: retainedEntry('Renamed instruction') })
renamed = (edited as { value: ScheduleCatalogEntry }).value
persisted = await readStore(root)
const document = storedUnit(persisted)
expect(document.unit).toEqual({ name: 'schedule', version: 2 })
expect(document.global).toBeNull()
expect(document.tables.tasks[id]!).toMatchObject({ record: { ...record, title: 'Renamed instruction' },
target: { kind: 'session', sessionId }, status: 'active', updatedAt: renamed.updatedAt, lastDelivery: receipt })
expect(document.tables.tasks[id]!).not.toHaveProperty('sessionId')
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
expect(await rpc('schedule/edit', rename)).toEqual({ ok: true, value: { id, code: 'schedule_conflict' } })
expect(await rpc('schedule/edit', { request: { id: 'missing-task', action: 'delete' } }))
.toEqual({ ok: true, value: { id: 'missing-task', code: 'schedule_not_found' } })
expect(await readStore(root)).toEqual(persisted)
}, { prepare: root => seed(root) })
await withDefaultWeb(test, async ({ root, url }) => {
const rpc = await connect(url, test.signal)
expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [renamed] })
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
expect(await readStore(root)).toEqual(persisted)
await rpc('session/create', { request: { sessionId, cwd: root } })
const rrule = 'DTSTART;TZID=Asia/Shanghai:20990101T090000\nRRULE:FREQ=DAILY'
const replaced = await rpc('schedule/edit', {
request: { id, action: 'update', patch: { timing: { kind: 'rrule', rrule } }, expectedUpdatedAt: renamed?.updatedAt },
})
expect(replaced).toEqual({
ok: true, value: expect.objectContaining({ id, title: 'Renamed instruction', scheduledAt: '2099-01-01T01:00:00.000Z' }) as object,
})
const stored = storedUnit(await readStore(root)).tables.tasks[id]!
expect(stored.record).toMatchObject({ kind: 'rrule', rrule })
expect(stored).not.toHaveProperty('sessionId')
expect(stored).toMatchObject({ target: { kind: 'session', sessionId }, lastDelivery: receipt })
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
expect(await rpc('schedule/update', { request: { sessionId, id, expected: record, change } }))
.toEqual({ ok: true, value: { id, updated: false, code: 'schedule_conflict' } })
expect(await rpc('schedule/update', { request: { sessionId: 'other-owner', id, expected: updated, change } }))
.toEqual({ ok: true, value: { id, updated: false, code: 'schedule_not_found' } })
expect(await readFile(taskPath(root), 'utf8')).toBe(persisted)
}, { prepare: root => seed(root, persisted) })
await withDefaultWeb(test, async ({ root, url }) => {
const rpc = await connect(url, test.signal)
expect(await rpc('schedule/catalog', {})).toEqual({ ok: true, value: [{ ...updated, sessionId, status: 'active', lastDelivery }] })
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
expect(await rpc('schedule/update', { request: {
sessionId, id, expected: updated, change: { kind: 'daily', daily: { time: updated.time, time_zone: 'Etc/UTC' } },
} })).toEqual({ ok: true, value: { id, updated: false, record: updated } })
expect(await readFile(taskPath(root), 'utf8')).toBe(persisted)
}, { prepare: root => seed(root, persisted) })
})
it('creates and idempotently adopts the explicit Session id bound to seeded task data without touching its task file', async (test) => {
const persisted = encoded(task)
const expectedList = { ok: true, value: [record] }
const expectedHistory = {
ok: true,
value: {
id, records: task.deliveryHistory.records, earlierRecordsUnavailable: false,
earlierRecordsPruned: false, retention: { days: 30, records: 200 },
},
}
it('creates and idempotently adopts the explicit Session id bound to existing task data without touching its task files', async (test) => {
await withDefaultWeb(test, async ({ root, url }) => {
const rpc = await connect(url, test.signal)
// A Schedule request waits for startup to validate the task store.
const view = await rpc('schedule/view', { request: { id } })
expect(view).toEqual({ ok: true, value: retainedEntry(record.title) })
const retained = await readStore(root)
const create = { request: { sessionId, cwd: root } }
const expectedCreate = { ok: true, value: { sessionId, agentPreset: 'standard' } }
expect(await rpc('session/create', create)).toEqual(expectedCreate)
expect(await rpc('session/create', create)).toEqual(expectedCreate)
expect(await rpc('schedule/list', { request: { sessionId } })).toEqual(expectedList)
expect(await rpc('schedule/history', { request: { sessionId, id, limit: 20 } })).toEqual(expectedHistory)
expect(await readFile(taskPath(root), 'utf8')).toBe(persisted)
}, { prepare: root => seed(root, persisted) })
expect(await rpc('schedule/view', { request: { id } })).toEqual(view)
expect(await rpc('schedule/history', historyRequest)).toEqual(expectedHistory)
expect(await readStore(root)).toEqual(retained)
expect(await readFile(sourcePath(root), 'utf8')).toBe(source)
}, { prepare: root => seed(root) })
})
/** Read test-owned output without normalizing away the fields asserted below. */
function storedUnit(text: string): {
readonly unit: unknown
readonly global: unknown
readonly tables: { readonly tasks: Record<string, ScheduleTask> }
} {
return JSON.parse(text) as {
unit: unknown
global: unknown
tables: { tasks: Record<string, ScheduleTask> }
}
}
+8 -6
View File
@@ -302,7 +302,7 @@ describe('the shipped Web composition', () => {
expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
'get_goal', 'interrupt_agent', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'plugin_manager', 'present', 'read', 'read_image',
'schedule_create', 'schedule_delete', 'schedule_list', 'schedule_update',
'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view',
'send_message', 'skill',
'subagent', 'subagent_fork', 'todo_write', 'update_goal', 'web_fetch', 'web_search',
'workflow', 'working_directory', 'write',
@@ -1004,7 +1004,7 @@ describe('a forked session', () => {
})
describe('a delegated child', () => {
it.each([false, true])('inherits preset tools with seeded=%s and refuses child reminders', async (seeded) => {
it.each([false, true])('inherits preset tools with seeded=%s and refuses child scheduled tasks', async (seeded) => {
const parent = await ctx.agents.create({
sessionId: SessionId(`preset-child-parent-${seeded}`),
meta: { agentPreset: 'standard' },
@@ -1026,10 +1026,12 @@ describe('a delegated child', () => {
expect(toolNames(ctx, child.agent)).toContain('bash')
expect(ctx.tools.schemas(child.agent)).toEqual(ctx.tools.schemas(parent.agent))
const calls = [
['schedule_create', { prompt: 'Check', after_seconds: 60, title: 'Check' }],
['schedule_create', {
title: 'Check', prompt: 'Check', rrule: 'DTSTART:20990101T010000Z\nRRULE:FREQ=DAILY;COUNT=1', target: 'this_session',
}],
['schedule_list', {}],
['schedule_delete', { id: 'task-1' }],
['schedule_update', { id: 'task-1', title: 'Check' }],
['schedule_view', { id: 'task-1' }],
['schedule_edit', { id: 'task-1', action: 'update', title: 'Check' }],
] as const
for (const [name, args] of calls) {
expect(toolNames(ctx, child.agent)).toContain(name)
@@ -1037,7 +1039,7 @@ describe('a delegated child', () => {
callId: ToolCallId(`child-${name}`), signal: new AbortController().signal,
name, arguments: args, agent: child.agent,
})
expect(result.value).toEqual({ code: 'subagent_session', message: 'A delegated subagent cannot use reminders.' })
expect(result.value).toEqual({ code: 'subagent_session', message: 'A delegated subagent cannot use scheduled tasks.' })
}
expect(child.agent.session.header.agentPreset).toBe('standard')
} finally {
+2 -2
View File
@@ -15,8 +15,8 @@
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: b57525e17b9638ab
zh: 274fe8344f7c2202
en: 1667e3d6ffddea4a
zh: 4661a42b9ef4f673
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
+1 -1
View File
@@ -53,7 +53,7 @@ A server-expired account credential returns to Welcome when no official API key
Desktop microphone access is restricted to audio requests from the primary `dsh-app://app` frame. macOS uses system microphone authorization, a packaged usage description, and `com.apple.security.device.audio-input` in the main application and Helper signatures.
Press F12 (Fn+F12 on media-key keyboards), Command+Option+I on macOS, or Ctrl+Shift+I on Windows to toggle DevTools for the focused application page, including in packaged builds. These native shortcuts use hidden application-menu items. Update overlays and packaged embedded browser guests disable DevTools.
Press F12 (Fn+F12 on media-key keyboards), Command+Option+I on macOS, or Ctrl+Shift+I on Windows to toggle DevTools for the focused application page, including in packaged builds. The application menu shows a localized “Developer tools” command in a separate group before Hide and Quit (before Exit on Windows). Windows exposes it in the titlebar application popup; its hidden native application menu registers the shortcuts. macOS and Linux keep a hidden F12 shortcut alias in their application menus. Update overlays and packaged embedded browser guests disable DevTools.
<a id="terminal-command"></a>
+1 -1
View File
@@ -53,7 +53,7 @@ Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform
桌面麦克风访问仅允许主 `dsh-app://app` 页面发起的音频请求。macOS 使用系统麦克风授权、随包用途说明,以及主应用与 Helper 签名中的 `com.apple.security.device.audio-input` 权限。
按 F12(多媒体功能键键盘上为 Fn+F12)、macOS 的 Command+Option+I 或 Windows 的 Ctrl+Shift+I,可切换当前获得焦点的应用页面的 DevTools,打包版本同样支持。这些原生快捷键通过隐藏的应用菜单项注册。更新遮罩和打包版本的内嵌浏览器禁用 DevTools。
按 F12(多媒体功能键键盘上为 Fn+F12)、macOS 的 Command+Option+I 或 Windows 的 Ctrl+Shift+I,可切换当前获得焦点的应用页面的 DevTools,打包版本同样支持。应用菜单在隐藏和退出命令之前的独立分组中显示本地化的“开发者工具”命令。Windows 在标题栏的应用弹出菜单中显示开关,通过隐藏的原生应用菜单注册快捷键;macOS 和 Linux 的应用菜单保留隐藏的 F12 快捷键别名。更新遮罩和打包版本的内嵌浏览器禁用 DevTools。
<a id="terminal-command"></a>
+8
View File
@@ -104,6 +104,7 @@ export const en = {
welcomeContinueFailed: 'Could not open the workspace. Please try again.',
checkUpdatesMenu: 'Check for Updates…',
reloadPageMenu: 'Reload Page',
toggleDevToolsMenu: 'Developer tools',
restartAppHostMenu: 'Restart App and Host',
updateCheckFailedTitle: 'Update Check Failed',
updateCheckFailed: 'Could not check for updates. Please try again later.',
@@ -283,6 +284,7 @@ export const zh = {
welcomeContinueFailed: '无法打开工作区,请重试。',
checkUpdatesMenu: '检查更新…',
reloadPageMenu: '刷新页面',
toggleDevToolsMenu: '开发者工具',
restartAppHostMenu: '重启应用与 Host',
updateCheckFailedTitle: '更新检查失败',
updateCheckFailed: '检查更新失败,请稍后重试。',
@@ -460,6 +462,7 @@ export const ja = {
welcomeContinueFailed: 'ワークスペースを開けませんでした。もう一度お試しください。',
checkUpdatesMenu: 'アップデートを確認…',
reloadPageMenu: 'ページを再読み込み',
toggleDevToolsMenu: '開発者ツール',
restartAppHostMenu: 'アプリとホストを再起動',
updateCheckFailedTitle: 'アップデートの確認に失敗しました',
updateCheckFailed: 'アップデートを確認できませんでした。後でもう一度お試しください。',
@@ -637,6 +640,7 @@ export const es = {
welcomeContinueFailed: 'No se pudo abrir el espacio de trabajo. Por favor inténtalo de nuevo.',
checkUpdatesMenu: 'Buscar actualizaciones...',
reloadPageMenu: 'Recargar página',
toggleDevToolsMenu: 'Herramientas de desarrollo',
restartAppHostMenu: 'Reiniciar la aplicación y el host',
updateCheckFailedTitle: 'Error en la comprobación de actualización',
updateCheckFailed: 'No se pudo buscar actualizaciones. Inténtelo de nuevo más tarde.',
@@ -814,6 +818,7 @@ export const fr = {
welcomeContinueFailed: "Impossible d'ouvrir l'espace de travail. Veuillez réessayer.",
checkUpdatesMenu: 'Vérifiez les mises à jour…',
reloadPageMenu: 'Recharger la page',
toggleDevToolsMenu: 'Outils de développement',
restartAppHostMenu: "Redémarrez l'application et l'hôte",
updateCheckFailedTitle: 'Échec de la vérification de la mise à jour',
updateCheckFailed: 'Impossible de vérifier les mises à jour. Veuillez réessayer plus tard.',
@@ -991,6 +996,7 @@ export const de = {
welcomeContinueFailed: 'Der Arbeitsbereich konnte nicht geöffnet werden. Bitte versuchen Sie es erneut.',
checkUpdatesMenu: 'Nach Updates suchen…',
reloadPageMenu: 'Seite neu laden',
toggleDevToolsMenu: 'Entwicklertools',
restartAppHostMenu: 'Anwendung und Host neu starten',
updateCheckFailedTitle: 'Update-Überprüfung fehlgeschlagen',
updateCheckFailed: 'Es konnte nicht nach Updates gesucht werden. Bitte versuchen Sie es später noch einmal.',
@@ -1168,6 +1174,7 @@ export const ru = {
welcomeContinueFailed: 'Не удалось открыть рабочую область. Пожалуйста, попробуйте еще раз.',
checkUpdatesMenu: 'Проверить наличие обновлений…',
reloadPageMenu: 'Обновить страницу',
toggleDevToolsMenu: 'Инструменты разработчика',
restartAppHostMenu: 'Перезапустите приложение и хост.',
updateCheckFailedTitle: 'Проверка обновления не удалась',
updateCheckFailed: 'Не удалось проверить наличие обновлений. Пожалуйста, повторите попытку позже.',
@@ -1345,6 +1352,7 @@ export const pt = {
welcomeContinueFailed: 'Não foi possível abrir o espaço de trabalho. Por favor, tente novamente.',
checkUpdatesMenu: 'Verifique se há atualizações…',
reloadPageMenu: 'Recarregar página',
toggleDevToolsMenu: 'Ferramentas do desenvolvedor',
restartAppHostMenu: 'Reinicie o aplicativo e o host',
updateCheckFailedTitle: 'Falha na verificação de atualização',
updateCheckFailed: 'Não foi possível verificar se há atualizações. Por favor, tente novamente mais tarde.',
+10 -7
View File
@@ -1060,8 +1060,8 @@ async function main(): Promise<void> {
{ label: currentDesktopLocale().messages.checkUpdatesMenu, click: () => { void openUpdatePrompt(true) } },
...process.platform === 'darwin' || process.platform === 'win32'
? [{ label: currentDesktopLocale().messages.cliCommandMenu, click: () => { void commandManager.show() } }] : [],
{ type: 'separator' },
...development ? [
{ type: 'separator' as const },
{ label: currentDesktopLocale().messages.reloadPageMenu, role: 'reload' as const },
{ label: currentDesktopLocale().messages.restartAppHostMenu, click: () => {
if (quitting) return
@@ -1069,20 +1069,23 @@ async function main(): Promise<void> {
quitWithoutConfirmation()
} },
] : [],
{ role: 'toggleDevTools', label: currentDesktopLocale().messages.toggleDevToolsMenu },
{ type: 'separator' },
...hideCommands,
{ role: 'quit', ...(darwin ? { label: currentDesktopLocale().messages.quitApplication }
: process.platform === 'win32' ? { label: currentDesktopLocale().messages.exitApplication } : {}) },
]
const devToolsItems: MenuItemConstructorOptions[] = [
const devToolsF12Shortcut: MenuItemConstructorOptions = { role: 'toggleDevTools', visible: false, accelerator: 'F12' }
const windowsDevToolsShortcuts: MenuItemConstructorOptions[] = [
{ role: 'toggleDevTools', visible: false },
{ role: 'toggleDevTools', visible: false, accelerator: 'F12' },
devToolsF12Shortcut,
]
const refreshApplicationMenu = (): void => {
Menu.setApplicationMenu(Menu.buildFromTemplate(process.platform === 'win32' ? devToolsItems : [{
label: darwin ? app.name : currentDesktopLocale().messages.application,
submenu: [...applicationItems(), ...devToolsItems],
}, ...platformMenus()]))
Menu.setApplicationMenu(Menu.buildFromTemplate(process.platform === 'win32'
? windowsDevToolsShortcuts : [{
label: darwin ? app.name : currentDesktopLocale().messages.application,
submenu: [...applicationItems(), devToolsF12Shortcut],
}, ...platformMenus()]))
tray?.relabel()
}
refreshApplicationMenu()
@@ -1,10 +1,27 @@
[
{
"label": "About DeepSeek Harness",
"role": "about"
},
{
"type": "separator"
},
{
"label": "Check for Updates…"
},
{
"label": "Manage dsh Command…"
},
{
"type": "separator"
},
{
"role": "toggleDevTools",
"label": "Developer tools"
},
{
"type": "separator"
},
{
"role": "hide",
"label": "Hide DeepSeek Harness"
@@ -17,6 +34,9 @@
"role": "unhide",
"label": "Show All"
},
{
"type": "separator"
},
{
"role": "quit",
"label": "Quit DeepSeek Harness"
@@ -1,10 +1,27 @@
[
{
"label": "关于 DeepSeek Harness",
"role": "about"
},
{
"type": "separator"
},
{
"label": "检查更新…"
},
{
"label": "管理 dsh 命令…"
},
{
"type": "separator"
},
{
"role": "toggleDevTools",
"label": "开发者工具"
},
{
"type": "separator"
},
{
"role": "hide",
"label": "隐藏 DeepSeek Harness"
@@ -17,6 +34,9 @@
"role": "unhide",
"label": "显示全部"
},
{
"type": "separator"
},
{
"role": "quit",
"label": "退出 DeepSeek Harness"
+46 -12
View File
@@ -550,12 +550,49 @@ describe('desktop main startup', () => {
expect((await handler(new Request('dsh-app://unknown/update-dialog.html'))).status).toBe(404)
})
it('installs hidden native DevTools shortcuts in the macOS application menu', async () => {
vi.stubGlobal('process', { ...process, platform: 'darwin' })
it.each(([
['darwin', 'en'], ['darwin', 'zh-CN'], ['win32', 'en'], ['win32', 'zh-CN'], ['linux', 'en'], ['linux', 'zh-CN'],
] as const).flatMap(([platform, locale]) => [
[platform, locale, true] as const, [platform, locale, false] as const,
]))('groups localized DevTools before quit on %s (%s, packaged=%s)', async (platform, locale, packaged) => {
vi.stubGlobal('process', { ...process, platform })
harness.app.isPackaged = packaged
vi.spyOn(harness.app, 'getPreferredSystemLanguages').mockReturnValue([locale])
await readyForUpdate()
expect(applicationMenuItems().slice(-2)).toEqual([
{ role: 'toggleDevTools', visible: false },
{ role: 'toggleDevTools', visible: false, accelerator: 'F12' },
const messages = locale === 'en' ? en : zh
const menu = applicationMenuItems()
const visible = menu.filter(item => item.visible !== false)
expect(visible.map(item => item.role === 'quit' ? 'quit' : item.label ?? item.type)).toEqual([
messages.aboutMenu, 'separator', messages.checkUpdatesMenu,
...platform === 'linux' ? [] : [messages.cliCommandMenu],
'separator', ...packaged ? [] : [messages.reloadPageMenu, messages.restartAppHostMenu],
messages.toggleDevToolsMenu, 'separator',
...platform === 'darwin' ? [messages.hideApplication, messages.hideOtherApplications, messages.showAllApplications, 'separator'] : [],
'quit',
])
expect(visible.filter(item => item.role === 'toggleDevTools')).toEqual([
{ role: 'toggleDevTools', label: messages.toggleDevToolsMenu },
])
if (platform === 'win32') {
expect(harness.menu.mock.calls[0]![0]).toEqual([
{ role: 'toggleDevTools', visible: false },
{ role: 'toggleDevTools', visible: false, accelerator: 'F12' },
])
expect(menu.every(item => item.visible !== false)).toBe(true)
} else {
expect(menu.filter(item => item.visible === false)).toEqual([
{ role: 'toggleDevTools', visible: false, accelerator: 'F12' },
])
}
const sender = harness.windows[0]!.webContents
const nextLocale = locale === 'en' ? 'zh' : 'en'
harness.ipcOn.mock.calls.find(([channel]) => channel === DESKTOP_IPC.localeChanged)![1](
{ sender, senderFrame: sender.mainFrame }, nextLocale,
)
const refreshed = platform === 'win32' ? applicationMenuItems()
: harness.menu.mock.lastCall![0][0]!.submenu as MenuItemConstructorOptions[]
expect(refreshed.filter(item => item.role === 'toggleDevTools' && item.visible !== false)).toEqual([
{ role: 'toggleDevTools', label: nextLocale === 'en' ? en.toggleDevToolsMenu : zh.toggleDevToolsMenu },
])
expect(harness.windows[0]!.options).toMatchObject({ webPreferences: { devTools: true } })
})
@@ -1031,7 +1068,7 @@ describe('desktop main startup', () => {
expect(() => handler(event, 'application', NaN, 34)).toThrow('invalid popup request')
const application = handler(event, 'application', 48, 34)
expect(harness.menu.buildFromTemplate.mock.lastCall![0].map(item => item.label ?? item.type)).toEqual([
'关于 DeepSeek Harness', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', '退出',
'关于 DeepSeek Harness', 'separator', '检查更新…', '管理 dsh 命令…', 'separator', zh.toggleDevToolsMenu, 'separator', '退出',
])
expect(harness.popup.mock.lastCall![0]).toMatchObject({ window, x: 48, y: 34 })
expect(harness.popup.mock.lastCall![0].callback).toBeTypeOf('function')
@@ -1068,8 +1105,8 @@ describe('desktop main startup', () => {
: ['Application', 'editMenu'])
const application = template[0]!.submenu as MenuItemConstructorOptions[]
expect(application.filter(item => item.visible !== false).map(describeItem)).toEqual(platform === 'darwin'
? ['about', 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit']
: ['about', 'separator', en.checkUpdatesMenu, 'separator', 'quit'])
? ['about', 'separator', en.checkUpdatesMenu, en.cliCommandMenu, 'separator', 'toggleDevTools', 'separator', 'hide', 'hideOthers', 'unhide', 'separator', 'quit']
: ['about', 'separator', en.checkUpdatesMenu, 'separator', 'toggleDevTools', 'separator', 'quit'])
expect(harness.menu.setApplicationMenu).toHaveBeenCalledOnce()
})
@@ -1082,10 +1119,7 @@ describe('desktop main startup', () => {
try {
await import('../src/main.ts')
await harness.preparing.promise
const commands = applicationMenuItems().filter(item =>
item.role === 'hide' || item.role === 'hideOthers' || item.role === 'unhide' || item.role === 'quit'
|| item.label === en.checkUpdatesMenu || item.label === zh.checkUpdatesMenu
|| item.label === en.cliCommandMenu || item.label === zh.cliCommandMenu)
const commands = applicationMenuItems().filter(item => item.visible !== false)
await expect(JSON.stringify(commands, null, 2) + '\n')
.toMatchFileSnapshot(`./expected/application-menu-${locale}.json`)
expect(harness.app.name).toBe('@deepseek-ai/dsh-desktop')
+1 -2
View File
@@ -228,9 +228,8 @@ export function createAssembledRemote(options: AssembledRemoteOptions = {}): Ass
})
mock.unary('session/list', () => ok({ items: structuredClone(sessions) }))
// The shipped composition mounts the `ui-schedule` row, so the Schedule
// client reads the catalog and the per-Session list over this mock.
// client reads the catalog over this mock.
mock.unary('schedule/catalog', () => ok([]))
mock.unary('schedule/list', () => ok([]))
mock.unary('session/projections', (request: unknown) => {
const sessionId = recordString(recordValue(request, 'request'), 'sessionId')
const summary = sessions.find(candidate => candidate.sessionId === sessionId)
+9 -6
View File
@@ -119,13 +119,16 @@ describe.skipIf(MODE === 'record')('web e2e: cold Auto-review denial', () => {
await ledger.locator('table[data-scroll-ready="true"]').waitFor({ timeout: 15_000 })
const nativeRecord = ledger.locator('tr[data-kind="tool"]').filter({ hasText: 'mystery' })
const innerRecord = ledger.locator('tr[data-kind="subtool"]').filter({ hasText: 'bash' })
await expect.poll(() => nativeRecord.textContent()).toContain('AUTO_REVIEW_DENIED')
await expect.poll(() => innerRecord.textContent()).toContain('AUTO_REVIEW_DENIED')
await expect.poll(() => nativeRecord.textContent()).toContain('Error: Auto review rejected tool "mystery"; its body was not executed')
await expect.poll(() => innerRecord.textContent()).toContain('Error: Auto review rejected tool "bash"; its body was not executed')
await innerRecord.click()
await page.getByRole('tab', { name: 'Result', exact: true }).click()
await page.getByRole('tabpanel', { name: 'Result' })
.getByText('AutoReviewDeniedError: AUTO_REVIEW_DENIED', { exact: true })
.waitFor({ state: 'visible' })
for (const tab of ['Summary', 'Result']) {
await page.getByRole('tab', { name: tab, exact: true }).click()
const panel = page.getByRole('tabpanel', { name: tab })
await panel.getByText('Error: Auto review rejected tool "bash"; its body was not executed', { exact: true })
.waitFor({ state: 'visible' })
expect(await panel.getByText('AutoReviewDeniedError: AUTO_REVIEW_DENIED', { exact: true }).count()).toBe(0)
}
await captureAutoReviewState(page, 'deny-trajectory')
const trajectory = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd))
.split(SEED_ID).join('{{seededId}}')
+5 -3
View File
@@ -55,7 +55,7 @@ it('replays highlighted Python stubs, PowerShell and CSV reads with their docume
await expandTurnProcesses(page)
await page.locator('[data-sidebar-right-expand]').click()
await page.locator('[data-sidebar-right-guide-entry="files"]').click()
const filesTab = page.locator('[data-dockkit-tab]').filter({ has: page.getByText('Files', { exact: true }) })
const toggle = page.locator('[data-files-navigator-toggle]:visible')
const preview = page.locator('[data-textpreview-url]')
const snapshots: string[] = []
for (const file of FILES) {
@@ -66,8 +66,10 @@ it('replays highlighted Python stubs, PowerShell and CSV reads with their docume
await expect.poll(() => read.locator('[data-read] span[style*="color:"]').count()).toBeGreaterThan(0)
expect(await read.getByText(file.lang, { exact: true }).count()).toBe(1)
snapshots.push(`## Read ${file.name}\n\n${await captureStableAria(page, readSelector, scaffold.workspaceCwd)}`)
await filesTab.click()
await page.locator('[data-files-entry="file"]').getByRole('button', { name: file.name, exact: true }).click()
// The first file replaces the files page; later ones open from the pane's navigator.
// The files page always shows its tree and draws no toggle.
if (await toggle.count() > 0 && await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click()
await page.locator('[data-files-navigator]:visible [data-files-entry="file"]').getByRole('button', { name: file.name, exact: true }).click()
const viewer = preview.locator('[data-document-viewer-menu]')
if (file.name === 'table.csv') {
await expect.poll(() => viewer.innerText()).toBe('Spreadsheet')
+20
View File
@@ -268,6 +268,26 @@ describe.each(['MacIntel', 'Win32', 'Linux x86_64'])('web context menus on %s',
await file.click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Open in sidebar', exact: true }).click()
await page.locator('[data-document-preview]').getByText('SECOND', { exact: true }).waitFor()
// The same link moves that tab into a floating panel and back, delivering its line each time.
const floating = page.locator('[data-sidebar-right-session]:not([hidden]) [data-dockkit-float]')
const dockedFirst = page.locator('[data-rightbar-col] [data-dockkit-pane] [data-dockkit-tab]', { hasText: 'first.txt' })
await file.click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Open in floating panel', exact: true }).click()
await expect.poll(() => floating.count()).toBe(1)
await floating.locator('[data-textpreview-target="2"]', { hasText: 'SECOND' }).waitFor()
await expect.poll(() => dockedFirst.count()).toBe(0)
// The new panel covers the link, so the keyboard raises its menu.
await file.focus()
await page.keyboard.press('Shift+F10')
await page.getByRole('menuitem', { name: 'Open in floating panel', exact: true }).click()
await floating.locator('[data-textpreview-target="2"]').waitFor()
expect(await floating.count()).toBe(1)
await file.focus()
await page.keyboard.press('Shift+F10')
await page.getByRole('menuitem', { name: 'Open in sidebar', exact: true }).click()
await expect.poll(() => floating.count()).toBe(0)
await expect.poll(() => dockedFirst.count()).toBe(1)
await page.locator('[data-rightbar-col] [data-textpreview-target="2"]').waitFor()
await page.getByRole('link', { name: 'Website', exact: true }).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click()
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe('https://example.com/path?q=1#fragment')
@@ -113,7 +113,7 @@ async function sidebarSnapshot(page: Page) {
coversViewport: expanded && rect.x === 0 && rect.y === 0
&& Math.round(rect.width) === window.innerWidth && Math.round(rect.height) === window.innerHeight,
resizeHandleWidth: handle === null ? 0 : Math.round(handle.getBoundingClientRect().width),
expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] > button[aria-expanded="true"]')]
expandedDirectories: [...panel.querySelectorAll('[data-files-entry="directory"] button[aria-expanded="true"]')]
.map(button => button.textContent?.trim()),
}
})
@@ -196,6 +196,14 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S
.toBe('none')
await expect.poll(() => blankColumn.locator('[data-sidebar-right-panel]').boundingBox())
.toEqual({ x: 0, y: 0, width: 767, height: blankViewport.height })
// A preview the files page opened starts with its tree hidden; shown, the tree fills the viewport.
const treeToggle = blankColumn.locator('[data-files-navigator-toggle]')
await expect.poll(() => treeToggle.getAttribute('aria-expanded')).toBe('false')
await treeToggle.click()
await blankColumn.locator('[data-files-navigator]').waitFor({ state: 'visible' })
expect(await blankColumn.locator('[data-textpreview-body]').evaluate(node => getComputedStyle(node).visibility)).toBe('hidden')
await treeToggle.click()
await expect.poll(() => treeToggle.getAttribute('aria-expanded')).toBe('false')
await blankColumn.getByText('Workspace preview is available.', { exact: true }).waitFor()
await blankColumn.locator('[data-sidebar-right-toggle]').click()
await blankColumn.locator('[data-dockkit-pane]').first().waitFor({ state: 'hidden' })
@@ -369,7 +377,8 @@ describe.skipIf(MODE === 'record')('web e2e: details panel follows the current S
expect(await panel.getAttribute('data-sidebar-right-panel')).toBe('push')
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
await column.locator('[data-files-state="tree"]').waitFor({ timeout: 15_000 })
const workspaceDirectory = column.locator('[data-files-entry="directory"] > button').filter({ hasText: /^workspace$/ })
const workspaceDirectory = column.locator('[data-files-entry="directory"] button')
.and(column.getByRole('button', { name: 'workspace', exact: true }))
await workspaceDirectory.waitFor({ timeout: 15_000 })
await workspaceDirectory.click()
await expect.poll(() => workspaceDirectory.getAttribute('aria-expanded')).toBe('true')
+56
View File
@@ -1563,6 +1563,62 @@ else process.exit(1);
await compareOrRefreshGolden(EXPECTED, sections.join('\n\n'), MODE)
await assertFixtureInventory(SNAPSHOT_DIR, ['document.expected.md', 'applications.expected.md', 'applications-no-default.expected.md', 'paging.patch.yml'])
})
it('preserves Markdown reading position beyond the first page after automatic and manual refresh', async () => {
onTestFailed(() => saveFailureShot(page, `screenshots/0908-document-preview/refresh-scroll-${process.pid}`))
if (await page.getByText('LIGHTHOUSE', { exact: true }).count() === 0) {
const settled = scaffold.whenTurnSettled()
const input = page.locator('[data-composer-input]').first()
await input.fill(PROMPT)
await input.press('Enter')
await settled
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
}
const cwd = scaffold.ctx.agents.list()[0]?.session.header.cwd
if (cwd === undefined) throw new Error('Session has no workspace cwd')
const path = join(cwd, 'refresh-scroll.md')
const markdown = '# Before refresh\n\n' + Array.from({ length: PAGE_LINES * 2 }, (_, index) => `Paragraph ${index + 1}\n`).join('\n')
await writeFile(path, markdown)
const column = page.locator('[data-rightbar-col]')
const expand = page.locator('[data-sidebar-right-expand]')
if (await expand.isVisible()) await expand.click()
const filesTab = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('Files', { exact: true }) })
if (await filesTab.count() === 0) await column.locator('[data-sidebar-right-guide-entry="files"]').click()
await filesTab.click()
await column.locator('[data-files-reload]').click()
const preview = column.locator('[data-textpreview-url]')
await openPreviewFile(column, filesTab, preview, 'refresh-scroll.md')
const body = preview.locator('[data-textpreview-body]')
const heading = body.getByRole('heading', { level: 1 })
await expect.poll(() => heading.textContent()).toBe('Before refresh')
await expect.poll(() => preview.locator('[data-textpreview-more]').isEnabled()).toBe(true)
const target = await body.evaluate(node => node.scrollHeight + 100)
await scrollForNextPage(body)
await expect.poll(() => body.evaluate(node => node.scrollHeight - node.clientHeight)).toBeGreaterThan(target)
await body.evaluate((node, top) => new Promise<void>((resolve) => {
node.addEventListener('scroll', () => { resolve() }, { once: true })
node.scrollTop = top
}), target)
const original = await body.evaluate(node => node.scrollTop)
expect(original).toBe(target)
// Content growing above the viewport keeps the pixel offset instead of following the content.
await heading.evaluate((node) => { node.style.paddingTop = '300px' })
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
expect(await body.evaluate(node => node.scrollTop)).toBe(original)
await heading.evaluate((node) => { node.style.paddingTop = '' })
await writeFile(path, markdown.replace('Before refresh', 'After refresh'))
await expect.poll(() => heading.textContent()).toBe('After refresh')
await expect.poll(() => body.evaluate((node, top) => Math.abs(node.scrollTop - top), original)).toBeLessThanOrEqual(1)
const rendered = await heading.elementHandle()
await preview.locator('[data-textpreview-tool="reload"]').click()
await expect.poll(() => rendered!.evaluate(node => node.isConnected)).toBe(false)
await expect.poll(() => heading.textContent()).toBe('After refresh')
await expect.poll(() => body.evaluate((node, top) => Math.abs(node.scrollTop - top), original)).toBeLessThanOrEqual(1)
await rendered!.dispose()
expect(tripwire.pageErrors).toEqual([])
})
})
describe.skipIf(MODE === 'record')('web e2e: Host Office preview', () => {
+5 -3
View File
@@ -54,7 +54,7 @@ describe.skipIf(mode === 'record')('web e2e: independent-writer Excel previews',
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
await column.locator('[data-files-state="tree"]').waitFor()
await column.locator('[data-files-reload]').click()
const files = column.locator('[data-dockkit-tab]').filter({ has: page.getByText('Files', { exact: true }) })
const toggle = column.locator('[data-files-navigator-toggle]:visible')
const preview = column.locator('[data-textpreview-url]')
const excel = preview.locator('[data-excel-preview]')
const sheets = excel.locator('.luckysheet-sheets-item-name')
@@ -62,8 +62,10 @@ describe.skipIf(mode === 'record')('web e2e: independent-writer Excel previews',
const rows = ['# Independent-writer Excel previews', '']
await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(page.url()).origin })
for (const name of [...excelOpcCases, ...excelOpeningCases, ...excelXmlCases]) {
await files.click()
await column.locator('[data-files-entry="file"]').getByRole('button', { name: `${name}.xlsx`, exact: true }).click()
// The first file replaces the files page; later ones open from the pane's navigator.
// The files page always shows its tree and draws no toggle.
if (await toggle.count() > 0 && await toggle.getAttribute('aria-expanded') !== 'true') await toggle.click()
await column.locator('[data-files-navigator]:visible [data-files-entry="file"]').getByRole('button', { name: `${name}.xlsx`, exact: true }).click()
await expect.poll(async () => (await preview.getAttribute('data-textpreview-url'))?.endsWith(`/${name}.xlsx`)).toBe(true)
await sheets.getByText('数据', { exact: true }).waitFor()
await excel.locator('.fortune-sheet-overlay').click({ position: { x: 70, y: 30 } })
@@ -29,20 +29,20 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: deepseek-flash
- button "模型选项 1"
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: DeepSeek-V4.1-Flash
- button "模型选项 1"
- button "删除模型 1"
- button "调整模型顺序 2"
- textbox "模型 ID 2":
- /placeholder: 模型 ID
- text: deepseek-v4-pro
- button "模型选项 2"
- button "删除模型 2"
- textbox "显示名称 2":
- /placeholder: 显示名称
- text: DeepSeek-V4-Pro
- button "模型选项 2"
- button "删除模型 2"
- button "添加模型"
- button "取消"
- button "保存"
@@ -36,11 +36,11 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: gpt-6-astra
- button "模型选项 1" [expanded]
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: GPT-6 Astra
- button "模型选项 1" [expanded]
- button "删除模型 1"
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
@@ -44,10 +44,10 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: acme-large
- textbox "显示名称 1":
- /placeholder: 显示名称
- button "模型选项 1" [expanded]
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
@@ -44,10 +44,10 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: acme-large
- textbox "显示名称 1":
- /placeholder: 显示名称
- button "模型选项 1" [expanded]
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
@@ -0,0 +1,64 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: minimax-cn
- img "API 密钥已配置"
- button "编辑 minimax-cn": 编辑
- button "删除 minimax-cn": 删除
- listitem:
- text: Acme 网关 自定义
- button "编辑 Acme 网关 (acme-gateway)": 编辑
- button "删除 Acme 网关 (acme-gateway)": 删除
- text: Acme 网关 acme-gateway API 密钥
- textbox "API 密钥":
- /placeholder: 输入 API 密钥
- group:
- text: 自定义设置 显示名称
- textbox "显示名称":
- /placeholder: acme-gateway
- text: Acme 网关
- text: API 地址
- textbox "API 地址":
- /placeholder: https://gateway.acme.example/v1
- text: https://gateway.acme.example/v1
- text: API 协议
- combobox "API 协议":
- option "OpenAI Chat Completions"
- option "OpenAI Responses"
- option "Anthropic Messages" [selected]
- region "模型目录":
- text: 模型目录 已自定义模型目录
- button "恢复默认模型"
- button "获取可用模型"
- button "调整模型顺序 1"
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: order-second
- button "模型选项 1"
- button "删除模型 1"
- button "调整模型顺序 2"
- textbox "模型 ID 2":
- /placeholder: 模型 ID
- text: order-third
- button "模型选项 2"
- button "删除模型 2"
- button "调整模型顺序 3"
- textbox "模型 ID 3":
- /placeholder: 模型 ID
- text: acme-large
- button "模型选项 3"
- button "删除模型 3"
- button "添加模型"
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -0,0 +1,84 @@
- dialog "设置":
- text: 设置
- navigation:
- button "通用设置"
- button "模型"
- button "内置插件"
- button "Agent 预设"
- button "打开配置文件"
- button "关闭"
- heading "模型" [level=2]
- paragraph: 填入各提供商的 API 密钥即可使用其模型。
- list:
- listitem:
- text: minimax-cn
- img "API 密钥已配置"
- button "编辑 minimax-cn": 编辑
- button "删除 minimax-cn": 删除
- listitem:
- text: Acme 网关 自定义
- button "编辑 Acme 网关 (acme-gateway)": 编辑
- button "删除 Acme 网关 (acme-gateway)": 删除
- text: Acme 网关 acme-gateway API 密钥
- textbox "API 密钥":
- /placeholder: 输入 API 密钥
- group:
- text: 自定义设置 显示名称
- textbox "显示名称":
- /placeholder: acme-gateway
- text: Acme 网关
- text: API 地址
- textbox "API 地址":
- /placeholder: https://gateway.acme.example/v1
- text: https://gateway.acme.example/v1
- text: API 协议
- combobox "API 协议":
- option "OpenAI Chat Completions"
- option "OpenAI Responses"
- option "Anthropic Messages" [selected]
- region "模型目录":
- text: 模型目录 已自定义模型目录
- button "恢复默认模型"
- button "获取可用模型"
- button "调整模型顺序 1"
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: order-second
- button "模型选项 1" [expanded]
- button "删除模型 1"
- text: 显示名称
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: 手机上的完整显示名称
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
- text: 最大输出 token 数
- textbox "最大输出 token 数 1":
- /placeholder: 128K
- group "输入类型 1":
- text: 输入类型
- checkbox "文本" [checked] [disabled]
- text: 文本
- checkbox "图片"
- text: 图片
- group "推理等级 1":
- text: 推理等级
- button "推理等级说明": "?"
- switch "推理等级 1"
- button "调整模型顺序 2"
- textbox "模型 ID 2":
- /placeholder: 模型 ID
- text: order-third
- button "模型选项 2"
- button "删除模型 2"
- button "调整模型顺序 3"
- textbox "模型 ID 3":
- /placeholder: 模型 ID
- text: acme-large
- button "模型选项 3"
- button "删除模型 3"
- button "添加模型"
- button "取消"
- button "保存"
- button "添加模型提供商"
@@ -29,11 +29,11 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: deepseek-flash
- button "模型选项 1" [expanded]
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: DeepSeek-V4.1-Flash
- button "模型选项 1" [expanded]
- button "删除模型 1"
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
@@ -51,11 +51,11 @@
- textbox "模型 ID 2":
- /placeholder: 模型 ID
- text: deepseek-v4-pro
- button "模型选项 2"
- button "删除模型 2"
- textbox "显示名称 2":
- /placeholder: 显示名称
- text: DeepSeek-V4-Pro
- button "模型选项 2"
- button "删除模型 2"
- button "添加模型"
- button "取消"
- button "保存"
@@ -30,11 +30,11 @@
- textbox "模型 ID 1":
- /placeholder: 模型 ID
- text: private-preview
- button "模型选项 1" [expanded]
- button "删除模型 1"
- textbox "显示名称 1":
- /placeholder: 显示名称
- text: Private Preview
- button "模型选项 1" [expanded]
- button "删除模型 1"
- text: 上下文窗口
- textbox "上下文窗口 1":
- /placeholder: 1M
@@ -0,0 +1,8 @@
# Discover toolbar responsive layout
- 390px: wrapped rows; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
- 430px: wrapped rows; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
- 768px: single row; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
- 1280px: single row; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.
At 390px, restoring the previous no-wrap layout causes horizontal overflow and fails the same layout check. Removing that override restores the controls and preserves search focus.
@@ -18,6 +18,7 @@
- button "Split" [disabled]
- text: {{cwd}}/workspace
- button "Reload"
- list:
- listitem:
- button "t6-refresh.txt"
- complementary "Workspace files":
- list:
- listitem:
- button "t6-refresh.txt"
@@ -21,5 +21,6 @@
- button "Split" [disabled]
- text: {{cwd}}/workspace
- button "Reload"
- list:
- listitem: Empty directory
- complementary "Workspace files":
- list:
- listitem: Empty directory
@@ -2,5 +2,6 @@
- button "Reload"
- button "Open in Finder"
- button "More ways to open"
- list:
- listitem: Empty directory
- complementary "Workspace files":
- list:
- listitem: Empty directory
@@ -0,0 +1,63 @@
/**
* The workspace file browser and the document preview each work without the
* other in the shipped Web composition: without the preview the files page
* lists the workspace and leaves files it cannot open unclickable; without the
* file browser a preview opens with no navigator or toggle beside it.
*/
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import { launchWebScaffold, seedSession, watchConsole, type WebScaffold } from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
/** A settled Session whose answer links `src/example.txt`, borrowed from the Markdown file links case. */
const SEED = fileURLToPath(new URL('../../../snapshots/web/markdown-file-links/session.v3.jsonl', import.meta.url))
/** Boot the composition with one plugin disabled, a workspace holding `src/example.txt`, and the seeded Session open. */
async function open(overlay: string, name: string) {
const scaffold: WebScaffold = await launchWebScaffold({ extraOverlayPath: fileURLToPath(new URL(overlay, import.meta.url)) })
onTestFinished(() => scaffold.close())
await mkdir(join(scaffold.workspaceCwd, 'src'))
await writeFile(join(scaffold.workspaceCwd, 'src/example.txt'), Array.from({ length: 40 }, (_, i) => `source line ${i + 1}\n`).join(''))
await seedSession(scaffold, await readFile(SEED, 'utf8'), name)
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const page = await newEnglishPage(browser)
onTestFailed(() => saveFailureShot(page, `web-e2e-${name}`))
const errors = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.locator('[role="treeitem"]').first().click()
await page.locator('[role="treeitem"]').nth(1).click()
await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).waitFor()
return { page, errors, column: page.locator('[data-rightbar-col]') }
}
it('lists the workspace without the document preview, leaving files nothing can open unclickable', async () => {
const { page, errors, column } = await open('./no-sidebar-documentpreview.overlay.yml', 'composition-no-preview')
await page.locator('[data-sidebar-right-expand]').click()
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
const navigator = column.locator('[data-files-navigator]')
await navigator.getByRole('button', { name: 'src', exact: true }).click()
const row = navigator.locator('[data-files-path$="/src/example.txt"]')
await row.waitFor()
expect(await row.locator('button').count()).toBe(0)
expect(await row.locator('[aria-disabled="true"]').getAttribute('title')).toBe('No viewer can open this file.')
const tabs = await column.locator('[data-dockkit-tab]').count()
await row.click()
expect(await column.locator('[data-dockkit-tab]').count()).toBe(tabs)
expect(await column.locator('[data-files-page]').count()).toBe(1)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
}, 120_000)
it('previews a linked file without the file browser, with no navigator or toggle beside it', async () => {
const { page, errors, column } = await open('./no-sidebar-files.overlay.yml', 'composition-no-files')
await page.getByRole('button', { name: 'src/example.txt:24–30', exact: true }).click()
await expect.poll(() => column.locator('[data-textpreview-target="24"]').textContent()).toBe('source line 24\n')
expect(await column.locator('[data-files-navigator], [data-files-navigator-toggle]').count()).toBe(0)
expect(await column.locator('[data-textpreview-content] > *').evaluateAll(children =>
children.map(child => child.hasAttribute('data-textpreview-body')))).toEqual([true])
expect(await column.locator('[data-sidebar-right-guide-entry="files"]').count()).toBe(0)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
}, 120_000)
+539
View File
@@ -0,0 +1,539 @@
/**
* The workspace file browser over the shipped Web composition, a real
* workspace and the real dock, across docked and floating panes and a
* phone-width viewport. The package README owns the behavior asserted here.
*/
import { mkdir, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator, type Page } from 'playwright'
import { expect, it, onTestFailed, onTestFinished } from 'vitest'
import { createLaunchEnvironmentSnapshot, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
import { connectFreshWorkspace, saveFailureShot } from './support.ts'
/** Press at the centre of `from`, travel in steps, and release at `to`. */
async function drag(page: Page, from: Locator, to: { x: number; y: number }): Promise<void> {
const box = await from.boundingBox()
if (box === null) throw new Error('drag source is not rendered')
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2)
await page.mouse.down()
await page.mouse.move(to.x, to.y, { steps: 12 })
await page.mouse.up()
}
/** Resize through the hit-tested corner, rather than dispatching events through covering content. */
async function resizeFloat(page: Page, panel: Locator, width: number, height: number): Promise<void> {
const before = await panel.boundingBox()
const handle = panel.locator('[data-dockkit-float-resize]')
const grip = await handle.boundingBox()
if (before === null || grip === null) throw new Error('floating resize geometry is not rendered')
await expect.poll(() => handle.evaluate((node) => {
const box = node.getBoundingClientRect()
return node.contains(document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2))
})).toBe(true)
await drag(page, handle, {
x: grip.x + grip.width / 2 + width - before.width,
y: grip.y + grip.height / 2 + height - before.height,
})
await expect.poll(async () => {
const after = await panel.boundingBox()
return after === null ? Infinity : Math.max(Math.abs(after.width - width), Math.abs(after.height - height))
}).toBeLessThanOrEqual(1)
}
/** Boot the shipped Web composition into a settled Session whose workspace holds `src/{a,b,c}.txt`, `README.md`, and `focus.html`. */
async function openWorkspace(
shot: string,
openInAppEnvironment?: LaunchEnvironmentSnapshot,
): Promise<{ page: Page; input: Locator; errors: ReturnType<typeof watchConsole> }> {
const scaffold = await launchWebScaffold({
replayFixture: fileURLToPath(new URL('../../../snapshots/web/lifecycle-chrome/session.v3.jsonl', import.meta.url)),
paceMs: 5, compareReplaySession: false, ...openInAppEnvironment === undefined ? {} : { openInAppEnvironment },
})
onTestFinished(() => scaffold.close())
const browser = await chromium.launch()
onTestFinished(() => browser.close())
const page = await browser.newPage({ locale: 'en-US', viewport: { width: 1680, height: 1000 } })
await page.addInitScript(() => { Object.defineProperty(navigator, 'platform', { value: 'Win32' }) })
onTestFailed(() => saveFailureShot(page, shot))
const errors = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await connectFreshWorkspace(page, scaffold.workspaceCwd, 'test workspace')
const settled = scaffold.whenTurnSettled()
const input = page.locator('[data-composer-input]').first()
await input.fill('Reply with the single word LIGHTHOUSE and stop.')
await input.press('Enter')
const session = await settled
const cwd = scaffold.ctx.agents.get(session)?.session.header.cwd
if (cwd === undefined) throw new Error('Session has no workspace')
await mkdir(join(cwd, 'src'))
const lines = (name: string): string => Array.from({ length: 300 }, (_, index) => `${name} line ${index}\n`).join('')
await writeFile(join(cwd, 'src', 'a.txt'), lines('a'))
await writeFile(join(cwd, 'src', 'b.txt'), lines('b'))
await writeFile(join(cwd, 'src', 'c.txt'), lines('c'))
await writeFile(join(cwd, 'README.md'), '# Readme\n')
await writeFile(join(cwd, 'focus.html'), '<!doctype html><button>Preview focus</button>')
await page.getByText('LIGHTHOUSE', { exact: true }).waitFor()
return { page, input, errors }
}
it('browses workspace files in tabs that share one pane tree', async () => {
const { page, input, errors } = await openWorkspace('web-e2e-file-browser')
await page.locator('[data-sidebar-right-expand]').click()
const column = page.locator('[data-rightbar-col]')
const layout = await page.addStyleTag({ content: '[data-sidebar-right-panel] { width: 960px !important; }' })
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
const tabs = column.locator('[data-dockkit-tab]')
const navigator = column.locator('[data-files-navigator]:visible')
const toggle = column.locator('[data-files-navigator-toggle]:visible')
const body = column.locator('[data-textpreview-state]:visible [data-textpreview-body]')
const path = column.locator('[data-textpreview-path]:visible')
const current = navigator.locator('[aria-current="true"]')
await column.locator('[data-files-page]').waitFor()
// The page's tree fills the page and stays shown: no toggle, no resize edge, and Escape leaves it.
await navigator.waitFor()
expect(await toggle.count()).toBe(0)
expect(await navigator.getByRole('separator').count()).toBe(0)
const pageContent = await column.locator('[data-files-content]').boundingBox()
const pageTree = await navigator.boundingBox()
if (pageContent === null || pageTree === null) throw new Error('files page geometry is not rendered')
expect(Math.abs(pageTree.width - pageContent.width)).toBeLessThanOrEqual(1)
await navigator.getByRole('button', { name: 'src', exact: true }).focus()
await page.keyboard.press('Escape')
expect(await navigator.count()).toBe(1)
const pageTab = await tabs.last().getAttribute('data-dockkit-tab')
const tabCount = await tabs.count()
// The page stays and opens the first file in a new tab after it in its pane, where the file's tree starts hidden.
await navigator.getByRole('button', { name: 'src', exact: true }).click()
await navigator.getByRole('button', { name: 'a.txt', exact: true }).click()
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await tabs.count()).toBe(tabCount + 1)
expect(await column.locator(`[data-dockkit-tab="${pageTab}"]`).count()).toBe(1)
expect(await column.locator('[data-dockkit-pane]').count()).toBe(1)
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
// Picking the open file again from the page switches back to its tab, which is the visible change, so nothing glows.
const flash = column.locator('[data-sidebar-right-flash]')
await column.locator(`[data-dockkit-tab="${pageTab}"]`).click()
await navigator.getByRole('button', { name: 'a.txt', exact: true }).click()
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await flash.count()).toBe(0)
expect(await tabs.count()).toBe(tabCount + 1)
// The preview's toggle shows the pane's tree without changing the files page.
await toggle.click()
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => current.textContent()).toBe('a.txt')
// Picking the open file again while its glow plays restarts the glow, which then lasts its whole 600ms animation.
const openFile = navigator.getByRole('button', { name: 'a.txt', exact: true })
await openFile.click()
// A glow replaced before it starts is dropped without a cancellation, so the repeat waits until the first one plays.
await expect.poll(() => flash.evaluate(pane => pane.getAnimations({ subtree: true })
.some(glow => Number(glow.currentTime) > 100))).toBe(true)
const first = await flash.getAttribute('data-sidebar-right-flash')
const repeat = await openFile.evaluate((button) => {
const pane = button.closest<HTMLElement>('[data-sidebar-right-flash]')
if (pane === null) throw new Error('the open file is outside the glowing pane')
const since = performance.now()
return new Promise<{ mark: string | undefined; lasted: number }>((resolve) => {
let mark: string | undefined
new MutationObserver((_, observer) => {
mark = pane.dataset.sidebarRightFlash ?? mark
if (pane.dataset.sidebarRightFlash !== undefined) return
observer.disconnect()
resolve({ mark, lasted: performance.now() - since })
}).observe(pane, { attributes: true, attributeFilter: ['data-sidebar-right-flash'] })
;(button as HTMLElement).click()
})
})
expect(repeat.mark).toBe(first === 'odd' ? 'even' : 'odd')
expect(repeat.lasted).toBeGreaterThan(450)
// In a wide row the tree is a card beside the preview: the body narrows by the card and its 8px margins, and still scrolls.
await column.locator('[data-files-navigator-mode="push"]:visible').waitFor()
const wideRow = await body.locator('..').boundingBox()
const wideBody = await body.boundingBox()
const wideTree = await navigator.boundingBox()
if (wideRow === null || wideBody === null || wideTree === null) throw new Error('preview row is not rendered')
expect(Math.abs(wideBody.width - (wideRow.width - wideTree.width - 16))).toBeLessThanOrEqual(1)
expect(wideTree.x).toBeGreaterThanOrEqual(wideBody.x + wideBody.width + 7)
await expect.poll(() => body.evaluate(node => node.scrollHeight > node.clientHeight)).toBe(true)
await page.mouse.move(wideBody.x + 40, wideBody.y + 80)
await page.mouse.wheel(0, 400)
await expect.poll(() => body.evaluate(node => node.scrollTop)).toBeGreaterThan(0)
// A press on the preview leaves the tree shown.
await page.mouse.click(wideBody.x + 40, wideBody.y + 80)
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
await toggle.focus()
// In dark mode the card takes the filled tree's background, with a soft white shadow.
const theme = await page.locator('body').getAttribute('data-ds-dark-theme')
try {
await page.evaluate(() => { document.body.setAttribute('data-ds-dark-theme', '') })
const cardPaint = await navigator.evaluate(node => ({
background: getComputedStyle(node).backgroundColor,
shadow: getComputedStyle(node).boxShadow,
}))
expect(cardPaint.shadow).toContain('color(srgb 1 1 1 / 0.08)')
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 360px !important; }' })
await column.locator('[data-files-navigator-mode="fill"]:visible').waitFor()
expect(await navigator.evaluate(node => getComputedStyle(node).backgroundColor)).toBe(cardPaint.background)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
await navigator.getByRole('separator').waitFor()
} finally {
await page.evaluate((value) => {
if (value === null) document.body.removeAttribute('data-ds-dark-theme')
else document.body.setAttribute('data-ds-dark-theme', value)
}, theme)
}
// The reader scrolls the preview and widens the tree.
await body.evaluate((node) => { node.scrollTop = 900 })
const edge = navigator.getByRole('separator', { name: 'Resize file tree' })
const grip = await edge.boundingBox()
if (grip === null) throw new Error('resize edge is not rendered')
await page.mouse.move(grip.x + grip.width / 2, grip.y + 120)
await page.mouse.down()
await page.mouse.move(grip.x + grip.width / 2 - 40, grip.y + 120, { steps: 4 })
await page.mouse.up()
await expect.poll(() => edge.getAttribute('aria-valuenow')).toBe('300')
// The files page appends another preview; it shares the pane's tree choice and width.
await column.locator(`[data-dockkit-tab="${pageTab}"]`).click()
await navigator.getByRole('button', { name: 'b.txt', exact: true }).click()
await column.locator(`[data-dockkit-tab="${pageTab}"]`).hover()
await column.locator(`[data-dockkit-tab-close="${pageTab}"]`).click()
await expect.poll(() => path.textContent()).toContain('b.txt')
expect(await tabs.count()).toBe(tabCount + 1)
await expect.poll(() => current.textContent()).toBe('b.txt')
expect(await navigator.getByRole('button', { name: 'src', exact: true }).getAttribute('aria-expanded')).toBe('true')
expect(await edge.getAttribute('aria-valuenow')).toBe('300')
// Clicking an open file returns to its tab, where the reader left off.
await navigator.getByRole('button', { name: 'a.txt', exact: true }).click()
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await tabs.count()).toBe(tabCount + 1)
await expect.poll(() => body.evaluate(node => node.scrollTop)).toBe(900)
await expect.poll(() => current.textContent()).toBe('a.txt')
// Workspace navigation has one open action; the row's shared context menu does not offer a second new-tab route.
await navigator.getByRole('button', { name: 'a.txt', exact: true }).click({ button: 'right' })
const rowMenu = page.locator('[data-context-menu][role="menu"]')
await rowMenu.waitFor()
expect(await page.getByRole('menuitem', { name: 'Open in new tab', exact: true }).count()).toBe(0)
await page.keyboard.press('Escape')
await rowMenu.waitFor({ state: 'detached' })
// A narrower pane floats the tree over the preview below its header; the body keeps the row's width and still scrolls.
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 460px !important; }' })
await column.locator('[data-files-navigator-mode="overlay"]:visible').waitFor()
const header = await path.locator('..').boundingBox()
const tree = await navigator.boundingBox()
if (header === null || tree === null) throw new Error('browser geometry is not rendered')
expect(tree.y).toBeGreaterThanOrEqual(header.y + header.height - 1)
const middleRow = await body.locator('..').boundingBox()
const preview = await body.boundingBox()
if (middleRow === null || preview === null) throw new Error('preview body is not rendered')
expect(preview.width).toBeGreaterThan(middleRow.width - 1)
await body.evaluate((node) => { node.scrollTop = 0 })
await page.mouse.move(preview.x + 20, preview.y + 80)
await page.mouse.wheel(0, 400)
await expect.poll(() => body.evaluate(node => node.scrollTop)).toBeGreaterThan(0)
await navigator.getByRole('button', { name: 'b.txt', exact: true }).click()
await expect.poll(() => current.textContent()).toBe('b.txt')
// The keyboard stays in the tree the revealed tab draws, so Escape reaches the row.
await expect.poll(() => current.evaluate(node => node === document.activeElement)).toBe(true)
await page.keyboard.press('Escape')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('false')
expect(await navigator.count()).toBe(0)
expect(await toggle.evaluate(node => node === document.activeElement)).toBe(true)
// A row narrower than 400px is filled by the tree, without the resize edge; Escape still closes it.
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 360px !important; }' })
await toggle.click()
await column.locator('[data-files-navigator-mode="fill"]:visible').waitFor()
const narrowRow = await body.locator('..').boundingBox()
const narrowTree = await navigator.boundingBox()
if (narrowRow === null || narrowTree === null) throw new Error('narrow geometry is not rendered')
expect(Math.abs(narrowTree.width - narrowRow.width)).toBeLessThanOrEqual(1)
expect(await navigator.getByRole('separator').count()).toBe(0)
expect(await body.evaluate(node => getComputedStyle(node).visibility)).toBe('hidden')
await toggle.focus()
await page.keyboard.press('Tab')
expect(await body.evaluate(node => node.contains(document.activeElement))).toBe(false)
expect(await navigator.evaluate(node => node.contains(document.activeElement))).toBe(true)
await navigator.getByRole('button', { name: 'b.txt', exact: true }).focus()
await page.keyboard.press('Escape')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('false')
// A phone-width viewport fills the row below the header with the tree, without the resize edge, and opening a file hides it.
// The resize edge holding the keyboard when the viewport narrows hands it to the tree.
await layout.evaluate((node) => { node.textContent = '' })
await toggle.click()
const resizeEdge = navigator.getByRole('separator', { name: 'Resize file tree' })
await resizeEdge.focus()
expect(await resizeEdge.evaluate(node => node === document.activeElement)).toBe(true)
await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(() => navigator.evaluate(node => node.contains(document.activeElement)
&& !document.activeElement?.hasAttribute('data-files-navigator-resize'))).toBe(true)
// The panel slides into its fullscreen place, so the geometry is read once it settles.
await expect.poll(async () => {
const row = await body.locator('..').boundingBox()
const filled = await navigator.boundingBox()
return row === null || filled === null ? Number.POSITIVE_INFINITY : Math.abs(filled.width - row.width)
}).toBeLessThanOrEqual(1)
expect(await navigator.getByRole('separator').count()).toBe(0)
await navigator.getByRole('button', { name: 'a.txt', exact: true }).click()
await expect.poll(() => path.textContent()).toContain('a.txt')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('false')
expect(await navigator.count()).toBe(0)
await page.setViewportSize({ width: 1680, height: 1000 })
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 460px !important; }' })
// The workspace command shows the pane's tree, moves the keyboard into it, and keeps the file.
await input.focus()
await page.keyboard.press('Control+Alt+p')
await expect.poll(() => toggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => current.evaluate(node => node === document.activeElement)).toBe(true)
await expect.poll(() => path.textContent()).toContain('a.txt')
expect(await tabs.count()).toBe(tabCount + 1)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
await column.locator('[data-dockkit-add-tab]').click()
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
const htmlFilesTab = await tabs.filter({ hasText: 'Files' }).getAttribute('data-dockkit-tab')
await navigator.getByRole('button', { name: 'focus.html', exact: true }).click()
await column.locator(`[data-dockkit-tab="${htmlFilesTab}"]`).hover()
await column.locator(`[data-dockkit-tab-close="${htmlFilesTab}"]`).click()
await expect.poll(() => path.textContent()).toContain('focus.html')
const frame = body.locator('[data-html-preview]')
await frame.waitFor()
for (const narrow of ['row', 'viewport'] as const) {
await toggle.focus()
if (narrow === 'row') await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 360px !important; }' })
else await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(() => body.evaluate(node => getComputedStyle(node).visibility)).toBe('hidden')
await page.keyboard.press('Tab')
expect(await navigator.evaluate(node => node.contains(document.activeElement))).toBe(true)
expect(await body.evaluate(node => node.contains(document.activeElement))).toBe(false)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
await page.setViewportSize({ width: 1680, height: 1000 })
await expect.poll(() => body.evaluate(node => getComputedStyle(node).visibility)).toBe('visible')
await frame.focus()
if (narrow === 'row') await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 360px !important; }' })
else await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(() => body.evaluate(node => getComputedStyle(node).visibility)).toBe('hidden')
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
await expect.poll(() => navigator.evaluate(node => node.contains(document.activeElement))).toBe(true)
expect(await frame.evaluate(node => document.activeElement === node)).toBe(false)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
await page.setViewportSize({ width: 1680, height: 1000 })
await expect.poll(() => body.evaluate(node => getComputedStyle(node).visibility)).toBe('visible')
}
// A preview dragged out into a floating panel keeps where the reader was in it.
await tabs.filter({ hasText: 'b.txt' }).click()
await expect.poll(() => path.textContent()).toContain('b.txt')
await body.evaluate((node) => { node.scrollTop = 600 })
await expect.poll(() => body.evaluate(node => node.scrollTop)).toBe(600)
const surface = await page.locator('[data-dockkit-surface]').first().boundingBox()
if (surface === null) throw new Error('surface is not rendered')
await drag(page, tabs.filter({ hasText: 'b.txt' }), { x: surface.x - 240, y: surface.y + surface.height / 2 })
const float = page.locator('[data-sidebar-right-session]:not([hidden]) [data-dockkit-float]')
await expect.poll(() => float.count()).toBe(1)
const floatPath = float.locator('[data-textpreview-path]')
await floatPath.waitFor()
const floatBody = float.locator('[data-textpreview-state] [data-textpreview-body]')
await expect.poll(() => floatBody.evaluate(node => node.scrollTop)).toBe(600)
// The panel is a new pane, so its tree starts hidden; shown, it draws there too, and the panel keeps its resize handle.
const floatToggle = float.locator('[data-files-navigator-toggle]')
expect(await floatToggle.getAttribute('aria-expanded')).toBe('false')
expect(await float.locator('[data-files-navigator]').count()).toBe(0)
await floatToggle.click()
const before = await float.boundingBox()
if (before === null) throw new Error('float is not rendered')
const resize = float.locator('[data-dockkit-float-resize]')
await drag(page, resize, { x: before.x + Math.max(before.width + 80, 560), y: before.y + before.height + 60 })
await expect.poll(async () => (await float.boundingBox())?.width ?? before.width).toBeGreaterThan(before.width)
// Wide enough that the tree does not fill the panel.
expect((await float.boundingBox())!.width).toBeGreaterThanOrEqual(440)
const floatTree = float.locator('[data-files-navigator]')
await floatTree.waitFor()
expect(await floatToggle.getAttribute('aria-expanded')).toBe('true')
// Resize while the tree is open, through both sides of its fill breakpoint.
const openBox = await float.boundingBox()
if (openBox === null) throw new Error('floating preview is not rendered')
await resizeFloat(page, float, 360, openBox.height - 20)
await float.locator('[data-files-navigator-mode="fill"]').waitFor()
await resizeFloat(page, float, 560, openBox.height)
expect(await floatTree.count()).toBe(1)
const floatPane = await float.getAttribute('data-dockkit-float')
// A file nothing shows replaces the preview in its panel, which keeps its pane and its tree.
await floatTree.getByRole('button', { name: 'README.md', exact: true }).click()
await expect.poll(() => floatPath.textContent()).toContain('README.md')
expect(await float.count()).toBe(1)
expect(await float.getAttribute('data-dockkit-float')).toBe(floatPane)
expect(await float.locator('[data-files-navigator] [aria-current="true"]').textContent()).toBe('README.md')
// Navigating to the floating preview itself exposes its file when its tree fills the row.
const previewHeight = (await float.boundingBox())!.height
await resizeFloat(page, float, 360, previewHeight)
await float.locator('[data-files-navigator-mode="fill"]').waitFor()
await floatTree.getByRole('button', { name: 'README.md', exact: true }).click()
await expect.poll(() => floatToggle.getAttribute('aria-expanded')).toBe('false')
await expect.poll(() => floatToggle.evaluate(node => node === document.activeElement)).toBe(true)
await floatToggle.click()
await floatTree.waitFor()
// A file already shown is revealed in the column, which first shows another tab; the panel keeps its file.
// Revealing b.txt opened `src`.
const shown = column.locator('[data-dockkit-tab][aria-selected="true"]')
await column.locator('[data-dockkit-add-tab]').click()
await expect.poll(() => shown.textContent()).not.toContain('a.txt')
const guide = await shown.getAttribute('data-dockkit-tab')
const dockedTabs = await tabs.count()
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 360px !important; }' })
const sourceFile = floatTree.getByRole('button', { name: 'a.txt', exact: true })
await sourceFile.click()
await expect.poll(() => shown.textContent()).toContain('a.txt')
const dockPreview = column.locator('[data-dockkit-pane] [data-textpreview-state]:visible')
await expect.poll(() => dockPreview.locator('[data-files-navigator-toggle]').getAttribute('aria-expanded')).toBe('false')
expect(await dockPreview.locator('[data-textpreview-body]').evaluate(node => getComputedStyle(node).visibility)).toBe('visible')
expect(await floatToggle.getAttribute('aria-expanded')).toBe('true')
expect(await sourceFile.evaluate(node => node === document.activeElement)).toBe(true)
await layout.evaluate((node) => { node.textContent = '[data-sidebar-right-panel] { width: 960px !important; }' })
await resizeFloat(page, float, 560, previewHeight)
expect(await tabs.count()).toBe(dockedTabs)
expect(await floatPath.textContent()).toContain('README.md')
expect(await float.count()).toBe(1)
expect(await tabs.filter({ hasText: 'a.txt' }).count()).toBe(1)
// The column offers a new tab again only once its guide closes.
await column.locator(`[data-dockkit-tab="${guide}"]`).hover()
await column.locator(`[data-dockkit-tab-close="${guide}"]`).click()
await expect.poll(() => column.locator(`[data-dockkit-tab="${guide}"]`).count()).toBe(0)
// A floating files page stays and opens a file nothing shows in the active docked pane.
await column.locator('[data-dockkit-add-tab]').click()
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
await column.locator('[data-files-page]').waitFor()
await drag(page, tabs.filter({ hasText: 'Files' }), { x: surface.x - 240, y: surface.y + 120 })
await expect.poll(() => float.count()).toBe(2)
const pageFloat = float.filter({ has: page.locator('[data-files-page]') })
const filePageBox = await pageFloat.boundingBox()
if (filePageBox === null) throw new Error('floating files page is not rendered')
await resizeFloat(page, pageFloat, 360, filePageBox.height - 20)
await page.setViewportSize({ width: 390, height: 844 })
const phoneBox = await pageFloat.boundingBox()
if (phoneBox === null) throw new Error('phone-width files page is not rendered')
await resizeFloat(page, pageFloat, 340, phoneBox.height - 20)
expect(await pageFloat.locator('[data-files-navigator]').count()).toBe(1)
await page.setViewportSize({ width: 1680, height: 1000 })
const docked = await tabs.count()
await pageFloat.getByRole('button', { name: 'src', exact: true }).click()
await pageFloat.getByRole('button', { name: 'c.txt', exact: true }).click()
await column.locator('[data-textpreview-path]:visible', { hasText: 'c.txt' }).waitFor()
expect(await pageFloat.count()).toBe(1)
expect(await float.count()).toBe(2)
expect(await column.locator('[data-dockkit-pane]').count()).toBe(1)
expect(await tabs.count()).toBe(docked + 1)
// A file already shown is revealed in the column, and the floating page stays with its tree.
await pageFloat.getByRole('button', { name: 'a.txt', exact: true }).click()
await expect.poll(() => column.locator('[data-dockkit-pane-active] [data-dockkit-tab][aria-selected="true"]').textContent()).toContain('a.txt')
expect(await pageFloat.count()).toBe(1)
expect(await pageFloat.locator('[data-files-navigator]').count()).toBe(1)
expect(await float.count()).toBe(2)
expect(await tabs.count()).toBe(docked + 1)
// With the docked area emptied and the column collapsed, a file from the floating page gets a docked pane in the expanded column.
const dockTabs = column.locator('[data-dockkit-pane] [data-dockkit-tab]')
while (await dockTabs.count() > 0) {
const id = await dockTabs.first().getAttribute('data-dockkit-tab')
await dockTabs.first().hover()
await column.locator(`[data-dockkit-tab-close="${id}"]`).click()
await expect.poll(() => column.locator(`[data-dockkit-tab="${id}"]`).count()).toBe(0)
}
const expand = page.locator('[data-sidebar-right-expand]')
await expand.waitFor()
expect(await pageFloat.count()).toBe(1)
await pageFloat.getByRole('button', { name: 'b.txt', exact: true }).click()
await column.locator('[data-textpreview-path]:visible', { hasText: 'b.txt' }).waitFor()
// Past the column's slide, it stays open with the file's tab alone: no default page beside it.
await expect.poll(() => column.evaluate(node => node.getAnimations({ subtree: true })
.filter(animation => animation.playState === 'running').length)).toBe(0)
expect(await expand.count()).toBe(0)
expect(await column.locator('[data-dockkit-pane]').count()).toBe(1)
expect(await dockTabs.count()).toBe(1)
expect(await dockTabs.first().textContent()).toContain('b.txt')
expect(await column.locator('[data-sidebar-right-guide-entry]').count()).toBe(0)
expect((await column.boundingBox())?.width ?? 0).toBeGreaterThan(200)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
})
it('moves a file between the docked column and a floating panel from the file menu, keeping its reading position', async () => {
// The file menu's open actions belong to Open In, which ordinary scenarios leave out; remote launch facts suppress native probes.
const { page, errors } = await openWorkspace('web-e2e-file-browser-destination',
createLaunchEnvironmentSnapshot([{ source: 'process', values: { SSH_CONNECTION: '10.0.0.2 55000 10.0.0.9 22' } }]))
const column = page.locator('[data-rightbar-col]')
const expand = page.locator('[data-sidebar-right-expand]')
const float = page.locator('[data-sidebar-right-session]:not([hidden]) [data-dockkit-float]')
const docked = (name: string) => column.locator('[data-dockkit-pane] [data-dockkit-tab]', { hasText: name })
const menu = page.locator('[data-context-menu][role="menu"]')
// The files page floats and the column collapses, so every later open starts from a floating source pane.
await expand.click()
await column.locator('[data-sidebar-right-guide-entry="files"]').click()
await column.locator('[data-files-page]').waitFor()
const surface = await page.locator('[data-dockkit-surface]').first().boundingBox()
if (surface === null) throw new Error('surface is not rendered')
await drag(page, column.locator('[data-dockkit-tab]', { hasText: 'Files' }), { x: surface.x - 240, y: surface.y + 120 })
await expect.poll(() => float.count()).toBe(1)
await column.locator('[data-sidebar-right-toggle]').click()
await expand.waitFor()
const pageFloat = float.filter({ has: page.locator('[data-files-page]') })
await pageFloat.getByRole('button', { name: 'src', exact: true }).click()
const row = pageFloat.getByRole('button', { name: 'a.txt', exact: true })
const choose = async (item: string): Promise<void> => {
await row.click({ button: 'right' })
await menu.waitFor()
await menu.getByRole('menuitem', { name: item, exact: true }).click()
await menu.waitFor({ state: 'detached' })
}
await row.click({ button: 'right' })
await menu.getByRole('menuitem', { name: 'Open in floating panel', exact: true }).waitFor()
expect(await menu.getByRole('menuitem', { name: 'Open in sidebar', exact: true }).count()).toBe(1)
await page.keyboard.press('Escape')
await menu.waitFor({ state: 'detached' })
// A file nothing shows opens in its own floating panel; the collapsed column stays collapsed.
await choose('Open in floating panel')
await expect.poll(() => float.count()).toBe(2)
const fileFloat = float.filter({ has: page.locator('[data-textpreview-path]', { hasText: 'a.txt' }) })
const floatBody = fileFloat.locator('[data-textpreview-state] [data-textpreview-body]')
await floatBody.waitFor()
expect(await expand.count()).toBe(1)
expect(await docked('a.txt').count()).toBe(0)
await expect.poll(() => floatBody.evaluate(node => node.scrollHeight > node.clientHeight)).toBe(true)
await floatBody.evaluate((node) => { node.scrollTop = 600 })
await expect.poll(() => floatBody.evaluate(node => node.scrollTop)).toBe(600)
// Asking again reveals that panel rather than adding one.
await choose('Open in floating panel')
expect(await float.count()).toBe(2)
expect(await fileFloat.count()).toBe(1)
expect(await expand.count()).toBe(1)
// The floating file moves into the expanded column, where the reader left off.
await choose('Open in sidebar')
await expect.poll(() => fileFloat.count()).toBe(0)
expect(await float.count()).toBe(1)
await expect.poll(() => expand.count()).toBe(0)
await expect.poll(() => docked('a.txt').count()).toBe(1)
const dockBody = column.locator('[data-dockkit-pane] [data-textpreview-state]:visible [data-textpreview-body]')
await expect.poll(() => dockBody.evaluate(node => node.scrollTop)).toBe(600)
// And back out into a floating panel, leaving the column open and its strip without the file.
await choose('Open in floating panel')
await expect.poll(() => fileFloat.count()).toBe(1)
expect(await float.count()).toBe(2)
await expect.poll(() => docked('a.txt').count()).toBe(0)
expect(await expand.count()).toBe(0)
await expect.poll(() => floatBody.evaluate(node => node.scrollTop)).toBe(600)
expect(errors).toEqual({ warnings: [], pageErrors: [] })
})
@@ -0,0 +1,19 @@
{
"format": 1,
"title": { "en": "Awesome DSH Plugin", "zh": "Awesome DSH Plugin 插件精选" },
"metadata": {
"categories": { "tools": { "title": { "en": "Tools", "zh": "工具与能力" } } },
"labels": { "featured": { "title": { "en": "Featured", "zh": "精选" } } }
},
"plugins": [
{
"name": "dsh-toolbar-layout-fixture",
"title": { "en": "Toolbar layout fixture", "zh": "工具栏布局示例" },
"description": { "en": "A local index for responsive toolbar checks.", "zh": "用于工具栏响应式检查的本地索引" },
"metadata": { "category": "tools", "labels": ["featured"] },
"versions": [
{ "version": "1.0.0", "publishTimestamp": 1793145600, "source": { "type": "npm" } }
]
}
]
}
+72 -21
View File
@@ -1,37 +1,88 @@
/** Model input types stay below both capacity fields across editor widths. */
/** Model identity, capacity and input-type fields follow the model row's available width. */
import type { Locator, Page } from 'playwright'
import { expect } from 'vitest'
/**
* Verify the expanded row at the current viewport and a narrow viewport.
* Verify expanded identity fields, capacity fields and input types across viewport and row-width boundaries.
* @param page - page with an explicit viewport, restored even when an assertion fails.
* @param editor - expanded model editor containing the capacity and input-type fields.
* @returns after checking both widths and restoring the caller's size.
* @param editor - expanded model editor containing the first model's identity, capacity and input-type fields.
* @returns after checking all widths and restoring the caller's size.
*/
export async function assertModelInputLayout(page: Page, editor: Locator): Promise<void> {
const original = page.viewportSize()
if (original === null) throw new Error('Model input layout checks require an explicit viewport')
const drawerCount = await page.locator('[data-sidebar-drawer]').count()
const entry = editor.locator('[data-row-key]').first()
const originalStyle = await entry.getAttribute('style')
const check = async (): Promise<void> => {
const id = await editor.getByLabel('模型 ID 1', { exact: true }).boundingBox()
const name = await editor.getByRole('textbox', { name: '显示名称 1', exact: true }).boundingBox()
const context = await editor.getByLabel('上下文窗口 1', { exact: true }).boundingBox()
const output = await editor.getByLabel('最大输出 token 数 1', { exact: true }).boundingBox()
const types = await editor.getByRole('group', { name: '输入类型 1' }).boundingBox()
if (id === null || name === null || context === null || output === null || types === null) {
throw new Error('Expanded model fields are not visible')
}
const geometry = await entry.evaluate((element) => {
const style = getComputedStyle(element)
const row = element.firstElementChild!
return {
contentWidth: element.getBoundingClientRect().width - Number.parseFloat(style.paddingLeft)
- Number.parseFloat(style.paddingRight) - Number.parseFloat(style.borderLeftWidth) - Number.parseFloat(style.borderRightWidth),
rowWidth: row.getBoundingClientRect().width,
gap: Number.parseFloat(getComputedStyle(row).columnGap),
buttons: [...row.querySelectorAll(':scope > button')].map(button => button.getBoundingClientRect().width),
}
})
expect(Math.abs(context.y - output.y)).toBeLessThan(1)
expect(types.y).toBeGreaterThanOrEqual(Math.max(context.y + context.height, output.y + output.height))
expect(types.width).toBeGreaterThan(context.width)
if (geometry.contentWidth <= 440) {
expect(name.y).toBeGreaterThanOrEqual(id.y + id.height)
expect(name.width).toBeGreaterThan(id.width)
expect(context.y).toBeGreaterThanOrEqual(name.y + name.height)
expect(geometry.buttons).toHaveLength(3)
const available = geometry.rowWidth - geometry.buttons.reduce((sum, width) => sum + width, 0) - 3 * geometry.gap
expect(Math.abs(id.width - available)).toBeLessThan(1)
} else {
expect(Math.abs(id.y - name.y)).toBeLessThan(1)
expect(name.x).toBeGreaterThanOrEqual(id.x + id.width)
}
const overflowing = await editor.getByRole('region', { name: '模型目录', exact: true }).evaluate((region) => {
const widths = []
for (let element: Element | null = region; element !== null; element = element.parentElement) {
if (element === region || /auto|scroll/.test(getComputedStyle(element).overflowY)) {
widths.push({ width: element.clientWidth, scroll: element.scrollWidth })
}
if (element.getAttribute('role') === 'dialog') break
}
return widths.filter(({ width, scroll }) => scroll > width)
})
expect(overflowing).toEqual([])
}
try {
for (const viewport of [original, { width: 760, height: 1000 }]) {
for (const viewport of [original, { width: 760, height: 1000 }, { width: 390, height: 844 }]) {
await page.setViewportSize(viewport)
const context = await editor.getByLabel('上下文窗口 1', { exact: true }).boundingBox()
const output = await editor.getByLabel('最大输出 token 数 1', { exact: true }).boundingBox()
const types = await editor.getByRole('group', { name: '输入类型 1' }).boundingBox()
expect(context).not.toBeNull()
expect(output).not.toBeNull()
expect(types).not.toBeNull()
if (context === null || output === null || types === null) throw new Error('Expanded model fields are not visible')
expect(Math.abs(context.y - output.y)).toBeLessThan(1)
expect(types.y).toBeGreaterThanOrEqual(Math.max(context.y + context.height, output.y + output.height))
expect(types.width).toBeGreaterThan(context.width)
await check()
}
await page.setViewportSize({ width: 1680, height: 1000 })
for (const width of [440, 441]) {
await entry.evaluate((element, width) => {
element.style.boxSizing = 'content-box'
element.style.width = `${String(width)}px`
}, width)
await check()
}
} 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)
try {
await entry.evaluate((element, originalStyle) => {
if (originalStyle === null) element.removeAttribute('style')
else element.setAttribute('style', originalStyle)
}, originalStyle)
} finally {
await page.setViewportSize(original)
// The shell's ResizeObserver must restore its original drawer posture before the next capture.
await expect.poll(async () => page.locator('[data-sidebar-drawer]').count(), { timeout: 5_000 }).toBe(drawerCount)
}
}
}
+147 -1
View File
@@ -26,7 +26,7 @@ import {
assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
launchWebScaffold, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { openSettings, ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
import { expectTooltipOnTop, openSettings, ZH_BROWSER_LOCALE, saveFailureShot } from './support.ts'
const SNAPSHOT_DIR = fileURLToPath(new URL('./expected/models-settings', import.meta.url))
const EMPTY_EXPECTED = join(SNAPSHOT_DIR, 'empty.expected.md')
@@ -576,6 +576,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
return { x: rect.left + 20, y: rect.bottom + 4 }
})
await page.mouse.move(insertion.x, insertion.y, { steps: 3 })
expect(await dialog.locator('[data-drop-target]').evaluate(element => getComputedStyle(element).zIndex)).toBe('1')
await page.mouse.up()
await page.locator('body > div[inert][aria-hidden="true"]:has(button[aria-label^="调整模型顺序 "])').waitFor({ state: 'detached' })
await expect.poll(() => dialog.getByLabel(`模型 ID ${save ? '3' : '2'}`, { exact: true }).inputValue()).toBe('acme-large')
@@ -603,7 +604,21 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
const viewport = page.viewportSize()
if (viewport === null) throw new Error('Model ordering checks require an explicit viewport')
try {
const id = dialog.getByRole('textbox', { name: '模型 ID 1', exact: true })
const name = dialog.getByRole('textbox', { name: '显示名称 1', exact: true })
const toggle = dialog.getByRole('button', { name: '模型选项 1', exact: true })
const desktopId = await id.boundingBox()
const desktopName = await name.boundingBox()
if (desktopId === null || desktopName === null) throw new Error('Wide model identity fields are not visible')
expect(Math.abs(desktopId.y - desktopName.y)).toBeLessThan(1)
await name.focus()
await page.setViewportSize({ width: 390, height: 844 })
expect(await name.evaluate(input => input.ownerDocument.activeElement === input)).toBe(true)
expect(await name.isVisible()).toBe(true)
await toggle.click()
await name.waitFor({ state: 'hidden' })
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'mobile-collapsed.expected.md'),
await captureStableAria(page, '[data-shortcut-modal="settings"]', scaffold.workspaceCwd), MODE)
for (const name of ['调整模型顺序 1', '模型选项 1', '删除模型 1']) {
const box = await dialog.getByRole('button', { name, exact: true }).boundingBox()
expect(box).not.toBeNull()
@@ -611,6 +626,24 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
expect(box.x).toBeGreaterThanOrEqual(0)
expect(box.x + box.width).toBeLessThanOrEqual(390)
}
const compactId = await id.boundingBox()
if (compactId === null) throw new Error('Narrow model ID is not visible')
await toggle.click()
await name.waitFor({ state: 'visible' })
await name.fill('手机上的完整显示名称')
await toggle.click()
await name.waitFor({ state: 'hidden' })
expect(await id.inputValue()).toBe('order-second')
await toggle.click()
expect(await name.inputValue()).toBe('手机上的完整显示名称')
const expandedName = await name.boundingBox()
if (expandedName === null) throw new Error('Expanded model name is not visible')
expect(expandedName.y).toBeGreaterThanOrEqual(compactId.y + compactId.height)
expect(expandedName.width).toBeGreaterThan(compactId.width)
expect(await dialog.getByRole('region', { name: '模型目录', exact: true })
.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await compareOrRefreshGolden(join(SNAPSHOT_DIR, 'mobile-expanded.expected.md'),
await captureStableAria(page, '[data-shortcut-modal="settings"]', scaffold.workspaceCwd), MODE)
} finally {
await page.setViewportSize(viewport)
}
@@ -618,6 +651,118 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
expect(tripwire.pageErrors).toEqual([])
})
it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])(
'keeps mobile model actions, focus and keyboard order in $name', async ({ name: engineName, engine }) => {
const provider = `review-${engineName.toLowerCase()}`
let mobileBrowser: Browser | undefined
try {
await scaffold.ctx.settings.mutate('llm-pi-ai', [{
op: 'set', path: ['providers', provider], value: {
api: 'anthropic-messages', baseURL: 'https://layout.example',
models: [{ id: 'layout-model', name: '完整显示名称' }, { id: 'next-model', name: '下一模型' }],
},
}])
mobileBrowser = await engine.launch()
const mobilePage = await mobileBrowser.newPage({ viewport: { width: 1680, height: 1000 }, locale: ZH_BROWSER_LOCALE })
const errors = watchConsole(mobilePage)
onTestFailed(() => saveFailureShot(mobilePage, `web-e2e-models-mobile-${engineName.toLowerCase()}`))
await mobilePage.goto(scaffold.authenticatedUrl)
await openSettings(mobilePage, 'zh')
const dialog = mobilePage.getByRole('dialog', { name: '设置' })
await dialog.getByRole('button', { name: '模型', exact: true }).click()
const edit = dialog.getByRole('button', { name: `编辑 ${provider}`, exact: true })
await edit.click()
await dialog.getByText('自定义设置').click()
const id = dialog.getByRole('textbox', { name: '模型 ID 1', exact: true })
const name = dialog.getByRole('textbox', { name: '显示名称 1', exact: true })
const toggle = dialog.getByRole('button', { name: '模型选项 1', exact: true })
const nextToggle = dialog.getByRole('button', { name: '模型选项 2', exact: true })
await toggle.click()
await assertModelInputLayout(mobilePage, dialog)
await dialog.getByRole('button', { name: '调整模型顺序 1', exact: true }).hover()
const tooltip = mobilePage.getByRole('tooltip')
await tooltip.waitFor()
expect(await tooltip.evaluate(element => element.parentElement === element.ownerDocument.body)).toBe(true)
await expectTooltipOnTop(tooltip)
await id.hover()
await tooltip.waitFor({ state: 'hidden' })
await toggle.click()
await name.fill('缩窄后继续编辑')
const input = await name.elementHandle()
if (input === null) throw new Error('Model name input is missing')
await mobilePage.setViewportSize({ width: 390, height: 844 })
expect(await input.evaluate(element => element.isConnected && element.ownerDocument.activeElement === element)).toBe(true)
await nextToggle.click()
expect(await nextToggle.getAttribute('aria-expanded')).toBe('true')
expect(await toggle.getAttribute('aria-expanded')).toBe('true')
await nextToggle.click()
await name.fill('手机保存后的名称')
await dialog.getByRole('button', { name: '保存', exact: true }).click()
await id.waitFor({ state: 'detached' })
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'llm-pi-ai')?.value).toMatchObject({
providers: { [provider]: { models: [{ id: 'layout-model', name: '手机保存后的名称' }, { id: 'next-model', name: '下一模型' }] } },
})
await dialog.getByText(`已保存 ${provider}。`, { exact: true }).waitFor()
await edit.click()
await dialog.getByText('自定义设置').click()
await name.waitFor({ state: 'hidden' })
await toggle.focus()
await mobilePage.keyboard.press('Enter')
const tab = engine === webkit ? 'Alt+Tab' : 'Tab'
await mobilePage.keyboard.press(tab)
expect(await dialog.getByRole('button', { name: '删除模型 1', exact: true })
.evaluate(button => button.ownerDocument.activeElement === button)).toBe(true)
await mobilePage.keyboard.press(tab)
expect(await name.evaluate(element => element.ownerDocument.activeElement === element)).toBe(true)
await name.fill('直接点击收起后保留')
await toggle.click()
await name.waitFor({ state: 'hidden' })
expect(await toggle.getAttribute('aria-expanded')).toBe('false')
expect(await toggle.evaluate(button => button.ownerDocument.activeElement === button)).toBe(true)
await toggle.click()
expect(await name.inputValue()).toBe('直接点击收起后保留')
const region = dialog.getByRole('region', { name: '模型目录', exact: true })
expect(await region.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await dialog.getByRole('button', { name: '取消', exact: true }).click()
expect(errors.pageErrors).toEqual([])
const touchPage = await mobileBrowser.newPage({
viewport: { width: 390, height: 844 }, locale: ZH_BROWSER_LOCALE, isMobile: true, hasTouch: true,
})
const touchErrors = watchConsole(touchPage)
await touchPage.goto(scaffold.authenticatedUrl)
await openSettings(touchPage, 'zh')
const touchDialog = touchPage.getByRole('dialog', { name: '设置' })
await touchDialog.getByRole('button', { name: '模型', exact: true }).tap()
await touchDialog.getByRole('button', { name: `编辑 ${provider}`, exact: true }).tap()
await touchDialog.getByText('自定义设置').tap()
const touchToggle = touchDialog.getByRole('button', { name: '模型选项 1', exact: true })
const touchName = touchDialog.getByRole('textbox', { name: '显示名称 1', exact: true })
await touchToggle.tap()
expect(await touchName.evaluate(element => element.ownerDocument.activeElement === element)).toBe(false)
await touchName.fill('触屏编辑后的名称')
await touchToggle.tap()
await touchName.waitFor({ state: 'hidden' })
expect(await touchToggle.getAttribute('aria-expanded')).toBe('false')
await touchToggle.tap()
expect(await touchName.inputValue()).toBe('触屏编辑后的名称')
await touchName.fill('触屏保存后的名称')
const touchNext = touchDialog.getByRole('button', { name: '模型选项 2', exact: true })
await touchNext.tap()
expect(await touchNext.getAttribute('aria-expanded')).toBe('true')
await touchDialog.getByRole('button', { name: '保存', exact: true }).tap()
await touchName.waitFor({ state: 'detached' })
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'llm-pi-ai')?.value).toMatchObject({
providers: { [provider]: { models: [{ id: 'layout-model', name: '触屏保存后的名称' }, { id: 'next-model', name: '下一模型' }] } },
})
expect(touchErrors.pageErrors).toEqual([])
} finally {
await mobileBrowser?.close()
await scaffold.ctx.settings.mutate('llm-pi-ai', [{ op: 'unset', path: ['providers', provider] }])
}
}, 60_000,
)
it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])(
'keeps keyboard reorder focus and visibility in $name', async ({ engine }) => {
const keyboardBrowser = await engine.launch()
@@ -704,6 +849,7 @@ describe('web e2e: Models settings page configures a dormant provider', () => {
'configured.expected.md', 'declared-edit.expected.md', 'declared.expected.md',
'delete.expected.md', 'empty.expected.md', 'model-picker.expected.md',
'native-delete.expected.md', 'native-keyless.expected.md', 'catalog-inputs.expected.md',
'mobile-collapsed.expected.md', 'mobile-expanded.expected.md',
'refreshing.expected.md', 'image-only.expected.md',
])
})
+38
View File
@@ -319,6 +319,44 @@ describe('web e2e: navigation & panes over a rich seeded session', () => {
await details.getByRole('button', { name: 'Close details' }).click()
}, 60_000)
it.skipIf(MODE === 'record')('keeps trajectory folding and search usable at 390px in every locale', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-trajectory-toolbar-narrow'))
await ensureSeedOpen(page)
await page.getByRole('tab', { name: 'Trajectory' }).click()
const toolbar = page.getByRole('toolbar')
const search = toolbar.getByRole('searchbox')
try {
for (const locale of ['en', 'zh', 'ja', 'es', 'fr', 'de', 'ru', 'pt']) {
await scaffold.ctx.settings.update('locale', { preference: locale })
await expect.poll(() => page.evaluate(() => document.documentElement.lang))
.toBe(locale === 'zh' ? 'zh-CN' : locale)
await search.fill('NAVIGATION_OK')
await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(() => toolbar.evaluate((element) => {
const bounds = element.getBoundingClientRect()
return {
fits: element.scrollWidth <= element.clientWidth + 1,
controlsFit: [...element.querySelectorAll('button:not([hidden]), input')].every((control) => {
const rect = control.getBoundingClientRect()
return rect.width > 0 && rect.height > 0
&& rect.left >= bounds.left && rect.right <= bounds.right
&& rect.top >= bounds.top && rect.bottom <= bounds.bottom
}),
}
}), { message: `${locale} toolbar at 390px` }).toEqual({ fits: true, controlsFit: true })
expect(await search.evaluate(element => element === document.activeElement)).toBe(true)
expect(await search.inputValue()).toBe('NAVIGATION_OK')
await search.fill('')
const subcalls = toolbar.getByRole('button').last()
await subcalls.click()
expect(await subcalls.isVisible()).toBe(true)
await page.setViewportSize({ width: 1680, height: 1_000 })
}
} finally {
await scaffold.ctx.settings.update('locale', { preference: 'en' })
}
}, 90_000)
it.skipIf(MODE === 'record')('restores Assistant timing from recorded history', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-navigation-timing'))
await ensureSeedOpen(page)
@@ -0,0 +1,3 @@
# Exercise the workspace file browser without the document preview.
- id: ui-sidebar-documentpreview
disabled: true
@@ -0,0 +1,3 @@
# Exercise the document preview without the workspace file browser.
- id: ui-sidebar-files
disabled: true
@@ -248,7 +248,7 @@ describe.skipIf(MODE === 'record')('web e2e: first-run DeepSeek credential setup
const customModelId = model.getByLabel('模型 ID 1')
await customModelId.fill('private-preview')
await model.getByLabel('显示名称 1').fill('Private Preview')
await settings.getByRole('button', { name: '模型选项 1' }).click()
expect(await settings.getByRole('button', { name: '模型选项 1' }).getAttribute('aria-expanded')).toBe('true')
await model.getByLabel('上下文窗口 1').fill('131072')
await model.getByLabel('最大输出 token 数 1').fill('64K')
expect(await settings.getByRole('group', { name: '输入类型 1' }).getByRole('checkbox', { name: '图片' }).isChecked()).toBe(false)
+134
View File
@@ -0,0 +1,134 @@
/** Keyless browser geometry for the Discover toolbar against a local plugin index. */
import { once } from 'node:events'
import { readFile } from 'node:fs/promises'
import { createServer } from 'node:http'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator } from 'playwright'
import { expect, it } from 'vitest'
import type {} from '@deepseek-ai/dsh-plugin-market'
import { compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts'
import { ZH_BROWSER_LOCALE } from './support.ts'
const EXPECTED = fileURLToPath(new URL('./expected/plugin-market/toolbar-responsive.expected.md', import.meta.url))
const INDEX = new URL('./fixtures/plugin-market/toolbar.index.json', import.meta.url)
/** Read live control geometry, including the index button's intentional left outset. */
async function measure(toolbar: Locator) {
return toolbar.evaluate((element) => {
const bounds = element.getBoundingClientRect()
const panel = element.closest('[data-plugin-panel]')!.getBoundingClientRect()
const controls = Array.from(element.querySelectorAll('button, input'))
const rects = controls.map(control => control.getBoundingClientRect())
const contained = rects.every((rect, index) => {
// The index button uses an 8px left outset to align its text with the page content.
const left = index === 0 ? bounds.left - 8 : bounds.left
return rect.left >= left - 1 && rect.right <= bounds.right + 1
&& rect.left >= panel.left && rect.right <= panel.right
&& rect.left >= 0 && rect.right <= innerWidth && rect.top >= 0 && rect.bottom <= innerHeight
})
const reachable = controls.every((control, index) => {
const rect = rects[index]!
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
return rect.width > 0 && rect.height > 0 && (hit === control || control.contains(hit))
})
const separated = rects.every((rect, index) => rects.slice(index + 1).every(other =>
rect.right <= other.left || other.right <= rect.left || rect.bottom <= other.top || other.bottom <= rect.top))
const centers = rects.map(rect => rect.top + rect.height / 2)
return {
controls: controls.length,
contained,
reachable,
separated,
overflow: element.scrollWidth > element.clientWidth,
pageOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
singleLine: Math.max(...centers) - Math.min(...centers) < 1,
focused: document.activeElement === element.querySelector('input'),
}
})
}
/** Every toolbar action remains visible, reachable, and separate without losing the search focus. */
function validLayout(layout: Awaited<ReturnType<typeof measure>>): boolean {
return layout.controls === 5 && layout.contained && layout.reachable && layout.separated
&& !layout.overflow && !layout.pageOverflow && layout.focused
}
it('keeps Discover controls reachable when the toolbar wraps and retains search focus across widths', async () => {
const body = await readFile(INDEX)
const source = createServer((request, response) => {
if (request.url !== '/index.json') {
response.writeHead(404).end()
return
}
response.writeHead(200, { 'content-type': 'application/json' }).end(body)
})
source.listen(0, '127.0.0.1')
try {
await once(source, 'listening')
const address = source.address()
if (address === null || typeof address === 'string') throw new Error('The plugin index fixture has no TCP port')
const scaffold = await launchWebScaffold({
extraOverlayPath: fileURLToPath(new URL('./pin-browse-picker.overlay.yml', import.meta.url)),
profile: { packages: [], bundles: ['@deepseek-ai/dsh-experimental-plugin-market-bundle'] },
})
try {
await scaffold.ctx.pluginMarket.setIndexes([`http://127.0.0.1:${address.port}/index.json`])
const browser = await chromium.launch()
try {
const page = await browser.newPage({ viewport: { width: 1280, height: 844 }, locale: ZH_BROWSER_LOCALE, reducedMotion: 'reduce' })
const consoleWatch = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.getByRole('button', { name: '插件', exact: true }).click()
await page.getByRole('tab', { name: '发现', exact: true }).click()
await page.locator('[data-market-entry="dsh-toolbar-layout-fixture"]').waitFor()
await page.getByRole('button', { name: '收起侧边栏', exact: true }).click()
await page.evaluate(() => document.fonts.ready)
const toolbar = page.locator('[data-discover-toolbar]')
const search = toolbar.getByRole('searchbox', { name: '搜索插件' })
await search.focus()
const facts: string[] = []
for (const width of [390, 430, 768, 1280]) {
await page.setViewportSize({ width, height: 844 })
await expect.poll(async () => {
const layout = await measure(toolbar)
return validLayout(layout) && layout.singleLine === (width >= 768) ? true : layout
}, { message: `Discover toolbar at ${width}px` }).toBe(true)
facts.push(`- ${width}px: ${width >= 768 ? 'single row' : 'wrapped rows'}; index, search, labels, sort, and refresh are contained, reachable, and separate; no horizontal overflow; search focus retained.`)
}
await page.setViewportSize({ width: 390, height: 844 })
await expect.poll(async () => validLayout(await measure(toolbar))).toBe(true)
const previous = await toolbar.evaluate((element) => {
const previous = { value: element.style.getPropertyValue('flex-wrap'), priority: element.style.getPropertyPriority('flex-wrap') }
element.style.setProperty('flex-wrap', 'nowrap')
return previous
})
try {
const noWrap = await measure(toolbar)
expect(noWrap.overflow).toBe(true)
expect(validLayout(noWrap)).toBe(false)
} finally {
await toolbar.evaluate((element, previous) => {
if (previous.value === '') element.style.removeProperty('flex-wrap')
else element.style.setProperty('flex-wrap', previous.value, previous.priority)
}, previous)
}
await expect.poll(async () => validLayout(await measure(toolbar))).toBe(true)
expect(consoleWatch.pageErrors).toEqual([])
await compareOrRefreshGolden(EXPECTED,
`# Discover toolbar responsive layout\n\n${facts.join('\n')}\n\nAt 390px, restoring the previous no-wrap layout causes horizontal overflow and fails the same layout check. Removing that override restores the controls and preserves search focus.`,
webSnapshotMode())
} finally {
await browser.close()
}
} finally {
await scaffold.close()
}
} finally {
await new Promise<void>((resolve, reject) => {
source.close((error) => {
if (error === undefined) resolve()
else reject(error)
})
})
}
})
+170 -128
View File
@@ -22,8 +22,8 @@ import {
ScheduleId,
createAfterScheduleRecord,
createEveryScheduleRecord,
foldScheduleEvents,
type EveryScheduleRecord,
type ScheduleRecord,
} from '@deepseek-ai/dsh-schedule'
import {
assertFixtureInventory,
@@ -155,7 +155,9 @@ class EveryReminderAdapter extends LlmAdapter {
override async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
this.requests.push(options)
yield * textResponse(EVERY_REPLY)
const last = options.messages.findLast(message => message.source?.kind === 'schedule')
yield * textResponse(last?.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) === true
? EVERY_REPLY : 'Task change noted.')
}
}
@@ -184,6 +186,21 @@ function localAt(epoch: number, timeZone: string): LocalAt {
}
}
/** One occurrence in the target-based tool's explicit local-time format. */
function oneOccurrence(at: LocalAt): string {
return `DTSTART;TZID=${at.time_zone}:${at.date.replaceAll('-', '')}T${at.time.replaceAll(':', '')}\nRRULE:FREQ=DAILY;COUNT=1`
}
/** Historical rules retain their exact dispatch semantics in the Host task domain. */
function hostTask(record: ScheduleRecord, sessionId: SessionId): ScheduleTask {
const instant = new Date().toISOString()
return {
record, target: { kind: 'session', sessionId }, involvedSessionIds: [sessionId], status: 'active',
createdAt: instant, updatedAt: instant,
deliveryHistory: { records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false },
}
}
/** Dynamic model seam proving request-local browser context becomes an explicit At selector. */
class BrowserZoneAtAdapter extends LlmAdapter {
override async listModels(provider: string) { return [{ provider, id: MODEL, name: `${provider}/${MODEL}` }] }
@@ -201,7 +218,7 @@ class BrowserZoneAtAdapter extends LlmAdapter {
const target = Math.ceil((Date.now() + 5_000) / 1_000) * 1_000
this.selectedAt = localAt(target, AT_BROWSER_ZONE)
this.scheduledAt = new Date(target).toISOString()
const argumentsJson = JSON.stringify({ prompt: AT_PROMPT, title: AT_PROMPT, at: this.selectedAt })
const argumentsJson = JSON.stringify({ prompt: AT_PROMPT, title: AT_PROMPT, rrule: oneOccurrence(this.selectedAt), target: 'this_session' })
const callId = ToolCallId('schedule-at-browser-zone')
yield { type: 'block-start', index: 0, blockType: 'tool-call' }
yield {
@@ -224,7 +241,10 @@ class BrowserZoneAtAdapter extends LlmAdapter {
yield { type: 'finish', reason: { kind: 'tool-calls' } }
return
}
yield * textResponse(this.requests.length === 3 ? AT_ACK : AT_REPLY)
const last = options.messages.findLast(message => message.source?.kind === 'schedule')
yield * textResponse(this.requests.length === 3 ? AT_ACK
: last?.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]')) === true
? AT_REPLY : 'Task change noted.')
}
}
@@ -249,6 +269,7 @@ function requestText(options: GenerateOptions): string {
function expectReminderFraming(options: GenerateOptions): void {
const reminder = options.messages.find(message => (
message.role === 'user' && message.source?.kind === 'schedule'
&& message.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]'))
))
expect(reminder?.role).toBe('user')
const text = reminder?.content.find(block => block.type === 'text')?.text
@@ -277,15 +298,11 @@ function assistantKey(event: SessionEvent<'assistant/message'>): string {
return conversationContextKey('assistant-step', `${String(event.data.turn)}:${String(event.data.step)}`)
}
/** Wait until opening a persisted Session publishes its live Agent. */
/** Restore a persisted Session explicitly when the fixture needs a tool-calling Agent. */
async function liveAgent(scaffold: WebScaffold, sessionId: SessionId): Promise<Agent> {
const deadline = Date.now() + 30_000
for (;;) {
const found = scaffold.ctx.agents.get(sessionId)
if (found !== undefined) return found
if (Date.now() >= deadline) throw new Error(`opening session "${sessionId}" published no live Agent`)
await new Promise<void>(resolve => setTimeout(resolve, 100))
}
const resolved = await scaffold.ctx.sessionController.resolveAgent(sessionId)
if ('error' in resolved) throw new Error(`restoring session "${sessionId}" failed`)
return resolved.agent
}
describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
@@ -360,7 +377,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
signal: AbortSignal.timeout(10_000),
callId: ToolCallId('schedule-after-create'),
name: 'schedule_create',
arguments: { prompt: AFTER_PROMPT, title: AFTER_PROMPT, after_seconds: 1 },
arguments: { prompt: AFTER_PROMPT, title: AFTER_PROMPT,
rrule: oneOccurrence(localAt(Math.ceil((Date.now() + 5_000) / 1_000) * 1_000, 'UTC')), target: 'this_session' },
agent: afterHandle.agent,
})
if (afterCreated.isError) {
@@ -372,11 +390,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
}
expect(createdView.id).toMatch(/^schedule-/)
expect(createdView).toMatchObject({
kind: 'after',
prompt: AFTER_PROMPT,
afterSeconds: 1,
state: 'scheduled',
deliveryMode: 'host',
target: { kind: 'session', sessionId: afterHandle.agent.id }, status: 'active',
})
afterAssistantReply = await waitForReply(afterHandle, AFTER_REPLY, 15_000)
await afterHandle.agent.whenIdle()
@@ -415,12 +430,10 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
const domain = scaffold.ctx.storageDomain.get('schedule')
if (domain === undefined) throw new Error('Schedule domain was not opened')
for (const record of everyRecords) {
await domain.table('tasks').put(record.id, { sessionId: everyHandle.agent.id, record, status: 'active' })
await domain.table('tasks').put(record.id, hostTask(record, everyHandle.agent.id))
}
const wake = await scaffold.ctx.schedule.create(everyHandle.agent.id, {
prompt: 'Unused future scheduling wake', title: 'Future wake', after_seconds: 86_400,
})
await scaffold.ctx.schedule.delete({ sessionId: everyHandle.agent.id, id: wake.id })
const wake = await scaffold.ctx.schedule.create({ prompt: 'Unused future scheduling wake', title: 'Future wake', timing: { kind: 'after', after_seconds: 86_400 }, target: { kind: 'session', sessionId: everyHandle.agent.id } }, everyHandle.agent.id)
await scaffold.ctx.schedule.edit({ action: 'delete', id: wake.id })
await workspace.attachSession(everyHandle.agent.id)
const everyListed = await executeToolFixture(scaffold.ctx, {
signal: AbortSignal.timeout(10_000),
@@ -472,9 +485,8 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
await atSession.click()
const composer = page.locator('[data-composer-input][contenteditable="true"]').last()
await composer.fill(AT_USER_PROMPT)
const settled = scaffold.whenTurnSettled(60_000)
await page.getByRole('button', { name: 'Send message', exact: true }).click()
expect(await settled).toBe(atHandle.agent.id)
await waitForReply(atHandle, AT_ACK, 60_000)
await page.getByText(AT_ACK, { exact: true }).waitFor({ timeout: 15_000 })
atAssistantReply = await waitForReply(atHandle, AT_REPLY, 20_000)
await atHandle.agent.whenIdle()
@@ -518,18 +530,19 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
)
await expectNoReminderEntry(page)
await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).some(task => (
task.sessionId === afterHandle.agent.id && task.status === 'inactive' && task.lastDelivery !== undefined
task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id && task.status === 'ended' && task.lastDelivery !== undefined
))).toBe(true)
const delivered = (await scaffold.ctx.schedule.catalog()).find(task => task.sessionId === afterHandle.agent.id)
const delivered = (await scaffold.ctx.schedule.catalog()).find(task => task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id)
if (delivered?.lastDelivery === undefined) throw new Error('delivered one-shot receipt was not retained')
expect(await scaffold.ctx.schedule.list({ sessionId: afterHandle.agent.id })).toEqual([])
expect((await scaffold.ctx.schedule.list({ active: true })).items.filter(task =>
task.target.kind === 'session' && task.target.sessionId === afterHandle.agent.id)).toEqual([])
// Archiving the Session shown in the main pane returns the app to its
// workspace-selection view and unmounts the Tasks page with it, so the
// linked-Session assertions run with another Session in the main pane.
await page.getByRole('treeitem', { name: /Explicit local-time reminder/ }).click()
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
await manager.getByRole('button', { name: 'Inactive', exact: true }).click()
await manager.getByRole('button', { name: 'Ended', exact: true }).click()
await manager.getByRole('list', { name: 'Task catalog' })
.getByRole('button', { name: AFTER_PROMPT, exact: true }).click()
const detail = manager.getByRole('complementary', { name: 'Task details' })
@@ -550,7 +563,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
await scaffold.ctx.workspaceRegistry.archiveSession(afterHandle.agent.id)
try {
await expect.poll(() => linkedSession.isDisabled(), { timeout: 15_000 }).toBe(true)
expect(await detail.getByText('The original session is archived.', { exact: true }).count()).toBe(1)
expect(await detail.getByText('The linked session is archived.', { exact: true }).count()).toBe(1)
expect(await detail.getByText('Scheduled After follow-up', { exact: true }).count()).toBe(1)
const moreActions = detail.getByRole('button', { name: 'Automation task actions', exact: true })
await moreActions.click()
@@ -562,7 +575,9 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
// must not reach the page's own handler and close the whole panel.
await expect.poll(() => page.getByRole('menu').count(), { timeout: 5_000 }).toBe(0)
await detail.waitFor({ timeout: 5_000 })
expect((await scaffold.ctx.schedule.catalog()).find(task => task.id === delivered.id)).toEqual(delivered)
expect((await scaffold.ctx.schedule.catalog()).find(task => task.id === delivered.id)).toMatchObject({
id: delivered.id, status: 'ended', prompt: delivered.prompt, lastDelivery: delivered.lastDelivery,
})
} finally {
await scaffold.ctx.workspaceRegistry.unarchiveSession(afterHandle.agent.id)
}
@@ -577,6 +592,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
const messages = everyHandle.agent.session.snapshotEvents().filter(event => (
event.type === 'user/message'
&& event.data.source.kind === 'schedule'
&& event.data.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]'))
))
expect(messages).toHaveLength(1)
const texts = messages.map((event) => {
@@ -587,9 +603,11 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
expect(texts.filter(text => text.includes(record.id))).toHaveLength(1)
expect(texts.some(text => text.includes(record.prompt))).toBe(true)
}
expect(everyAdapter.requests).toHaveLength(1)
for (const request of everyAdapter.requests) expectReminderFraming(request)
const active = await scaffold.ctx.schedule.list({ sessionId: everyHandle.agent.id })
const request = everyAdapter.requests.find(request => request.messages.some(message => message.content.some(block =>
block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]'))))
if (request === undefined) throw new Error('the recurring delivery did not reach the model')
expectReminderFraming(request)
const active = (await scaffold.ctx.schedule.list({ active: true })).items
expect(active).toHaveLength(2)
for (const record of active) {
const original = everyRecords.find(candidate => candidate.id === record.id)
@@ -611,11 +629,11 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
await captureStableAria(page, selector, scaffold.workspaceCwd),
MODE,
)
await page.getByRole('button', { name: '2 reminders', exact: true }).waitFor({ timeout: 15_000 })
expect(await page.getByRole('list', { name: 'Active reminders' }).count()).toBe(0)
await page.getByRole('button', { name: '2 automation tasks', exact: true }).waitFor({ timeout: 15_000 })
expect(await page.getByRole('list', { name: 'Enabled automation tasks' }).count()).toBe(0)
const original = everyRecords[0]
const first = await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 })
const first = await scaffold.ctx.schedule.history({ id: original.id, limit: 20 })
if ('code' in first || first.records.length !== 1) throw new Error('expected one actual recurring receipt')
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
@@ -631,17 +649,19 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
if (domain === undefined) throw new Error('Schedule domain was not opened')
const latest = first.records[0]!
// Make the next occurrence due through the fixture's existing stored-time input.
const stored = hostTask(original, everyHandle.agent.id)
const dueAt = new Date(Date.now() - 1_000).toISOString()
await domain.table('tasks').put(original.id, {
sessionId: everyHandle.agent.id,
record: { ...original, scheduledAt: new Date(Date.now() - 1_000).toISOString() },
status: 'active',
lastDelivery: { scheduledAt: latest.scheduledAt, deliveredAt: latest.deliveredAt, messageId: latest.messageId },
deliveryHistory: { records: [...first.records].reverse(), earlierRecordsUnavailable: first.earlierRecordsUnavailable },
...stored, record: { ...stored.record, scheduledAt: dueAt },
lastDelivery: { ...latest, targetSessionId: everyHandle.agent.id },
deliveryHistory: { records: [...first.records].reverse().map(receipt => ({ ...receipt, targetSessionId: everyHandle.agent.id })),
earlierRecordsUnavailable: first.earlierRecordsUnavailable },
})
const wake = await scaffold.ctx.schedule.create(everyHandle.agent.id, { prompt: 'Future history refresh wake', title: 'History refresh wake', after_seconds: 86_400 })
await scaffold.ctx.schedule.delete({ sessionId: everyHandle.agent.id, id: wake.id })
await expect.poll(() => receipts.count(), { timeout: 15_000 }).toBe(2)
const saved = await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 })
const wake = await scaffold.ctx.schedule.create({ prompt: 'Future history refresh wake', title: 'History refresh wake', timing: { kind: 'after', after_seconds: 86_400 }, target: { kind: 'session', sessionId: everyHandle.agent.id } }, everyHandle.agent.id)
await scaffold.ctx.schedule.edit({ action: 'delete', id: wake.id })
// A second delivery waits for the Host's one-minute admission interval.
await expect.poll(() => receipts.count(), { timeout: 75_000 }).toBe(2)
const saved = await scaffold.ctx.schedule.history({ id: original.id, limit: 20 })
if ('code' in saved) throw new Error('recurring delivery history was unavailable')
expect(saved.records).toHaveLength(2)
expect(saved.records[1]).toEqual(latest)
@@ -652,28 +672,28 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
}
expect(await detail.getByRole('tab', { name: 'Records', exact: true }).getAttribute('aria-selected')).toBe('true')
await detail.getByRole('tab', { name: 'Rules', exact: true }).click()
// The interval row states its quantity in the friendly unit the stored
// seconds select: 3600 seconds is one whole hour, so the row shows 1 and
// doubling the interval is two of those hours.
const interval = detail.getByLabel('Repeat every', { exact: true })
await detail.getByRole('button', { name: 'Edit', exact: true }).click()
await detail.getByRole('button', { name: /^Repeat / }).click()
await page.getByRole('menuitem', { name: 'Every N hours', exact: true }).click()
const interval = detail.getByLabel('Interval', { exact: true })
expect(await interval.inputValue()).toBe('1')
await interval.fill('2')
// Run-time rows edit a local draft; the save bar is the only commit path.
await detail.getByText('Unsaved changes', { exact: true }).waitFor({ timeout: 15_000 })
await detail.getByRole('button', { name: 'Save changes', exact: true }).click()
await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).find(task => task.id === original.id), { timeout: 15_000 })
.toMatchObject({
id: original.id, sessionId: everyHandle.agent.id, prompt: original.prompt,
kind: 'every', everySeconds: EVERY_INTERVAL_SECONDS * 2, status: 'active',
})
expect(await scaffold.ctx.schedule.history({ sessionId: everyHandle.agent.id, id: original.id, limit: 20 })).toEqual(saved)
await expect.poll(async () => rruleOf((await scaffold.ctx.schedule.catalog()).find(task => task.id === original.id)),
{ timeout: 15_000 })
.toContain('FREQ=HOURLY;INTERVAL=2')
expect(await scaffold.ctx.schedule.history({ id: original.id, limit: 20 })).toEqual({
...saved, records: saved.records.map(receipt => ({ ...receipt, targetSessionId: everyHandle.agent.id })),
})
await detail.getByRole('tab', { name: 'Records', exact: true }).click()
await expect.poll(() => receipts.count()).toBe(2)
// The linked-session row renders on the Rules view only.
await detail.getByRole('tab', { name: 'Rules', exact: true }).click()
await detail.getByRole('button', { name: 'Linked session Fixed-rate reminder batch: open original session', exact: true }).click()
await page.getByRole('button', { name: '2 reminders', exact: true }).waitFor({ timeout: 15_000 })
}, 60_000)
await detail.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click()
await page.getByRole('button', { name: '2 automation tasks', exact: true }).waitFor({ timeout: 15_000 })
})
it('uses request-local browser context to create an explicit local At reminder', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-at'))
@@ -706,7 +726,7 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
event.type === 'tool/call' && event.data.name === 'schedule_create'
))
if (toolCall?.type !== 'tool/call') throw new Error('missing schedule_create tool call')
expect(JSON.parse(toolCall.data.arguments)).toEqual({ prompt: AT_PROMPT, title: AT_PROMPT, at: selectedAt })
expect(JSON.parse(toolCall.data.arguments)).toEqual({ prompt: AT_PROMPT, title: AT_PROMPT, rrule: oneOccurrence(selectedAt), target: 'this_session' })
const result = atHandle.agent.session.snapshotEvents().find(event => (
event.type === 'tool/result' && event.data.message.toolCallId === toolCall.data.callId
))
@@ -714,15 +734,18 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
expect(result.data.message.isError).not.toBe(true)
const resultText = result.data.message.content.find(block => block.type === 'text')
if (resultText?.type !== 'text') throw new Error('missing schedule_create response fields')
expect(JSON.parse(resultText.text)).toMatchObject({ kind: 'at', prompt: AT_PROMPT, scheduledAt })
expect(JSON.parse(resultText.text)).toMatchObject({ prompt: AT_PROMPT, scheduledAt,
target: { kind: 'session', sessionId: atHandle.agent.id } })
const reminders = atHandle.agent.session.snapshotEvents().filter(event => (
event.type === 'user/message'
&& event.data.source.kind === 'schedule'
&& event.data.content.some(block => block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]'))
))
expect(reminders).toHaveLength(1)
expect(await scaffold.ctx.schedule.list({ sessionId: atHandle.agent.id })).toEqual([])
expect(atAdapter.requests).toHaveLength(4)
const reminderRequest = atAdapter.requests[3]
expect((await scaffold.ctx.schedule.list({ active: true })).items.filter(task =>
task.target.kind === 'session' && task.target.sessionId === atHandle.agent.id)).toEqual([])
const reminderRequest = atAdapter.requests.find(request => request.messages.some(message => message.content.some(block =>
block.type === 'text' && block.text.includes('This is a scheduled message from the user') && !block.text.includes('[SCHEDULE CHANGE]'))))
if (reminderRequest === undefined) throw new Error('model did not receive the At reminder')
expectReminderFraming(reminderRequest)
@@ -768,16 +791,23 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
extraOverlayPath: [await writeEveryStepOverlay(root)],
})
await seedSession(scaffold, fixture, CATALOG_SESSION_ID, 'standard')
const records = foldScheduleEvents(fixture.trim().split('\n').slice(1).map(line => JSON.parse(line) as SessionEvent)).active
const events = fixture.trim().split('\n').slice(1).map(line => JSON.parse(line) as SessionEvent)
const records = events.flatMap(event => event.type === 'schedule/change' && event.data.operation === 'create'
? [event.data.schedule] : [])
expect(records.map(record => record.id)).toEqual(Object.keys(CATALOG_TITLES))
const domain = scaffold.ctx.storageDomain.get('schedule')
if (domain === undefined) throw new Error('Schedule domain was not opened')
// The fixture holds the bytes its writer produced before titles existed, so
// each recorded task is seeded under the name this catalog lane asserts.
const seeded = records.map(record => ({ ...record, title: CATALOG_TITLES[record.id] }))
const seeded = records.map((record) => {
const title = CATALOG_TITLES[record.id]
if (title === undefined) throw new Error(`unnamed catalog fixture task: ${record.id}`)
return { ...record, title }
})
for (const record of seeded) {
await domain.table('tasks').put(record.id, { sessionId: CATALOG_SESSION_ID, record, status: 'active' })
await domain.table('tasks').put(record.id, hostTask(record, CATALOG_SESSION_ID))
}
expect(await scaffold.ctx.schedule.list({ sessionId: CATALOG_SESSION_ID })).toEqual(seeded)
expect((await scaffold.ctx.schedule.list({ active: true })).items).toMatchObject(seeded)
expect(scaffold.ctx.agents.get(CATALOG_SESSION_ID)).toBeUndefined()
const workspace = await scaffold.ctx.workspaceRegistry.create(scaffold.workspaceCwd)
@@ -816,9 +846,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
it('manages cross-Session tasks from the sidebar without activating their Sessions', async () => {
const otherSessionId = SessionId('schedule-manager-other-session')
await seedSession(scaffold, await readFile(CATALOG_FIXTURE, 'utf8'), otherSessionId, 'standard')
const other = await scaffold.ctx.schedule.create(otherSessionId, {
prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', at: '2099-08-25T12:08:00.000Z',
})
const other = await scaffold.ctx.schedule.create({ prompt: 'Inspect the second workspace deployment', title: 'Second workspace deployment', timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'session', sessionId: otherSessionId } }, otherSessionId)
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
await manager.getByRole('heading', { name: 'Automation tasks', exact: true }).waitFor()
@@ -831,7 +859,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
// unrestricted state; the repeating task is reached by name instead of a
// retired type chip.
const statuses = manager.getByRole('group', { name: 'Task status' })
expect(await statuses.getByRole('button').count()).toBe(3)
expect(await statuses.getByRole('button').count()).toBe(4)
await manager.getByRole('button', { name: 'All', exact: true }).click()
await expect.poll(() => tasks.getByRole('listitem').count()).toBe(4)
expect(await tasks.textContent()).toContain('Check exact cadence')
@@ -850,8 +878,8 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await page.setViewportSize({ width: 600, height: 340 })
// The linked Session is a seat in the detail's tab strip, above the rule's
// scroll region, so it stays fully visible however far that region scrolls.
const contextRow = details.locator('[class*="detailContext"]')
const linkedSession = contextRow.getByRole('button', { name: 'Linked session: open original session', exact: true })
const contextRow = details.locator('[class*="hostSessionFooter"]')
const linkedSession = contextRow.getByRole('button', { name: 'Linked session: open linked session', exact: true })
expect(await contextRow.getByRole('button').count()).toBe(1)
expect(await linkedSession.textContent()).toContain(otherSessionId)
expect(await contextRow.evaluate(element => element.closest('[class*="detailScroll"]') === null)).toBe(true)
@@ -887,9 +915,9 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await tasks.getByRole('button', { name: 'Check exact cadence', exact: true }).click()
// This Session's catalog row carries no title before the Session is opened,
// so its link shows the Session id and is named without one.
await manager.getByRole('button', { name: 'Linked session: open original session', exact: true }).click()
await manager.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click()
await liveAgent(scaffold, CATALOG_SESSION_ID)
await page.getByRole('button', { name: '3 reminders', exact: true }).waitFor()
await page.getByRole('button', { name: '3 automation tasks', exact: true }).waitFor()
expect(tripwire.pageErrors).toEqual([])
}, 60_000)
@@ -935,20 +963,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
await manager.getByRole('button', { name: 'Check exact cadence', exact: true }).click()
await manager.getByRole('button', { name: `Linked session ${CATALOG_TITLE}: open original session`, exact: true }).click()
await manager.getByRole('button', { name: /^Linked session.*: open linked session$/ }).click()
await liveAgent(scaffold, CATALOG_SESSION_ID)
await page.getByRole('navigation', { name: 'Session hierarchy' })
.getByText(CATALOG_TITLE, { exact: true }).waitFor({ timeout: 15_000 })
const trigger = page.getByRole('button', { name: '3 reminders' })
const trigger = page.getByRole('button', { name: '3 automation tasks' })
await trigger.waitFor({ timeout: 15_000 })
await trigger.click()
const catalog = page.getByRole('list', { name: 'Active reminders' })
const catalog = page.getByRole('list', { name: 'Enabled automation tasks' })
await catalog.waitFor({ timeout: 10_000 })
expect(await catalog.getByRole('listitem').count()).toBe(3)
const lightLayout = await page.evaluate(() => {
const triggerElement = document.querySelector('button[aria-label="3 reminders"]')
const catalogElement = document.querySelector('[aria-label="Active reminders"]')
const triggerElement = document.querySelector('button[aria-label="3 automation tasks"]')
const catalogElement = document.querySelector('[aria-label="Enabled automation tasks"]')
if (!(triggerElement instanceof HTMLElement) || !(catalogElement instanceof HTMLElement)) {
throw new Error('active reminder trigger or catalog is not mounted')
}
@@ -983,7 +1011,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
// pushing the popover past its own width, and a longer stored name wraps
// through the same `overflow-wrap: anywhere` declaration the stylesheet
// states for the title.
const longPrompt = longRow.getByRole('button', { name: 'Open reminder details: Join release review' })
const longPrompt = longRow.getByRole('button', { name: 'Open automation task details: Join release review' })
const promptLayout = await longPrompt.evaluate(element => ({
clientWidth: element.clientWidth,
scrollWidth: element.scrollWidth,
@@ -1046,7 +1074,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
expect(darkBackground).not.toBe(lightLayout.background)
await compareOrRefreshGolden(
CATALOG_EXPECTED,
await captureStableAria(page, '[aria-label="Active reminders"]', scaffold.workspaceCwd),
await captureStableAria(page, '[aria-label="Enabled automation tasks"]', scaffold.workspaceCwd),
MODE,
)
@@ -1069,16 +1097,16 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
expect(metadataText).toMatch(/\d{1,2}:\d{2}/)
// The delete glyph is an aria-hidden SVG, so the ARIA golden cannot prove it
// still renders; the DOM has to.
const deleteButton = catalog.getByRole('button', { name: /^Delete reminder:/ }).first()
const deleteButton = catalog.getByRole('button', { name: /^Delete automation task:/ }).first()
await expect.poll(() => deleteButton.locator('svg').count(), { timeout: 15_000 }).toBe(1)
for (let remaining = 3; remaining > 0; remaining--) {
await catalog.getByRole('button', { name: /^Delete reminder:/ }).first().click()
await expect.poll(() => catalog.getByRole('button', { name: /^Delete reminder:/ }).count(), { timeout: 15_000 })
await catalog.getByRole('button', { name: /^Delete automation task:/ }).first().click()
await expect.poll(() => catalog.getByRole('button', { name: /^Delete automation task:/ }).count(), { timeout: 15_000 })
.toBe(remaining - 1)
}
await expectNoReminderEntry(page)
expect(await scaffold.ctx.schedule.list({ sessionId: CATALOG_SESSION_ID })).toEqual([])
expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([])
await page.reload({ waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
await expectNoReminderEntry(page)
@@ -1100,9 +1128,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
it('shows the pruning footer only for confirmed cleanup after the final saved page', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-retention'))
const record = await scaffold.ctx.schedule.create(CATALOG_SESSION_ID, {
prompt: 'Review retained records', title: 'History retention review', at: '2099-09-01T12:00:00.000Z',
})
const record = await scaffold.ctx.schedule.create({ prompt: 'Review retained records', title: 'History retention review', timing: { kind: 'at', at: '2099-09-01T12:00:00.000Z' }, target: { kind: 'session', sessionId: CATALOG_SESSION_ID } }, CATALOG_SESSION_ID)
try {
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
@@ -1119,10 +1145,10 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
const domain = scaffold.ctx.storageDomain.get('schedule')
if (domain === undefined) throw new Error('Schedule domain was not opened')
const instant = new Date().toISOString()
const receipt = { scheduledAt: instant, deliveredAt: instant, messageId: MessageId('retention-legacy') }
const receipt = { scheduledAt: instant, deliveredAt: instant, messageId: MessageId('retention-legacy'), targetSessionId: CATALOG_SESSION_ID }
await rulesTab.click()
await domain.table('tasks').put(record.id, {
sessionId: CATALOG_SESSION_ID, record, status: 'inactive', lastDelivery: receipt,
...hostTask(record, CATALOG_SESSION_ID), status: 'ended', lastDelivery: receipt,
deliveryHistory: { records: [receipt], earlierRecordsUnavailable: true },
})
await recordsTab.click()
@@ -1131,13 +1157,16 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
expect(await notice.count()).toBe(0)
await rulesTab.click()
let task: ScheduleTask = {
sessionId: CATALOG_SESSION_ID, record, status: 'inactive',
deliveryHistory: { records: [], earlierRecordsUnavailable: false },
record,
target: { kind: 'session', sessionId: CATALOG_SESSION_ID },
involvedSessionIds: [CATALOG_SESSION_ID], status: 'ended',
createdAt: instant, updatedAt: instant,
deliveryHistory: { records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false },
}
for (let index = 0; index < 23; index++) {
const time = new Date(Date.now() - (index === 0 ? 40 * 86_400_000 : (23 - index) * 3_600_000)).toISOString()
task = { ...task, ...appendDelivery(task, {
scheduledAt: time, deliveredAt: time, messageId: MessageId(`retention-${index}`),
scheduledAt: time, deliveredAt: time, messageId: MessageId(`retention-${index}`), targetSessionId: CATALOG_SESSION_ID,
}, { days: 30, records: 200 }) }
}
expect(task.deliveryHistory?.records).toHaveLength(22)
@@ -1153,7 +1182,8 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await info.click()
const bounds = detail.getByText('Each task keeps up to 200 delivery records from the last 30 days.', { exact: true })
await bounds.waitFor()
expect(await detail.locator('footer').innerText()).toMatchInlineSnapshot(`
const retentionFooter = detail.locator('[class*="retentionEnd"]')
expect(await retentionFooter.innerText()).toMatchInlineSnapshot(`
"Earlier delivery records have been cleared
Each task keeps up to 200 delivery records from the last 30 days.
@@ -1163,15 +1193,17 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await info.click()
expect(await bounds.count()).toBe(0)
const panelBox = await detail.boundingBox()
const footerBox = await detail.locator('footer').boundingBox()
const footerBox = await retentionFooter.boundingBox()
const sessionFooterBox = await detail.locator('[class*="hostSessionFooter"]').boundingBox()
expect(panelBox).not.toBeNull()
expect(footerBox).not.toBeNull()
expect(Math.abs(footerBox!.x - panelBox!.x)).toBeLessThan(2)
expect(Math.abs(footerBox!.y + footerBox!.height - panelBox!.y - panelBox!.height)).toBeLessThan(2)
expect(await detail.locator('footer').evaluate(element => getComputedStyle(element).borderTopWidth)).toBe('0px')
expect(sessionFooterBox).not.toBeNull()
expect(footerBox!.y + footerBox!.height).toBeLessThanOrEqual(sessionFooterBox!.y)
expect(await retentionFooter.evaluate(element => getComputedStyle(element).borderTopWidth)).toBe('0px')
expect(tripwire.pageErrors).toEqual([])
} finally {
await scaffold.ctx.schedule.delete({ sessionId: CATALOG_SESSION_ID, id: record.id })
await scaffold.ctx.schedule.edit({ action: 'delete', id: record.id })
}
}, 60_000)
@@ -1182,20 +1214,22 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
const clock = new Intl.DateTimeFormat('en-GB-u-nu-latn', {
timeZone, hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23',
})
const time = clock.format(new Date(Date.now() + 3_600_000))
const at = localAt(Math.ceil((Date.now() + 3_600_000) / 60_000) * 60_000, timeZone)
const time = at.time
const rrule = `DTSTART;TZID=${timeZone}:${at.date.replaceAll('-', '')}T${time.replaceAll(':', '')}\nRRULE:FREQ=DAILY`
const prompt = 'Inspect the daily calendar rule'
const result = await executeToolFixture(scaffold.ctx, {
signal: AbortSignal.timeout(10_000), callId: ToolCallId('schedule-daily-catalog-create'),
name: 'schedule_create', arguments: { prompt, title: prompt, daily: { time, time_zone: timeZone } }, agent,
name: 'schedule_create', arguments: { prompt, title: prompt, rrule, target: 'this_session' }, agent,
})
const created = (await scaffold.ctx.schedule.catalog()).find(task => (
task.sessionId === CATALOG_SESSION_ID && task.prompt === prompt
task.target.kind === 'session' && task.target.sessionId === CATALOG_SESSION_ID && task.prompt === prompt
))
if (created === undefined) throw new Error('daily tool did not create a stored task')
try {
expect(result.isError).toBe(false)
expect(result.value).toMatchObject({ kind: 'daily', time: `${time}.000`, timeZone })
expect(created).toMatchObject({ kind: 'daily', time: `${time}.000`, timeZone, status: 'active' })
expect(result.value).toMatchObject({ rrule, target: { kind: 'session', sessionId: CATALOG_SESSION_ID } })
expect(created).toMatchObject({ rrule, status: 'active' })
expect(clock.format(new Date(created.scheduledAt))).toBe(time)
await page.clock.setFixedTime(new Date())
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
@@ -1219,6 +1253,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
const detail = manager.getByRole('complementary', { name: 'Task details' })
expect(await detail.getByText(frequency, { exact: true }).count()).toBe(1)
expect(await detail.getByText('Once', { exact: true }).count()).toBe(0)
await detail.getByRole('button', { name: 'Edit', exact: true }).click()
const runTime = detail.getByRole('region', { name: 'Run time', exact: true })
const timeField = runTime.getByRole('button', { name: 'Time', exact: true })
// The Time zone row is a menu trigger button; the zone is chosen, never typed.
@@ -1227,37 +1262,36 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
// Zone rows lead with the current offset and the localized zone name, so
// the browser's own zone is the row marked as the system one.
await page.getByRole('menuitem', { name: /China Standard Time \(system\)$/ }).click()
// The Time row opens three clock columns; a pick stages the clock itself,
// and the stored rule keeps the millisecond precision the picker writes.
// Daily guided rules keep minute precision; a pick stages the clock.
await timeField.click()
expect(await timeField.getAttribute('aria-expanded')).toBe('true')
await page.getByRole('listbox', { name: 'Hour', exact: true }).getByRole('option', { name: '12', exact: true }).click()
await page.getByRole('listbox', { name: 'Minute', exact: true }).getByRole('option', { name: '34', exact: true }).click()
await page.getByRole('listbox', { name: 'Second', exact: true }).getByRole('option', { name: '56', exact: true }).click()
await page.keyboard.press('Escape')
expect(await timeField.textContent()).toBe('12:34:56')
expect(await timeField.textContent()).toBe('12:34:00')
await expect.poll(() => detail.getByText('Unsaved changes', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
// The staged draft reaches the Host only through the save bar's Save action.
await detail.getByRole('button', { name: 'Save changes', exact: true }).click()
await expect.poll(async () => (await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id), { timeout: 15_000 })
.toMatchObject({ time: '12:34:56.000', timeZone: 'Asia/Shanghai' })
await expect.poll(async () => rruleOf((await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id)),
{ timeout: 15_000 })
.toContain('DTSTART;TZID=Asia/Shanghai:')
const saved = (await scaffold.ctx.schedule.catalog()).find(task => task.id === created.id)
expect(saved).toMatchObject({
id: created.id, sessionId: CATALOG_SESSION_ID, prompt, status: 'active',
kind: 'daily', time: '12:34:56.000', timeZone: 'Asia/Shanghai',
id: created.id, target: { kind: 'session', sessionId: CATALOG_SESSION_ID }, prompt, status: 'active',
})
expect(rruleOf(saved)).toContain('BYHOUR=12;BYMINUTE=34')
// A stored zone equal to the browser zone is omitted from the frequency line.
await expect.poll(() => detail.getByText('Daily at 12:34:56', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
expect(await scaffold.ctx.schedule.history({ sessionId: CATALOG_SESSION_ID, id: created.id, limit: 20 }))
await expect.poll(() => detail.getByText('Daily at 12:34', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
expect(await scaffold.ctx.schedule.history({ id: created.id, limit: 20 }))
.toEqual({ id: created.id, records: [], earlierRecordsUnavailable: false,
earlierRecordsPruned: false, retention: { days: 30, records: 200 } })
// The created rule stays active, so the ended-status filter hides every
// row; the retired type chips no longer exist.
await manager.getByRole('button', { name: 'Inactive', exact: true }).click()
await manager.getByRole('button', { name: 'Ended', exact: true }).click()
await expect.poll(() => tasks.getByRole('listitem').count()).toBe(0)
expect(tripwire.pageErrors).toEqual([])
} finally {
await scaffold.ctx.schedule.delete({ sessionId: CATALOG_SESSION_ID, id: created.id })
await scaffold.ctx.schedule.edit({ id: created.id, action: 'delete' })
await page.clock.setFixedTime(new Date(CATALOG_NOW))
}
}, 60_000)
@@ -1279,17 +1313,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
scheduledAt: record.scheduledAt,
deliveredAt: new Date(Date.parse(record.scheduledAt) + 1_000).toISOString(),
messageId: MessageId(`${id}-delivery`),
targetSessionId: endedSession,
}
await domain.table('tasks').put(record.id, {
sessionId: endedSession, record, status: 'inactive', lastDelivery: receipt,
deliveryHistory: { records: [receipt], earlierRecordsUnavailable: false },
target: { kind: 'session', sessionId: endedSession }, involvedSessionIds: [endedSession],
record, status: 'ended', lastDelivery: receipt,
deliveryHistory: { records: [receipt], earlierRecordsUnavailable: false, earlierRecordsPruned: false },
})
}
// The running task is what the cleanup must leave alone. Creating it also
// announces a committed Host change, so the open page reads the rows seeded
// above without waiting for its own first catalog read.
const kept = await scaffold.ctx.schedule.create(endedSession, {
prompt: 'Keep this running task', title: 'Keep this running task', at: '2099-08-25T12:08:00.000Z',
const kept = await scaffold.ctx.schedule.create({
prompt: 'Keep this running task', title: 'Keep this running task',
timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' },
})
try {
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
@@ -1304,22 +1341,22 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
// The confirmation states the Host-side target and removes nothing until it
// is confirmed.
await more.click()
await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click()
const confirmation = page.getByRole('dialog', { name: 'Clear inactive tasks (2)?' })
await page.getByRole('menuitem', { name: 'Clear all ended tasks', exact: true }).click()
const confirmation = page.getByRole('dialog', { name: 'Clear ended tasks (2)?' })
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click()
expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toHaveLength(2)
expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended')).toHaveLength(2)
await more.click()
await page.getByRole('menuitem', { name: 'Clear all inactive tasks', exact: true }).click()
await page.getByRole('menuitem', { name: 'Clear all ended tasks', exact: true }).click()
await confirmation.getByRole('button', { name: 'Clear tasks', exact: true }).click()
await expect.poll(
async () => (await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive'),
async () => (await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended'),
{ timeout: 15_000 },
).toEqual([])
const remaining = await scaffold.ctx.schedule.catalog()
expect(remaining.some(task => endedIds.includes(task.id))).toBe(false)
expect(remaining.map(task => task.title)).toContain('Keep this running task')
await page.getByText('Cleared 2 inactive tasks.', { exact: true }).waitFor({ timeout: 15_000 })
await page.getByText('Cleared 2 ended tasks.', { exact: true }).waitFor({ timeout: 15_000 })
// The trigger left with the rows it removed, so the page heading owns the
// focus after the confirmation closes; this confirms the heading fallback
// in a real browser.
@@ -1332,15 +1369,20 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
await manager.getByRole('button', { name: 'All', exact: true }).click()
await expect.poll(() => manager.getByRole('list', { name: 'Task catalog' })
.getByRole('button', { name: kept.title, exact: true }).count(), { timeout: 15_000 }).toBe(1)
expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'inactive')).toEqual([])
expect((await scaffold.ctx.schedule.catalog()).filter(task => task.status === 'ended')).toEqual([])
expect(tripwire.pageErrors).toEqual([])
} finally {
// The shared page and Host outlive a failed assertion: remove every row
// this scenario introduced so the next one starts from the same state. A
// teardown rejection must not mask the assertion that failed first.
await Promise.allSettled(
[kept.id, ...endedIds].map(id => scaffold.ctx.schedule.delete({ sessionId: endedSession, id })),
[kept.id, ...endedIds].map(id => scaffold.ctx.schedule.edit({ id, action: 'delete' })),
)
}
}, 60_000)
})
/** Read a known RRULE task from the shared catalog after an explicit rule replacement. */
function rruleOf(task: ScheduleRecord | undefined): string | undefined {
return task?.kind === 'rrule' ? task.rrule : undefined
}
+147
View File
@@ -0,0 +1,147 @@
/** Manual task creation and editing through the shipped Web composition. */
import { chromium } from 'playwright'
import { expect, it } from 'vitest'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
it('creates from a paused empty state, selects the task, and saves an inline edit without starting an Agent', async () => {
// First use registers the default Workspace, which a new task's directory starts with.
const scaffold = await launchWebScaffold({ firstUse: true })
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
try {
browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'zh-CN', timezoneId: 'Asia/Shanghai' })
await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'zh') })
const tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.getByRole('button', { name: '自动化任务', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
const createStyles = await manager.getByRole('group', { name: '创建', exact: true }).getByRole('button').evaluateAll(buttons => buttons.map((button) => {
const style = getComputedStyle(button)
return { height: style.height, topLeft: style.borderTopLeftRadius, bottomLeft: style.borderBottomLeftRadius,
topRight: style.borderTopRightRadius, bottomRight: style.borderBottomRightRadius }
}))
expect(createStyles).toEqual([
{ height: '32px', topLeft: '16px', bottomLeft: '16px', topRight: '0px', bottomRight: '0px' },
{ height: '32px', topLeft: '0px', bottomLeft: '0px', topRight: '16px', bottomRight: '16px' },
])
await manager.getByRole('button', { name: '已暂停', exact: true }).click()
await manager.getByRole('heading', { name: '没有已暂停的自动化任务', exact: true }).waitFor()
await manager.getByRole('button', { name: '选择创建方式', exact: true }).click()
await page.getByRole('menuitem', { name: '手动创建', exact: true }).waitFor()
await page.keyboard.press('Escape')
await manager.getByRole('button', { name: '新建自动化任务', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '手动创建', exact: true })
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('AI 新闻简报')
await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接。')
await dialog.getByRole('button', { name: /^重复 / }).click()
await page.getByRole('menuitem', { name: '周一至周五', exact: true }).click()
await dialog.getByRole('button', { name: '时间', exact: true }).click()
await page.getByRole('listbox', { name: '时', exact: true }).getByRole('option', { name: '09', exact: true }).click()
await page.getByRole('listbox', { name: '分', exact: true }).getByRole('option', { name: '00', exact: true }).click()
await page.getByRole('listbox', { name: '秒', exact: true }).getByRole('option', { name: '00', exact: true }).click()
await page.keyboard.press('Escape')
await dialog.getByRole('button', { name: /^执行位置 / }).click()
await page.getByRole('menuitem', { name: '新建会话并复用 首次运行时创建,之后沿用这个会话', exact: true }).waitFor()
expect(await page.getByRole('menuitem').count()).toBe(2)
const workspace = dialog.getByRole('button', { name: /^关联工作区 / })
await expect.poll(() => workspace.textContent()).toContain('默认工作区')
await page.keyboard.press('Escape')
// The workspace menu states each directory, so the default workspace names its folder.
const defaultPath = scaffold.ctx.workspaceRegistry.list()[0]?.path
if (defaultPath === undefined) throw new Error('first use did not register the default workspace')
await workspace.click()
await page.getByRole('menuitem').getByTitle(defaultPath, { exact: true }).waitFor()
await page.keyboard.press('Escape')
expect(await dialog.count()).toBe(1)
await dialog.getByRole('button', { name: '创建', exact: true }).click()
const detail = manager.getByRole('complementary', { name: '任务详情', exact: true })
await detail.getByRole('heading', { name: 'AI 新闻简报', exact: true }).waitFor()
expect(await manager.getByRole('button', { name: '全部', exact: true }).getAttribute('aria-pressed')).toBe('true')
expect(await manager.getByRole('list', { name: '任务列表', exact: true }).getByRole('button', { name: 'AI 新闻简报', exact: true }).count()).toBe(1)
await detail.getByText('待创建', { exact: true }).waitFor()
const task = (await scaffold.ctx.schedule.catalog()).find(task => task.title === 'AI 新闻简报')
if (task === undefined || task.target.kind !== 'new_once') throw new Error('manual task was not created with the reusable target')
expect(task.target.create.cwd).toBe(defaultPath)
await detail.getByRole('button', { name: '编辑', exact: true }).click()
await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).waitFor({ state: 'detached' })
await detail.getByText('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。', { exact: true }).waitFor()
const saved = await scaffold.ctx.schedule.view({ id: task.id })
if ('code' in saved) throw new Error('edited task was not retained')
expect(saved.prompt).toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
await manager.getByRole('button', { name: '选择创建方式', exact: true }).click()
await page.getByRole('menuitem', { name: '手动创建', exact: true }).click()
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('检查最新进展')
await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('汇总最近的更新')
await dialog.getByRole('button', { name: /^重复 / }).click()
await page.getByRole('menuitem', { name: '每 N 分钟', exact: true }).click()
await dialog.getByRole('spinbutton', { name: '重复间隔', exact: true }).fill('5')
await dialog.getByRole('button', { name: /^执行位置 / }).click()
await page.getByRole('menuitem', { name: '每次新建会话 每次运行都创建独立会话', exact: true }).click()
await dialog.getByText('运行间隔至少 1分钟', { exact: true }).waitFor()
const beforeCreate = Date.now()
await dialog.getByRole('button', { name: '创建', exact: true }).click()
await detail.getByRole('heading', { name: '检查最新进展', exact: true }).waitFor()
const intervalTask = (await scaffold.ctx.schedule.catalog()).find(item => item.title === '检查最新进展')
if (intervalTask === undefined) throw new Error('interval task was not created')
expect(intervalTask.target.kind).toBe('new')
expect(Date.parse(intervalTask.scheduledAt) - beforeCreate).toBeGreaterThan(240_000)
expect(Date.parse(intervalTask.scheduledAt) - beforeCreate).toBeLessThanOrEqual(300_000)
await detail.getByRole('button', { name: '暂停任务', exact: true }).click()
await detail.getByRole('button', { name: '恢复任务', exact: true }).waitFor()
expect(await detail.getByText('待创建', { exact: true }).count()).toBe(0)
expect(await detail.getByText('最近运行会话', { exact: true }).count()).toBe(0)
expect(await detail.getByText('运行间隔至少', { exact: false }).count()).toBe(0)
expect(tripwire.pageErrors).toEqual([])
expect(scaffold.ctx.agents.get(task.target.sessionId)).toBeUndefined()
} finally {
try { await browser?.close() } finally { await scaffold.close() }
}
})
it('creates and edits Custom Cron through the built UI while retaining its explicit zone and record kind', async () => {
const scaffold = await launchWebScaffold({ firstUse: true })
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
try {
browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: 'zh-CN', timezoneId: 'Asia/Shanghai' })
await page.addInitScript(() => { localStorage.setItem('dsh.locale', 'zh') })
const tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await page.getByRole('button', { name: '自动化任务', exact: true }).click()
const manager = page.getByTestId('task-manager-page')
await manager.getByRole('button', { name: '选择创建方式', exact: true }).click()
await page.getByRole('menuitem', { name: '手动创建', exact: true }).click()
const dialog = page.getByRole('dialog', { name: '手动创建', exact: true })
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('Cron deployment check')
await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('Check the deployment status.')
await dialog.getByRole('button', { name: /^重复 / }).click()
await page.getByRole('menuitem', { name: '自定义', exact: true }).click()
await dialog.getByRole('textbox', { name: '自定义', exact: true }).fill('0 9 * * 1-5')
await dialog.getByRole('button', { name: /^时区 / }).waitFor()
await dialog.getByRole('button', { name: '创建', exact: true }).click()
const detail = manager.getByRole('complementary', { name: '任务详情', exact: true })
await detail.getByRole('heading', { name: 'Cron deployment check', exact: true }).waitFor()
const created = (await scaffold.ctx.schedule.catalog()).find(task => task.title === 'Cron deployment check')
if (created === undefined) throw new Error('Custom Cron creation did not store a task')
expect(created).toMatchObject({ kind: 'cron', expression: '0 9 * * 1-5', timeZone: 'Asia/Shanghai' })
expect(created).not.toHaveProperty('rrule')
await detail.getByRole('button', { name: '编辑', exact: true }).click()
await detail.getByRole('textbox', { name: '自定义', exact: true }).fill(' ')
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
await detail.getByRole('alert').getByText('请检查规则内容和时区', { exact: true }).waitFor()
expect(await scaffold.ctx.schedule.view({ id: created.id })).toEqual(created)
await detail.getByRole('textbox', { name: '自定义', exact: true }).fill('0 10 * * 1-5')
await detail.getByRole('button', { name: /^时区 / }).waitFor()
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
await detail.getByRole('textbox', { name: '自定义', exact: true }).waitFor({ state: 'detached' })
const edited = await scaffold.ctx.schedule.view({ id: created.id })
expect(edited).toMatchObject({ id: created.id, kind: 'cron', expression: '0 10 * * 1-5', timeZone: 'Asia/Shanghai' })
expect(edited).not.toHaveProperty('rrule')
expect(tripwire.pageErrors).toEqual([])
} finally {
try { await browser?.close() } finally { await scaffold.close() }
}
})
+9 -9
View File
@@ -4,12 +4,10 @@
import type { Browser, Locator, Page } from 'playwright'
import { chromium } from 'playwright'
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'
const PHONE_PAGE_WIDTH = 390
@@ -48,7 +46,7 @@ async function viewFacts(page: Page): Promise<ViewFacts> {
width: window.innerWidth,
documentWidth: document.documentElement.scrollWidth,
smallestField: steps.length === 0 ? -1 : Math.min(...steps),
name: step('[class*="_editName"]'),
name: step('[class*="_editorField"] input'),
search: step('[class*="_searchField"] input'),
instruction: step('[class*="_instruction"]'),
}
@@ -59,8 +57,9 @@ it('keeps the automation page on screen with its text fields at the touch step',
const scaffold = await launchWebScaffold()
const url = scaffold.authenticatedUrl
try {
await scaffold.ctx.schedule.create(PHONE_TASK_SESSION, {
prompt: 'Check the deployment log', title: PHONE_TASK_TITLE, at: '2099-08-25T12:08:00.000Z',
await scaffold.ctx.schedule.create({
prompt: 'Check the deployment log', title: PHONE_TASK_TITLE,
timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'new_once' },
})
const browser: Browser = await chromium.launch()
try {
@@ -80,15 +79,15 @@ it('keeps the automation page on screen with its text fields at the touch step',
search: '16px',
instruction: 'absent',
})
// The detail keeps the floor too, and the name control keeps the 20px step
// the floor must not flatten.
// The editor keeps the touch floor for its name and instruction fields.
await phonePanel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click()
await phonePanel.locator('[class*="_detailScroll"]').waitFor({ timeout: 10_000 })
await phonePanel.getByRole('button', { name: '编辑', exact: true }).click()
await expect.poll(() => viewFacts(phonePage)).toEqual({
width: PHONE_PAGE_WIDTH,
documentWidth: PHONE_PAGE_WIDTH,
smallestField: 16,
name: '20px',
name: '16px',
search: '16px',
instruction: '16px',
})
@@ -109,11 +108,12 @@ it('keeps the automation page on screen with its text fields at the touch step',
})
await desktopPanel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click()
await desktopPanel.locator('[class*="_detailScroll"]').waitFor({ timeout: 10_000 })
await desktopPanel.getByRole('button', { name: '编辑', exact: true }).click()
await expect.poll(() => viewFacts(desktopPage)).toEqual({
width: 1024,
documentWidth: 1024,
smallestField: 14,
name: '20px',
name: '14px',
search: '14px',
instruction: '14px',
})
+2 -2
View File
@@ -490,9 +490,9 @@ const EXPECTED_TOOLS = [
'read',
'read_image',
'schedule_create',
'schedule_delete',
'schedule_edit',
'schedule_list',
'schedule_update',
'schedule_view',
'send_message',
'skill',
'subagent',
+3
View File
@@ -184,6 +184,9 @@ describe.skipIf(process.platform === 'win32')('Web sidebar shortcuts', () => {
await page.keyboard.press(`${primary}+Shift+,`)
expect(await panel.locator('[data-dockkit-tab]').filter({ hasText: 'Files' }).count()).toBe(1)
expect(await panel.locator('[data-dockkit-pane]').evaluate(pane => document.activeElement === pane)).toBe(true)
// Once the reveal's glow has ended, the focused pane draws nothing of its own. file-browser.e2e.ts and the
// seat spec own the glow itself, so this waits for no marker rather than requiring the transient one.
await expect.poll(() => panel.locator('[data-dockkit-pane][data-sidebar-right-flash]').count()).toBe(0)
expect(await paneAppearance()).toEqual([plainPane])
await bind(page, primary, 'Toggle panel fullscreen', 'Workspace files')
+3 -2
View File
@@ -178,8 +178,9 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => {
await expect.poll(() => launched).toEqual([{ app: 'vscode', path: workspace.path }])
await page.keyboard.press('Meta+Alt+P')
const files = page.locator('[data-files-state="tree"]')
const files = page.locator('[data-files-page]')
await files.locator('[data-files-row="empty"]').waitFor()
// The directory opener sits in the files page's header, above the tree.
const opener = files.locator('[data-open-target="directory"]')
await opener.getByRole('button', { name: 'Open in VS Code', exact: true }).click()
await expect.poll(() => launched).toEqual([
@@ -196,7 +197,7 @@ describe.skipIf(mode === 'record')('web e2e: workspace shortcuts', () => {
])
await expect.poll(() => opener.getAttribute('data-state')).toBe('idle')
await compareOrRefreshGolden(join(root, 'files-open.expected.md'),
await captureStableAria(page, '[data-files-state="tree"]', scaffold.workspaceCwd), mode)
await captureStableAria(page, '[data-files-page]', scaffold.workspaceCwd), mode)
await opener.getByRole('button', { name: 'More ways to open', exact: true }).click()
await page.getByRole('menuitem', { name: 'Finder (default)', exact: true }).waitFor()
await page.keyboard.press('Escape')
+38
View File
@@ -1094,6 +1094,44 @@ describe('web e2e: shipped right Sidebar', () => {
expect(tripwire.warnings).toEqual([])
}, 60_000)
it('expands the collapsed column when a floating panel\'s dock control returns its tab', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-right-dock-expands'))
const column = await resetSidebar(page)
const floats = page.locator('[data-sidebar-right-session]:not([hidden]) [data-dockkit-float]')
const open = column.locator('[data-sidebar-right-open]')
const selected = (): Promise<string[]> =>
column.locator('[role="tab"][aria-selected="true"] [data-dockkit-tab-title]').allTextContents()
await proseChip(page).click()
await expect.poll(async () => await tabTitles(paneAt(column, 0))).toEqual(['Files', SAMPLE_NAME])
await floatByDrag(page, paneAt(column, 0).locator('[data-dockkit-tab]').filter({ hasText: SAMPLE_NAME }))
await expect.poll(async () => await floats.count()).toBe(1)
// The docked column still holds Files while collapsed.
await column.locator('[data-sidebar-right-toggle]').click()
await expect.poll(async () => await open.count()).toBe(0)
await floats.first().locator('[data-dockkit-float-dock]').click()
await expect.poll(async () => await open.count()).toBe(1)
expect(await floats.count()).toBe(0)
await expect.poll(async () => await tabTitles(column)).toEqual(['Files', SAMPLE_NAME])
await expect.poll(selected).toEqual([SAMPLE_NAME])
// Closing the column's only other tab collapses it empty; docking fills it with the tab alone.
await floatByDrag(page, column.locator('[data-dockkit-tab]').filter({ hasText: SAMPLE_NAME }))
await expect.poll(async () => await floats.count()).toBe(1)
const files = column.locator('[data-dockkit-tab]').filter({ hasText: 'Files' })
await files.hover()
await files.locator('[data-dockkit-tab-close]').click()
await expect.poll(async () => await open.count()).toBe(0)
await floats.first().locator('[data-dockkit-float-dock]').click()
await expect.poll(async () => await open.count()).toBe(1)
expect(await floats.count()).toBe(0)
await expect.poll(async () => await tabTitles(column)).toEqual([SAMPLE_NAME])
await expect.poll(selected).toEqual([SAMPLE_NAME])
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 60_000)
it('drops a pane whose last tab closes, and follows the last-tab rule on the surface', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-sidebar-right-settle'))
const column = await resetSidebar(page)
@@ -81,9 +81,9 @@ it.skipIf(MODE === 'record')('replays inherited schedule tools and refusals in a
const results = child.snapshotEvents().slice(child.inheritedEventCount)
.filter(event => event.type === 'tool/result')
expect(results.map(event => event.data.message.content)).toEqual(Array.from({ length: 4 }, () => [
{ type: 'text', text: '{"code":"subagent_session","message":"A delegated subagent cannot use reminders."}' },
{ type: 'text', text: '{"code":"subagent_session","message":"A delegated subagent cannot use scheduled tasks."}' },
]))
expect(await scaffold.ctx.schedule.list({ sessionId: child.id })).toEqual([])
expect((await scaffold.ctx.schedule.list({ active: true })).items).toEqual([])
if (MODE === 'refresh') {
const replacements = refreshFixtureReplacements(raw.map((content, index) => ({
+10 -5
View File
@@ -55,7 +55,7 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => {
// turn-tail create card carries the same `data-tool` marker without being
// one of the keyed call views this case walks.
const rows = page.locator('[data-chat-call-id] [data-tool]')
expect(await rows.count()).toBe(45)
expect(await rows.count()).toBe(50)
for (const row of await rows.all()) {
await row.getByRole('button', { expanded: false }).first().click()
expect(await row.getByRole('listitem').count()).toBeGreaterThan(0)
@@ -70,8 +70,10 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => {
await expect.poll(() => schema.textContent()).toContain('"properties"')
const callIds = [
...Array.from({ length: 3 }, (_, index) => `details-call-${index + 1}`),
// The authored schedule_update round sits beside its schedule_create sibling.
// The authored schedule_update round sits beside its schedule_create sibling, and the rounds of the current
// Schedule tools follow them.
'details-call-3b',
...['c', 'd', 'e', 'f', 'g'].map(suffix => `details-call-3${suffix}`),
...Array.from({ length: 41 }, (_, index) => `details-call-${index + 4}`),
]
const snapshots = await Promise.all(callIds.map(id =>
@@ -79,9 +81,12 @@ describe.skipIf(MODE === 'record')('web e2e: compact Tool details', () => {
const snapshot = snapshots.join('\n')
await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE)
await page.setViewportSize({ width: 360, height: 800 })
const card = page.locator('[data-chat-call-id] [data-tool="schedule_create"]')
expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
const reminders = page.locator('[data-tool="schedule_list"]')
const cards = page.locator('[data-chat-call-id] [data-tool="schedule_create"]')
expect(await cards.count()).toBe(2)
for (const card of await cards.all()) {
expect(await card.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
}
const reminders = page.locator('[data-chat-call-id="details-call-6"] [data-tool="schedule_list"]')
await scrollIntoView(reminders)
const list = reminders.getByRole('list').first()
await list.evaluate((element) => {
+4
View File
@@ -89,6 +89,8 @@
"tests/details-session-lifecycle.e2e.ts",
"tests/sessionless-header.e2e.ts",
"tests/document-preview.e2e.ts",
"tests/file-browser.e2e.ts",
"tests/file-browser-composition.e2e.ts",
"tests/excel-opc.e2e.ts",
"tests/office-fixture.ts",
"tests/sidebar-browser.e2e.ts",
@@ -96,6 +98,7 @@
"tests/plugin-config.e2e.ts",
"tests/input-plugin-extensions.e2e.ts",
"tests/plugin-manager.e2e.ts",
"tests/plugin-market-toolbar.e2e.ts",
"tests/plugin-sticky-motion.e2e.ts",
"tests/entry-customization.e2e.ts",
"tests/cua-optin.e2e.ts",
@@ -208,6 +211,7 @@
"tests/agent-preset-authoring.e2e.ts",
"tests/shipped-composition.e2e.ts",
"tests/schedule-after.e2e.ts",
"tests/schedule-manual.e2e.ts",
"tests/feedback-command.e2e.ts",
"tests/feedback-release.e2e.ts",
"tests/agent-team-panel.e2e.ts",
@@ -1,4 +1,4 @@
/** Required performance budgets for compiled Client history folding and tool preparation. */
/** Required performance budgets for compiled Client history folding and live Assistant updates. */
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
@@ -10,8 +10,8 @@ import {
ciTimeBudget,
PERFORMANCE_BUDGET_HEADROOM,
} from '../support/calibration.ts'
import { recordTimings, type BenchmarkCase } from '../support/scaling-report.ts'
import type { ConversationFoldWorkerReport, PreparingToolWorkerReport } from './conversation-fold.worker.client.ts'
import { recordPeakMemory, recordTimings, type BenchmarkCase } from '../support/scaling-report.ts'
import type { ConversationFoldWorkerReport, PreparingToolWorkerReport, StreamingAssistantWorkerReport } from './conversation-fold.worker.client.ts'
/** Replies in the folded window; each carries one reasoning block and one text block. */
const TURNS = 200
@@ -54,6 +54,20 @@ const PREPARING_CASES = [
{ tool: 'bash', characters: 128 * 1024, expectedMs: 150, expectedMb: 8 },
] as const
const STREAMING_CHARACTERS = 256 * 1024
const STREAMING_SAMPLES = 5
/** Reference-machine expectations; shared CI scaling applies only to elapsed time. */
const STREAMING_WORKLOADS = [
{ fragments: 4_096, expectedMs: 12 },
{ fragments: 16_384, expectedMs: 32 },
] as const
const STREAMING_CASES = STREAMING_WORKLOADS.flatMap(workload => [
{ ...workload, blockType: 'text', pattern: 'ordinary' },
{ ...workload, blockType: 'reasoning', pattern: 'leading-whitespace' },
] as const)
/** Incremental heap while the Assembler, live entries, and published Chat state remain reachable. */
const EXPECTED_STREAMING_RETAINED_MB = 16
const WORKER = join(
import.meta.dirname,
'..',
@@ -127,3 +141,39 @@ describe('preparing tool arguments', () => {
expect(retainedMb).toBeLessThanOrEqual(budgetMb)
})
})
describe('live Assistant text publication', () => {
it.each(STREAMING_CASES)('publishes $fragments $blockType deltas with $pattern content within bounded CPU and heap costs', async (workload) => {
const samples: StreamingAssistantWorkerReport[] = []
for (let index = 0; index < STREAMING_SAMPLES; index++) {
const run = await runBuiltBenchmarkWorker<StreamingAssistantWorkerReport>({
worker: WORKER,
args: ['streaming', workload.blockType, workload.pattern, String(STREAMING_CHARACTERS), String(workload.fragments)],
exposeGc: true, timeoutMs: WORKER_TIMEOUT_MS,
})
expect(run.timedOut, run.stderr).toBe(false)
expect(run.signal, run.stderr).toBeNull()
expect(run.exitCode, run.stderr).toBe(0)
const report = requireReport(run)
expect(report.characters).toBe(STREAMING_CHARACTERS)
expect(report.fragments).toBe(workload.fragments)
samples.push(report)
}
const median = samples.toSorted((a, b) => a.elapsedMs - b.elapsedMs)[Math.floor(STREAMING_SAMPLES / 2)]!
const retainedMb = samples.map(sample => sample.retainedMb).toSorted((a, b) => a - b)[Math.floor(STREAMING_SAMPLES / 2)]!
const budgetMs = ciTimeBudget(workload.expectedMs)
const budgetMb = EXPECTED_STREAMING_RETAINED_MB * PERFORMANCE_BUDGET_HEADROOM
const benchmarkCase: BenchmarkCase = {
id: `conversation-fold/streaming-${workload.blockType}-${workload.pattern}-${String(workload.fragments)}`,
measures: `Client append, final Chat publication, and complete text read for ${String(STREAMING_CHARACTERS / 1024)} KiB in ${String(workload.fragments)} ${workload.blockType} deltas with ${workload.pattern} content.`,
affects: 'Local processing of a long active model response; excludes model pacing, network transport, and browser rendering.',
}
console.log(JSON.stringify({ benchmark: benchmarkCase.id, samples, medianMs: median.elapsedMs, retainedMb, budgetMs, budgetMb }))
recordTimings(benchmarkCase, {
medianMs: { ms: median.elapsedMs, cpuMs: median.cpuUserMs + median.cpuSystemMs },
}, { medianMs: budgetMs })
recordPeakMemory(benchmarkCase, { peakRssMb: Math.max(...samples.map(sample => sample.maxRssMb)) })
expect(median.elapsedMs).toBeLessThanOrEqual(budgetMs)
expect(retainedMb).toBeLessThanOrEqual(budgetMb)
})
})
@@ -1,4 +1,4 @@
/** Compiled worker for Client history folding and live tool preparation. */
/** Compiled worker for Client history folding, live Assistant text, and tool preparation. */
import { performance } from 'node:perf_hooks'
import { Context } from '@deepseek-ai/cordis'
@@ -57,6 +57,20 @@ export interface PreparingToolWorkerReport {
readonly detail: string | undefined
}
/** One live Assistant block folded and read through the published Chat snapshot. */
export interface StreamingAssistantWorkerReport {
readonly blockType: 'text' | 'reasoning'
readonly pattern: 'ordinary' | 'leading-whitespace'
readonly characters: number
readonly fragments: number
readonly checksum: number
readonly elapsedMs: number
readonly cpuUserMs: number
readonly cpuSystemMs: number
readonly retainedMb: number
readonly maxRssMb: number
}
function registerEventDefinitions(ctx: Context): ConversationEventRegistry {
const events = new ConversationEventRegistry(ctx)
// Only the service holder is an adapter; registrations and routing use production code.
@@ -257,6 +271,74 @@ function preparingTool(tool: 'write' | 'bash', characters: number, definitions:
}
}
function streamingAssistant(
blockType: StreamingAssistantWorkerReport['blockType'],
pattern: StreamingAssistantWorkerReport['pattern'],
characters: number,
fragments: number,
definitions: ConversationEventRegistry,
): StreamingAssistantWorkerReport {
if (globalThis.gc === undefined) throw new Error('streaming benchmark requires --expose-gc')
if (characters % fragments !== 0) throw new Error('streaming characters must divide evenly into fragments')
const chunkSize = characters / fragments
const payload = pattern === 'ordinary'
? 'abcdefghijklmno '.repeat(Math.ceil(characters / 16)).slice(0, characters)
: ' '.repeat(characters / 2) + 'abcdefghijklmno '.repeat(Math.ceil(characters / 32)).slice(0, characters / 2)
const attemptId = LlmAttemptId('streaming-benchmark')
const live = (index: number, chunk: StreamChunk): SessionEventLikeEntry => ({
type: 'transient',
event: {
type: 'assistant/live-chunk', seq: 2 + index / (fragments + 1), time: TIME_ZERO + index,
data: { turn: 1, step: 1, attemptId, chunk },
},
})
const chunks: SessionEventLikeEntry[] = []
for (let index = 0; index < fragments; index++) {
chunks.push(live(index + 1, {
type: blockType === 'text' ? 'text-delta' : 'reasoning-delta', index: 0,
text: payload.slice(index * chunkSize, (index + 1) * chunkSize),
}))
}
const assembler = new ConversationNodeAssembler(definitions, new BenchViewDefinitions())
assembler.replaceWindow([
entry(0, 'turn/start', { turn: 1 }),
entry(1, 'step/start', { turn: 1, step: 1 }),
live(0, { type: 'block-start', index: 0, blockType }),
], false)
assembler.activateTarget('chat')
globalThis.gc()
const before = process.memoryUsage().heapUsed
const start = performance.now()
const cpuStart = process.cpuUsage()
for (const chunk of chunks) assembler.append(chunk)
assembler.flush()
const text = streamingText(assembler, blockType)
// Consuming every character includes any deferred string materialization in the endpoint.
let checksum = 0
for (let index = 0; index < text.length; index++) checksum += text.charCodeAt(index)
const cpu = process.cpuUsage(cpuStart)
const elapsedMs = performance.now() - start
if (text !== payload) throw new Error('streaming benchmark did not publish the complete Assistant text')
globalThis.gc()
const retainedMb = (process.memoryUsage().heapUsed - before) / 1048576
// This read keeps the complete owner graph reachable across endpoint collection.
if (streamingText(assembler, blockType) !== text) throw new Error('streaming benchmark lost its published Assistant text')
return {
blockType, pattern, characters: text.length, fragments, checksum,
elapsedMs, cpuUserMs: cpu.user / 1000, cpuSystemMs: cpu.system / 1000,
retainedMb, maxRssMb: process.resourceUsage().maxRSS / 1024,
}
}
function streamingText(assembler: ConversationNodeAssembler, blockType: StreamingAssistantWorkerReport['blockType']): string {
const node = assembler.get('chat')?.nodes.values().find((candidate): candidate is ChatNode<'assistant-step'> => candidate.kind === 'assistant-step')
const block = node?.data.blocks[0]
if (block?.kind !== blockType || (block.kind !== 'text' && block.kind !== 'reasoning')) {
throw new Error('streaming benchmark did not create its Assistant block')
}
return block.text
}
assertBuiltBenchmarkRuntime(import.meta.url, {
'@deepseek-ai/dsh-brand': import.meta.resolve('@deepseek-ai/dsh-brand'),
'@deepseek-ai/dsh-client-store': import.meta.resolve('@deepseek-ai/dsh-client-store'),
@@ -273,6 +355,16 @@ try {
if (tool !== 'write' && tool !== 'bash') throw new Error('preparing benchmark tool must be write or bash')
const report = preparingTool(tool, positiveInteger(process.argv[4], 'characters'), definitions)
process.stdout.write(`${JSON.stringify(report)}\n`)
} else if (process.argv[2] === 'streaming') {
const blockType = process.argv[3]
const pattern = process.argv[4]
if (blockType !== 'text' && blockType !== 'reasoning') throw new Error('streaming block type must be text or reasoning')
if (pattern !== 'ordinary' && pattern !== 'leading-whitespace') throw new Error('streaming pattern must be ordinary or leading-whitespace')
const report = streamingAssistant(
blockType, pattern, positiveInteger(process.argv[5], 'characters'),
positiveInteger(process.argv[6], 'fragments'), definitions,
)
process.stdout.write(`${JSON.stringify(report)}\n`)
} else {
const [turnsValue, smallDeltasValue, largeDeltasValue, attemptsValue] = process.argv.slice(2)
const turns = positiveInteger(turnsValue, 'turns')
+2 -2
View File
@@ -6,5 +6,5 @@
en: 41d772192075e133
zh: 5ef3da69b4de1d8a
/capability-seams-and-core-services:
en: 5e42f2392f0457d6
zh: a694691c079e36fb
en: 45dd67234744e29d
zh: a250e73f5b159175
+1 -1
View File
@@ -726,7 +726,7 @@ flowchart LR
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | Owns live Agent handles, the create/resume factory seam, and process-local initiator propagation. |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package. |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in the original Session. |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | Stores tasks independently of Session activation and queues due messages in each task's target Session. |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | Folds revisioned objective state from the session log and keeps live continuation activation process-local. |
| `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | Owns one authenticated OpenSSH connection, installed helper identity, independent program streams and disconnect cleanup for the paired remote providers. |
| `ctx.subprocess` | `seam` | [`subprocess`](../packages/subprocess/subprocess) | [`subprocess-local`](../packages/subprocess/subprocess-local), [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | [`bash-local`](../packages/shell/bash-local), [`bash-sandbox`](../packages/shell/bash-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash), [`lsp-stdio`](../packages/lsp/lsp-stdio), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | - | The bash executors, the PTY shell backend, the LSP host, and the out-of-process ACP, Codex, and Claude Code subagent backends spawn through ctx.subprocess; the service owns process coordinates, tree/session lifetime, stdio dispositions, terminal mechanics, and kill escalation. |
+1 -1
View File
@@ -728,7 +728,7 @@ flowchart LR
| `ctx.agents` | `core` | [`agent`](../packages/core/agent) | - | [`agent-loop`](../packages/core/agent-loop), [`acp`](../packages/acp/acp), [`subagent`](../packages/subagent/subagent) | - | 拥有实时 Agent 句柄、创建/恢复工厂 seam,以及进程本地的发起方传播。 |
| `ctx.agentDefaultModel` | `core` | [`agent-default-model`](../packages/core/agent-default-model) | - | [`api-session-controller`](../packages/api/session-controller), [`headless`](../packages/bundle/headless) | - | Reads the default ModelSelection from volatile Config and saves selections through the profile editor. |
| `ctx.agentLoop` | `bundle` | [`agent-loop`](../packages/core/agent-loop) | - | [`base`](../packages/bundle/base), [`sdk-minimal`](../packages/bundle/sdk-minimal) | - | 唯一的具体循环插件;扩展包依赖 dsh-agent 的事件和服务,而不依赖此包。 |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入原 Session。 |
| `ctx.schedule` | `core` | [`schedule`](../packages/schedule/schedule) | - | - | - | 独立于 Session 的加载状态存储任务,并将到期消息排入每个任务的目标 Session。 |
| `ctx.goals` | `core` | [`goal`](../packages/goal/goal) | - | - | - | 从会话日志折叠带修订版本的目标状态,并将实时延续激活保留在进程本地。 |
| `ctx.ssh` | `core` | [`ssh`](../packages/ssh/ssh) | - | [`fs-ssh`](../packages/ssh/fs-ssh), [`subprocess-ssh`](../packages/ssh/subprocess-ssh), [`sandbox-ssh`](../packages/ssh/sandbox-ssh) | - | 负责一条经过认证的 OpenSSH 连接、已安装辅助程序身份、独立程序流,以及配套远端提供方的断连清理。 |
| `ctx.subprocess` | `seam` | [`subprocess`](../packages/subprocess/subprocess) | [`subprocess-local`](../packages/subprocess/subprocess-local), [`subprocess-ssh`](../packages/ssh/subprocess-ssh) | [`bash-local`](../packages/shell/bash-local), [`bash-sandbox`](../packages/shell/bash-sandbox), [`terminal-bash`](../packages/terminal/terminal-bash), [`lsp-stdio`](../packages/lsp/lsp-stdio), [`subagent-acp`](../packages/subagent/subagent-acp), [`subagent-codex`](../packages/subagent/subagent-codex), [`subagent-claude-code`](../packages/subagent/subagent-claude-code) | - | Bash 执行器、PTY shell 后端、LSP Host,以及进程外 ACP、Codex 和 Claude Code subagent 后端都通过 ctx.subprocess 执行 spawn;该服务负责进程坐标、进程树/会话生命周期、stdio 处置、终端机制和 kill 升级。 |
+13 -5
View File
@@ -1564,7 +1564,7 @@ export interface Config {
## `@deepseek-ai/dsh-fs-local`
- `source`: [`packages/fs/fs-local/src/index.ts:46`](../packages/fs/fs-local/src/index.ts)
- `source`: [`packages/fs/fs-local/src/index.ts:51`](../packages/fs/fs-local/src/index.ts)
```ts config-catalog
/** Configuration for the local filesystem backend. */
@@ -2932,7 +2932,7 @@ export interface Config {
## `@deepseek-ai/dsh-schedule`
- `inject`: `agents` · `sessions` · `storageDomain` · `sessionPersistence`
- `source`: [`packages/schedule/schedule/src/index.ts:83`](../packages/schedule/schedule/src/index.ts)
- `source`: [`packages/schedule/schedule/src/index.ts:80`](../packages/schedule/schedule/src/index.ts)
```ts config-catalog
/** Configuration for the Host Schedule domain. */
@@ -2947,6 +2947,11 @@ export interface Config {
* cap and the window wins, and the newest records survive.
*/
deliveryHistoryRecords?: number
/**
* Shortest spacing, in seconds, from the occurrence of one delivery to the next delivery of one task whose target
* creates a Session at every delivery; omission defaults to 60. Timed and manual deliveries both wait for it.
*/
newSessionIntervalSeconds?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-schedule -->
@@ -3770,7 +3775,7 @@ export interface Config {
## `@deepseek-ai/dsh-system-prompt`
- `source`: [`packages/core/system-prompt/src/index.ts:263`](../packages/core/system-prompt/src/index.ts)
- `source`: [`packages/core/system-prompt/src/index.ts:265`](../packages/core/system-prompt/src/index.ts)
```ts config-catalog
/** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */
@@ -4004,7 +4009,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-fs`
- `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory`
- `source`: [`packages/fs/tool-fs/src/index.ts:26`](../packages/fs/tool-fs/src/index.ts)
- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts)
```ts config-catalog
/** Plugin config (all optional — `Config` supplies the defaults). */
@@ -4017,6 +4022,8 @@ export interface Config {
write?: boolean
/** Register `edit` and its guidance. Defaults to true. */
edit?: boolean
/** Register `apply_patch` and its guidance beside `edit`. Defaults to false; shipped compositions set it on their `tool-fs` rows. */
applyPatch?: boolean
/** Default and maximum number of lines returned by one `read` call. */
readLimit?: number
/** Maximum characters returned for a single line before truncation. */
@@ -4929,7 +4936,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co
| `@deepseek-ai/dsh-tool-call-timeout-policy` | `tools` | [`packages/guard/timeout-policy/src/index.ts`](../packages/guard/timeout-policy/src/index.ts) |
| `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) |
| `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) |
| `@deepseek-ai/dsh-tool-schedule` | `tools` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) |
| `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) |
| `@deepseek-ai/dsh-tool-subagent-control` | `tools` · `subagents` · `agents` | [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) |
| `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) |
| `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) |
@@ -5002,6 +5009,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them.
| `@deepseek-ai/dsh-experimental-voice-input-bundle` | — | [`packages/experimental/voice-input-bundle/src/index.ts`](../packages/experimental/voice-input-bundle/src/index.ts) |
| `@deepseek-ai/dsh-experimental-webworker-packer` | — | [`packages/experimental/webworker-packer/src/index.ts`](../packages/experimental/webworker-packer/src/index.ts) |
| `@deepseek-ai/dsh-experimental-webworker-runtime` | — | [`packages/experimental/webworker-runtime/src/index.ts`](../packages/experimental/webworker-runtime/src/index.ts) |
| `@deepseek-ai/dsh-fs-patch` | — | [`packages/fs/fs-patch/src/index.ts`](../packages/fs/fs-patch/src/index.ts) |
| `@deepseek-ai/dsh-home-paths` | — | [`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts) |
| `@deepseek-ai/dsh-hook-protocol` | — | [`packages/experimental/hook-protocol/src/index.ts`](../packages/experimental/hook-protocol/src/index.ts) |
| `@deepseek-ai/dsh-http-proxy` | — | [`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts) |
+13 -5
View File
@@ -1566,7 +1566,7 @@ export interface Config {
## `@deepseek-ai/dsh-fs-local`
- `source`: [`packages/fs/fs-local/src/index.ts:46`](../packages/fs/fs-local/src/index.ts)
- `source`: [`packages/fs/fs-local/src/index.ts:51`](../packages/fs/fs-local/src/index.ts)
```ts config-catalog
/** Configuration for the local filesystem backend. */
@@ -2934,7 +2934,7 @@ export interface Config {
## `@deepseek-ai/dsh-schedule`
- `inject`: `agents` · `sessions` · `storageDomain` · `sessionPersistence`
- `source`: [`packages/schedule/schedule/src/index.ts:83`](../packages/schedule/schedule/src/index.ts)
- `source`: [`packages/schedule/schedule/src/index.ts:80`](../packages/schedule/schedule/src/index.ts)
```ts config-catalog
/** Configuration for the Host Schedule domain. */
@@ -2949,6 +2949,11 @@ export interface Config {
* cap and the window wins, and the newest records survive.
*/
deliveryHistoryRecords?: number
/**
* Shortest spacing, in seconds, from the occurrence of one delivery to the next delivery of one task whose target
* creates a Session at every delivery; omission defaults to 60. Timed and manual deliveries both wait for it.
*/
newSessionIntervalSeconds?: number
}
```
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-schedule -->
@@ -3772,7 +3777,7 @@ export interface Config {
## `@deepseek-ai/dsh-system-prompt`
- `source`: [`packages/core/system-prompt/src/index.ts:263`](../packages/core/system-prompt/src/index.ts)
- `source`: [`packages/core/system-prompt/src/index.ts:265`](../packages/core/system-prompt/src/index.ts)
```ts config-catalog
/** Plugin config: the deployment-authored fragment of the system prompt (see {@link Config.personaPrefix} for its contract). */
@@ -4006,7 +4011,7 @@ export interface Config {
## `@deepseek-ai/dsh-tool-fs`
- `inject`: `tools` · `fs` · `systemPrompt` · `workingDirectory`
- `source`: [`packages/fs/tool-fs/src/index.ts:26`](../packages/fs/tool-fs/src/index.ts)
- `source`: [`packages/fs/tool-fs/src/index.ts:27`](../packages/fs/tool-fs/src/index.ts)
```ts config-catalog
/** Plugin config (all optional — `Config` supplies the defaults). */
@@ -4019,6 +4024,8 @@ export interface Config {
write?: boolean
/** Register `edit` and its guidance. Defaults to true. */
edit?: boolean
/** Register `apply_patch` and its guidance beside `edit`. Defaults to false; shipped compositions set it on their `tool-fs` rows. */
applyPatch?: boolean
/** Default and maximum number of lines returned by one `read` call. */
readLimit?: number
/** Maximum characters returned for a single line before truncation. */
@@ -4931,7 +4938,7 @@ export interface Config {
| `@deepseek-ai/dsh-tool-call-timeout-policy` | `tools` | [`packages/guard/timeout-policy/src/index.ts`](../packages/guard/timeout-policy/src/index.ts) |
| `@deepseek-ai/dsh-tool-cordis` | `tools` · `cordisInspect` | [`packages/extensions/tool-cordis/src/index.ts`](../packages/extensions/tool-cordis/src/index.ts) |
| `@deepseek-ai/dsh-tool-executor-native` | `tools` | [`packages/core/tool-executor-native/src/index.ts`](../packages/core/tool-executor-native/src/index.ts) |
| `@deepseek-ai/dsh-tool-schedule` | `tools` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) |
| `@deepseek-ai/dsh-tool-schedule` | `tools` · `systemPrompt` | [`packages/schedule/tool-schedule/src/index.ts`](../packages/schedule/tool-schedule/src/index.ts) |
| `@deepseek-ai/dsh-tool-subagent-control` | `tools` · `subagents` · `agents` | [`packages/subagent/tool-subagent-control/src/index.ts`](../packages/subagent/tool-subagent-control/src/index.ts) |
| `@deepseek-ai/dsh-tool-working-directory` | `tools` · `workingDirectory` | [`packages/session/tool-working-directory/src/index.ts`](../packages/session/tool-working-directory/src/index.ts) |
| `@deepseek-ai/dsh-tools` | `systemPrompt` | [`packages/core/tools/src/index.ts`](../packages/core/tools/src/index.ts) |
@@ -5004,6 +5011,7 @@ export interface Config {
| `@deepseek-ai/dsh-experimental-voice-input-bundle` | — | [`packages/experimental/voice-input-bundle/src/index.ts`](../packages/experimental/voice-input-bundle/src/index.ts) |
| `@deepseek-ai/dsh-experimental-webworker-packer` | — | [`packages/experimental/webworker-packer/src/index.ts`](../packages/experimental/webworker-packer/src/index.ts) |
| `@deepseek-ai/dsh-experimental-webworker-runtime` | — | [`packages/experimental/webworker-runtime/src/index.ts`](../packages/experimental/webworker-runtime/src/index.ts) |
| `@deepseek-ai/dsh-fs-patch` | — | [`packages/fs/fs-patch/src/index.ts`](../packages/fs/fs-patch/src/index.ts) |
| `@deepseek-ai/dsh-home-paths` | — | [`packages/util/home-paths/src/index.ts`](../packages/util/home-paths/src/index.ts) |
| `@deepseek-ai/dsh-hook-protocol` | — | [`packages/experimental/hook-protocol/src/index.ts`](../packages/experimental/hook-protocol/src/index.ts) |
| `@deepseek-ai/dsh-http-proxy` | — | [`packages/util/http-proxy/src/index.ts`](../packages/util/http-proxy/src/index.ts) |
+8 -6
View File
@@ -48,13 +48,15 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` |
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) |
@@ -65,10 +67,10 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
+8 -6
View File
@@ -50,13 +50,15 @@
| `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `workspace-controller` |
| `feedback/committed` | `parallel` | [`packages/feedback/message-feedback/src/index.ts:58`](../packages/feedback/message-feedback/src/index.ts) | [`message-feedback`](../packages/feedback/message-feedback) (`parallel`) | [`session-telemetry-otel`](../packages/session/session-telemetry-otel) |
| `forge/providers-changed` | `parallel` | [`packages/experimental/forge/src/index.ts:27`](../packages/experimental/forge/src/index.ts) | `forge` (`parallel`) | `forge-session` |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:67`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:77`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:59`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/delete-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:82`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:74`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:92`](../packages/fs/fs/src/index.ts) | `liveshare` (`emit`), [`tool-fs`](../packages/fs/tool-fs) (`emit`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`emit`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`skill-filesystem`](../packages/skill/skill-filesystem), `workspace-files` |
| `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:66`](../packages/fs/fs/src/index.ts) | `liveshare` (`waterfall`), [`tool-fs`](../packages/fs/tool-fs) (`waterfall`), [`tool-str-replace-editor`](../packages/fs/tool-str-replace-editor) (`waterfall`) | [`fs-observation-policy`](../packages/fs/fs-observation-policy), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `goal/activation-changed` | `emit` | [`packages/goal/goal/src/types.ts:147`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | `remotes`, `server` |
| `goal/changed` | `emit` | [`packages/goal/goal/src/domain.ts:114`](../packages/goal/goal/src/domain.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-round-driver`](../packages/goal/goal-round-driver) |
| `hmr/change` | `emit` | [`packages/boot/hmr/src/index.ts:35`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `hmr/reload` | `emit` | [`packages/boot/hmr/src/index.ts:40`](../packages/boot/hmr/src/index.ts) | [`hmr`](../packages/boot/hmr) (`emit`) | - |
| `llm-pi-ai/request-headers` | `waterfall` | [`packages/llm/llm-pi-ai/src/index.ts:114`](../packages/llm/llm-pi-ai/src/index.ts) | [`llm-pi-ai`](../packages/llm/llm-pi-ai) (`waterfall`) | - |
| `llm/adapters-updated` | `emit` | [`packages/llm/llm/src/types.ts:24`](../packages/llm/llm/src/types.ts) | [`llm`](../packages/llm/llm) (`events.dispatch`) | [`acp`](../packages/acp/acp), `remotes` |
| `llm/models-updated` | `emit` | [`packages/llm/llm/src/types.ts:30`](../packages/llm/llm/src/types.ts) | [`llm-deepseek`](../packages/llm/llm-deepseek) (`emit`) | `remotes` |
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:75`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title) |
@@ -67,10 +69,10 @@
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:424`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:168`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:484`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:74`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:634`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:71`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
| `session-telemetry/record` | `waterfall` | [`packages/session/session-telemetry/src/index.ts:44`](../packages/session/session-telemetry/src/index.ts) | [`session-telemetry`](../packages/session/session-telemetry) (`waterfall`) | - |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`schedule`](../packages/schedule/schedule), `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/created` | `emit` | [`packages/core/session/src/index.ts:56`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | `server`, `session-controller`, [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry) |
| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:65`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `agent-team`, `file-upload`, `forge-session`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-title`](../packages/session/session-title), `ui-trajectory`, [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/event` | `emit` | [`packages/core/session/src/index.ts:76`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/acp/acp), [`agent-instructions`](../packages/context/agent-instructions), [`agent-loop`](../packages/core/agent-loop), [`agent-preset-registry`](../packages/preset/agent-preset-registry), `agent-team`, `claude-code-mods`, `client-ui-forge`, [`compaction-basic`](../packages/compaction/compaction-basic), [`file-reference-local`](../packages/context/file-reference-local), `file-upload`, `forge-session`, [`goal`](../packages/goal/goal), [`goal-round-driver`](../packages/goal/goal-round-driver), [`headless`](../packages/bundle/headless), [`loader-smoke`](../packages/test-support/loader-smoke), `product-analytics`, [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), `server`, `session-controller`, [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-telemetry`](../packages/session/session-telemetry), [`session-telemetry-otel`](../packages/session/session-telemetry-otel), [`session-title`](../packages/session/session-title), [`subagent`](../packages/subagent/subagent), [`token-meter`](../packages/llm/token-meter), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`tool-jobs`](../packages/jobs/tool-jobs), `ui-trajectory`, [`user-questions`](../packages/interaction/user-questions), [`workspace-changes`](../packages/deliverables/workspace-changes) |
| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:84`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence-jsonl`](../packages/session/session-persistence-jsonl), [`session-telemetry`](../packages/session/session-telemetry) |
Loaded 100 of 586 files, more files were not shown because too many files have changed in this diff. Show more