DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
feat(scheduler): 统一双投递与右侧任务页 (#996)
Mao Mra7a2eef1d29f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 61fc9896..a83983c8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -68,8 +68,17 @@ jobs:# dsh-tauri-ui 的构建会重新生成并压缩已提交的 Tailwind 产物。若源码新增/删除了# utility 却漏提产物,运行时只会静默缺样式;显式检查工作树可在合并前阻断漂移。- name: Verify generated Tailwind CSS is current+ id: tailwind_checkrun: git diff --exit-code -- packages/dsh-tauri-ui/src/client/styles/index.ts+ - name: Upload regenerated Tailwind CSS on drift+ if: failure() && steps.tailwind_check.outcome == 'failure'+ uses: actions/upload-artifact@v6+ with:+ name: generated-tailwind-css+ path: packages/dsh-tauri-ui/src/client/styles/index.ts+ if-no-files-found: error+- name: Type check package exportsrun: pnpm exec tsc --noEmit@@ -130,7 +139,7 @@ jobs:- name: Plugin L2 test (legacy core)env:DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli/node_modules/@deepseek-ai/dsh/lib/bin.js- run: node node_modules/vitest/vitest.mjs run --project plugin --exclude test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts+ run: node node_modules/vitest/vitest.mjs run --project plugin --exclude test/e2e/plugins/dsh-tauri-extension-panel.e2e.ts --exclude test/e2e/plugins/dsh-tauri-scheduler.e2e.ts --exclude test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts- name: Mobile settings composition (legacy core)env:@@ -154,7 +163,25 @@ jobs:- name: Host and migrated plugin contracts (current core)env:DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli-current/node_modules/@deepseek-ai/dsh/lib/bin.js- run: node node_modules/vitest/vitest.mjs run --project plugin test/e2e/plugins/dsh-host-and-core-contract.e2e.ts test/e2e/plugins/dsh-tauri-model.e2e.ts test/e2e/plugins/dsh-tauri-worktree.e2e.ts test/e2e/plugins/dsh-tauri-scheduler.e2e.ts test/e2e/plugins/dsh-tauri-experimental.e2e.ts+ run: node node_modules/vitest/vitest.mjs run --project plugin test/e2e/plugins/dsh-host-and-core-contract.e2e.ts test/e2e/plugins/dsh-tauri-model.e2e.ts test/e2e/plugins/dsh-tauri-worktree.e2e.ts test/e2e/plugins/dsh-tauri-experimental.e2e.ts++ - name: Unified scheduler host and right-sidebar contracts (current core)+ id: scheduler_contracts+ env:+ DSH_E2E_DSH_BIN: ${{ runner.temp }}/dsh-cli-current/node_modules/@deepseek-ai/dsh/lib/bin.js+ DSH_SCHEDULER_DIAGNOSTICS_DIR: ${{ runner.temp }}/scheduler-diagnostics+ run: |+ for seed in 987 988 989 990 991; do+ node node_modules/vitest/vitest.mjs run --project plugin --sequence.shuffle --sequence.seed="$seed" test/e2e/plugins/dsh-tauri-scheduler.e2e.ts test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts || exit $?+ done++ - name: Upload scheduler contract failure diagnostics+ if: failure() && steps.scheduler_contracts.outcome == 'failure'+ uses: actions/upload-artifact@v6+ with:+ name: scheduler-contract-diagnostics+ path: ${{ runner.temp }}/scheduler-diagnostics+ if-no-files-found: error# 桌面端 L3 E2E(vitest + WebdriverIO):# 驱动真实 Tauri 窗口,只能在 Windows 上跑(embedded WebDriver + WebView2)。diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex 4d442676..832b1307 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -11,7 +11,7 @@| `packages/dsh-tauri-extension` | [qinyre/dsh-plugin-capabilities](https://github.com/qinyre/dsh-plugin-capabilities) | `0.3.11` | `52e3f664dbe1c9f1166ea3cf4e7416d5352f3ee9` | `source/dsh-plugin-capabilities` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-extension/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-extension` | [anthropics/skills](https://github.com/anthropics/skills) | — | — | — | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-extension/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-extension` | [vercel-labs/skills](https://github.com/vercel-labs/skills) | — | — | — | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-extension/THIRD_PARTY_NOTICES.md) |-| `packages/dsh-tauri-scheduler` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-alpha.1` | `5badb15009ae1756c3afe0ae0cef1faafc290ccc` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md) |+| `packages/dsh-tauri-scheduler` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-alpha.1` | `ec48669f48ac81bac353fc646e7cf9c57241242f` | — | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-scheduler` | [MichengAI/dsh-automation](https://github.com/MichengAI/dsh-automation) | `0.1.42` | `e75499e55d0b8bfe85e04ba5a579080b54edff56` | `source/dsh-automation` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-pet` | [deepseek-ai/deepseek-harness](https://github.com/deepseek-ai/deepseek-harness) | `dsh-v0.2.1-alpha.1` | `5badb15009ae1756c3afe0ae0cef1faafc290ccc` | `source/deepseek-harness` | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md) || `packages/dsh-tauri-pet` | [PC2005-cloud/dsh-pet](https://github.com/PC2005-cloud/dsh-pet) | — | `e1ff8c1e4001878cbb80441262d530e16541f138` | — | [THIRD_PARTY_NOTICES.md](packages/dsh-tauri-pet/THIRD_PARTY_NOTICES.md) |diff --git a/packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.mdindex eb4a8907..220c99e0 100644--- a/packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md+++ b/packages/dsh-tauri-scheduler/THIRD_PARTY_NOTICES.md@@ -19,14 +19,14 @@ Adapted files:- `src/host/types/index.ts`- `src/client/components/menu.tsx`, `src/client/components/menu.cssr.ts`- `src/client/components/model-picker.tsx`, `src/client/components/model-picker.cssr.ts`-- `src/client/components/task-create-dialog.tsx`+- [`src/client/components/task-form.tsx`](./src/client/components/task-form.tsx) — migrated from `task-create-dialog.tsx` into the right-sidebar task tab- `src/client/components/prefill-bridge.tsx`, `src/client/prefill.ts`, `src/client/register/prefill.ts`- `src/client/types/scheduler.ts`, `src/client/types/protocol.ts`Notes:-- Adapted files carry an inline attribution comment at the top.-- Scope, deliberately retained differences and verification history: [`docs/sync-log.md`](./docs/sync-log.md).+- This notice retains attribution for the adapted panel, form and unattended executor.+- Earlier adoption scope and verification history: [`docs/sync-log.md`](./docs/sync-log.md).## Retained upstream NOTICE@@ -46,35 +46,30 @@ Copyright 2026 MichengAI contributors- Repository: <https://github.com/deepseek-ai/deepseek-harness>- Version: `dsh-v0.2.1-alpha.1`-- Revision: `5badb15009ae1756c3afe0ae0cef1faafc290ccc`-- Source: `source/deepseek-harness`-- Catalog pin: `dsh:` → `0.2.1-alpha.1` (`pnpm-workspace.yaml`)+- Refork revision: `ec48669f48ac81bac353fc646e7cf9c57241242f`+- Reference: the release-matched source at this revision; the repository submodule pointer is not advanced by this refork.+- Catalog pin: `dsh:` → `0.2.1-alpha.1` ([`pnpm-workspace.yaml`](../../pnpm-workspace.yaml))- License: MIT — Copyright (c) 2026 DeepSeek-- Not derived: the desktop counterpart of the official Schedule plugin, running on the official Host contracts.-Official packages used:--- `@deepseek-ai/dsh-agent` → `installModelSelection`-- `@deepseek-ai/dsh-llm` → `createUserMessage`-- `@deepseek-ai/dsh-user-approval` → `setApprovalPolicy`-- `@deepseek-ai/dsh-session` → session creation and append for an unattended run-- `@deepseek-ai/dsh-tools`, `@deepseek-ai/dsh-workspace` → tool registration, workspace resolution-- The first three are imported dynamically in `src/host/utils/agent-runtime.ts`; the rest are declared dependencies.--Official counterpart (official `@deepseek-ai/dsh-schedule` + `@deepseek-ai/dsh-client-ui-schedule` → this package):--- Tools: official `schedule_create` / `schedule_list` / `schedule_update` / `schedule_delete` → `scheduler_create` / `scheduler_list` / `scheduler_update` / `scheduler_delete` (`src/host/tools/`), four to four. `scheduler_update` additionally absorbs pausing/resuming (`enabled`, the official set has no toggle) and offers a `run_now` switch that also triggers an immediate manual run.-- Delivery: official durable Host-wide reminders in the **original** Session → unattended runs, each starting a **fresh** Session (`workspaceId`, `permission`, `provider`, `model`, `reasoningEffort`).-- Recurrence: official one-shot / fixed-rate / daily / weekly / cron (`createCronScheduleRecord`, `resolveCronOccurrence`, `canonicalizeCronExpression`) → `once` / `hourly` / `daily` / `interval` / `workdays` / `weekly` / `monthly` / `custom` (`SCHEDULE_KINDS` in `src/shared/constants.ts`), evaluated with the `cron-schedule` package or anchored arithmetic; no cron kind.-- Missed occurrences: official keeps only the latest missed occurrence and restores a cold Session → anchored interval/custom arithmetic plus `runs/recover` reconciliation for interrupted runs.-- UI: official task list, task detail, delivery history, clock/date pickers and recent time zones → task list, create dialog and run history (`history/{get,delete}`); no delivery history or time-zone data source.-- Official Schedule is enabled by default in the target Web bundle (`cordis.patch.yml`: id `schedule`, id `ui-schedule`); its `schedule` service and `schedule_*` tools use a different task store from this plugin's `scheduler` service and `scheduler_*` tools.--## Compatibility `0.2.0-rc.2` → `0.2.1-alpha.1`--- The target enables the official `schedule` and `ui-schedule` rows by default in the Web bundle and scopes reminder tools to Standard, Creator, and PTC presets.-- This plugin keeps its separate `scheduler` service, `scheduler_*` tools, unattended fresh-session runs, and task store. It neither disables the official rows nor imports official tasks into its own store.-- Agent model selection, approval policy, session append, and user-message construction remain compatible; no removed invariant export is consumed.+Reforked contracts and local destinations:++- [`packages/schedule/schedule/src/runtime.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/schedule/schedule/src/runtime.ts): cold-session resolution, queued user notices, context guard, persistence acknowledgment before receipt/advancement and native `workspace/session-activity` / session-stop integration → [`src/host/service/delivery.ts`](./src/host/service/delivery.ts), [`src/host/service/scheduler.ts`](./src/host/service/scheduler.ts).+- [`packages/schedule/schedule/src/delivery-history.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/schedule/schedule/src/delivery-history.ts): immutable delivery receipts, exclusive cursor pagination and retention/migration flags → [`src/host/service/history.ts`](./src/host/service/history.ts), extended with fresh-session runs under one per-task 30-day / 200-record budget.+- [`packages/client/ui-schedule/src/client/definition.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/definition.ts), [`task-tab-bindings.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/task-tab-bindings.ts), [`ScheduleTaskTab.tsx`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/ScheduleTaskTab.tsx) and [`session-link.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/session-link.ts): `scheduleTask` body/title seats, durable task identity, post-navigation read barrier, expected-record mutation and four-state session validation → [`src/client/register/task-tab.tsx`](./src/client/register/task-tab.tsx), [`src/client/service/task-tab-bindings.ts`](./src/client/service/task-tab-bindings.ts), [`src/client/components/task-tab.tsx`](./src/client/components/task-tab.tsx), [`src/client/components/task-tab-content.tsx`](./src/client/components/task-tab-content.tsx), [`src/client/components/task-tab-title.tsx`](./src/client/components/task-tab-title.tsx), [`src/client/components/session-link.ts`](./src/client/components/session-link.ts).+- [`packages/client/ui-schedule/src/client/DeliveryHistory.tsx`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/DeliveryHistory.tsx): lazy task-specific pagination, stale request isolation, cursor recovery and clipping feedback → [`src/client/components/delivery-history.tsx`](./src/client/components/delivery-history.tsx), extended to both delivery modes.+- [`packages/client/ui-schedule/src/client/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/index.ts), `ScheduleCatalogAction`, `SessionSchedule` and `ScheduleTurnCard`: creation-card replay, `schedule-created` turn tail (order `20`), `schedule-mark` / `schedule-tasks` session-row seats, `schedule-catalog` header utility (order `-5`) and `schedule.delete-toast` shell overlay → [`src/client/register/ambient.tsx`](./src/client/register/ambient.tsx), [`src/client/components/schedule-catalog-action.tsx`](./src/client/components/schedule-catalog-action.tsx), [`src/client/components/session-schedule-mark.tsx`](./src/client/components/session-schedule-mark.tsx), [`src/client/components/session-schedule-hover.tsx`](./src/client/components/session-schedule-hover.tsx), [`src/client/components/schedule-created-card.tsx`](./src/client/components/schedule-created-card.tsx), [`src/client/components/schedule-current-cards.tsx`](./src/client/components/schedule-current-cards.tsx), [`src/client/components/schedule-turn-card.tsx`](./src/client/components/schedule-turn-card.tsx).+- [`packages/client/ui-schedule/src/client/TaskDetail.tsx`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/client/ui-schedule/src/client/TaskDetail.tsx), `TaskManagerPage.module.css`, `DatePicker.tsx`, `ClockPicker.tsx`, `schedule-format.ts` and `recent-time-zones.ts`: rule/history strip, linked-session/menu/close actions, responsive detail gutters, borderless name, compact instruction, row-based run-time card, staged save footer, calendar/clock popovers, searchable localized IANA zones and compact history timeline → [`src/client/components/task-detail.tsx`](./src/client/components/task-detail.tsx), [`src/client/components/task-form.tsx`](./src/client/components/task-form.tsx), [`src/client/components/delivery-history.tsx`](./src/client/components/delivery-history.tsx), and shared `dsh-tauri-ui` date/time pickers. Runtime metadata remains separate from the retained editing snapshot; local one-shot tasks keep their existing zone/absolute-instant contract and millisecond precision.+- [`packages/session/session-projection/src/index.ts`](https://github.com/deepseek-ai/deepseek-harness/blob/ec48669f48ac81bac353fc646e7cf9c57241242f/packages/session/session-projection/src/index.ts): public durable projection registration and catalog wire values → [`src/host/events/session-origin.ts`](./src/host/events/session-origin.ts), restoring scheduled fresh-session source marks without history scans or a custom session-header origin.+- Official delete store / `DeleteToast` / Banner confirmation and feedback → [`src/client/store/modules/deletion.ts`](./src/client/store/modules/deletion.ts), [`src/client/service/deletion.ts`](./src/client/service/deletion.ts), [`src/client/components/schedule-deletion-overlay.tsx`](./src/client/components/schedule-deletion-overlay.tsx). The local shared `Toast` reexports the same official Banner control.++Retained local behavior and assembly:++- [`cordis.patch.yml`](./cordis.patch.yml) disables official `schedule` and `ui-schedule`. This package alone owns the task store, `scheduler_*` tools, HTTP routes and task UI; it does not runtime-import either disabled feature package.+- `delivery: 'this-session'` binds a validated original session and inherits its workspace, permission and model. `delivery: 'new-session'` retains unattended execution and per-task workspace / permission / provider / model / reasoning-effort overrides. Legacy local tasks are normalized as fresh-session tasks; no implicit import from the disabled official store is performed.+- Reversible `enabled` pause/resume remains distinct from terminal `inactive`. Manual runs, recommendations and `runs/recover` remain supported. Both deliveries coalesce missed recurring occurrences to the latest due instant and preserve IANA calendar / DST semantics for the eight local schedule kinds.+- The main task list, search and chat/manual creation buttons retain their wording. The catalog opens details in place without navigating to any conversation; only its explicit linked-session action navigates. The same rule/history view renders in native session task tabs. Local `draft: true` creation, collapsed delivery/resource settings and pause/resume share the reforked detail layout; page-level tabs and global-task arrow markers are removed.+- [`src/host/utils/agent-runtime.ts`](./src/host/utils/agent-runtime.ts) uses the host loader for `createUserMessage`, scoped Agent/model selection and approval helpers so runtime module identity remains shared. Session and workspace contracts are capability-checked; unsupported public UI seats are disabled with a warning rather than patched through private React state.+- A durable prepared-message journal reconciles receipt failures using the same message identity, including messages already consumed into the session surface. Host session reads, resolution and persistence waits are bounded to 10 seconds; an unacknowledged flush remains pending and reuses its in-flight promise on a later drive. The timeout does not cancel the host operation or claim durability. This is not an exactly-once execution guarantee across a crash between conversation persistence and task-state persistence.## Licensediff --git a/packages/dsh-tauri-scheduler/cordis.patch.yml b/packages/dsh-tauri-scheduler/cordis.patch.ymlindex f9e0be13..70c3d7c0 100644--- a/packages/dsh-tauri-scheduler/cordis.patch.yml+++ b/packages/dsh-tauri-scheduler/cordis.patch.yml@@ -1,3 +1,7 @@+- id: schedule+ disabled: true+- id: ui-schedule+ disabled: true- insert:- id: dsh-tauri-schedulername: dsh-tauri-schedulerdiff --git a/packages/dsh-tauri-scheduler/package.json b/packages/dsh-tauri-scheduler/package.jsonindex 5b2a6ea9..f568c24f 100644--- a/packages/dsh-tauri-scheduler/package.json+++ b/packages/dsh-tauri-scheduler/package.json@@ -2,7 +2,7 @@"name": "dsh-tauri-scheduler","type": "module","version": "1.0.0",- "description": "DeepSeek Harness 桌面面板的定时任务:创建每日/间隔/工作日/每周自动化,按计划在全新会话中运行,并可查看运行历史。",+ "description": "DeepSeek Harness 桌面定时任务:向当前会话投递提醒或启动新会话执行,统一管理计划、会话关联和投递历史。","author": "Hairyf <[email protected]>","license": "MIT","homepage": "https://github.com/dsh-tauri-desk/dsh-tauri-plugins#readme",diff --git a/packages/dsh-tauri-scheduler/src/client/apis/index.ts b/packages/dsh-tauri-scheduler/src/client/apis/index.tsindex 57ba95d5..eec415e1 100644--- a/packages/dsh-tauri-scheduler/src/client/apis/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/apis/index.ts@@ -39,7 +39,7 @@ export function postTasksRun(body: Types.PostApiTauriSchedulerTasksRunBody, opti}/** @method get */-export function getHistory(params?: Types.GetApiTauriSchedulerHistoryQuery, options?: FetchOptions) {+export function getHistory(params: Types.GetApiTauriSchedulerHistoryQuery, options?: FetchOptions) {return ofetch<Types.GetApiTauriSchedulerHistoryResponse>("/api/tauri/scheduler/history", { method: "get", params, ...options });}diff --git a/packages/dsh-tauri-scheduler/src/client/apis/index.type.ts b/packages/dsh-tauri-scheduler/src/client/apis/index.type.tsindex b967a4a2..29e0b70f 100644--- a/packages/dsh-tauri-scheduler/src/client/apis/index.type.ts+++ b/packages/dsh-tauri-scheduler/src/client/apis/index.type.ts@@ -1,6 +1,9 @@export type GetApiTauriSchedulerTasksResponse = {tasks: {id: string;+ delivery: "this-session" | "new-session";+ status: "active" | "inactive";+ sessionId?: undefined | string;name: string;schedule: { kind: "once"; at: string; timeZone: string } | { kind: "hourly"; minute: number; timeZone: string } | { kind: "daily"; time: string; timeZone: string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone: string } | { kind: "workdays"; time: string; timeZone: string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone: string } | { kind: "monthly"; day: number; time: string; timeZone: string } | { kind: "custom"; everyDays: number; anchor: string; time: string; timeZone: string };prompt: string;@@ -27,6 +30,9 @@ export type PostApiTauriSchedulerTasksResponse = {| undefined| {id: string;+ delivery: "this-session" | "new-session";+ status: "active" | "inactive";+ sessionId?: undefined | string;name: string;schedule: { kind: "once"; at: string; timeZone: string } | { kind: "hourly"; minute: number; timeZone: string } | { kind: "daily"; time: string; timeZone: string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone: string } | { kind: "workdays"; time: string; timeZone: string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone: string } | { kind: "monthly"; day: number; time: string; timeZone: string } | { kind: "custom"; everyDays: number; anchor: string; time: string; timeZone: string };prompt: string;@@ -46,6 +52,7 @@ export type PostApiTauriSchedulerTasksResponse = {waiting?: undefined | false | true;};error?: undefined | string;+ code?: undefined | string;};export type PutApiTauriSchedulerTasksResponse = {ok?: undefined | false | true;@@ -53,6 +60,9 @@ export type PutApiTauriSchedulerTasksResponse = {| undefined| {id: string;+ delivery: "this-session" | "new-session";+ status: "active" | "inactive";+ sessionId?: undefined | string;name: string;schedule: { kind: "once"; at: string; timeZone: string } | { kind: "hourly"; minute: number; timeZone: string } | { kind: "daily"; time: string; timeZone: string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone: string } | { kind: "workdays"; time: string; timeZone: string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone: string } | { kind: "monthly"; day: number; time: string; timeZone: string } | { kind: "custom"; everyDays: number; anchor: string; time: string; timeZone: string };prompt: string;@@ -72,14 +82,18 @@ export type PutApiTauriSchedulerTasksResponse = {waiting?: undefined | false | true;};error?: undefined | string;+ code?: undefined | string;};-export type DeleteApiTauriSchedulerTasksResponse = { ok?: undefined | false | true; error?: undefined | string };+export type DeleteApiTauriSchedulerTasksResponse = { ok?: undefined | false | true; error?: undefined | string; code?: undefined | string };export type PostApiTauriSchedulerTasksToggleResponse = {ok?: undefined | false | true;task?:| undefined| {id: string;+ delivery: "this-session" | "new-session";+ status: "active" | "inactive";+ sessionId?: undefined | string;name: string;schedule: { kind: "once"; at: string; timeZone: string } | { kind: "hourly"; minute: number; timeZone: string } | { kind: "daily"; time: string; timeZone: string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone: string } | { kind: "workdays"; time: string; timeZone: string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone: string } | { kind: "monthly"; day: number; time: string; timeZone: string } | { kind: "custom"; everyDays: number; anchor: string; time: string; timeZone: string };prompt: string;@@ -99,11 +113,23 @@ export type PostApiTauriSchedulerTasksToggleResponse = {waiting?: undefined | false | true;};error?: undefined | string;+ code?: undefined | string;};-export type PostApiTauriSchedulerTasksRunResponse = { ok?: undefined | false | true; error?: undefined | string };-export type GetApiTauriSchedulerHistoryResponse = { runs: { id: string; taskId: string; taskName: string; trigger: "schedule" | "manual"; status: "queued" | "running" | "succeeded" | "failed" | "interrupted" | "skipped" | "cancelled"; scheduledFor: string; startedAt: string; finishedAt?: undefined | string; sessionId?: undefined | string; error?: undefined | string }[] };+export type PostApiTauriSchedulerTasksRunResponse = { ok?: undefined | false | true; error?: undefined | string; code?: undefined | string };+export type GetApiTauriSchedulerHistoryResponse =+ | { ok: false; error: string; code?: undefined | string }+ | ({ ok: true } & {+ records: ({ id: string; taskId: string; taskName: string; delivery: "this-session"; occurrence: string; trigger: "schedule" | "manual"; sessionId: string; scheduledAt: string; deliveredAt: string; messageId: string; prompt: string } | ({ id: string; taskId: string; taskName: string; prompt?: undefined | string; trigger: "schedule" | "manual"; status: "queued" | "running" | "succeeded" | "failed" | "interrupted" | "skipped" | "cancelled"; scheduledFor: string; startedAt: string; finishedAt?: undefined | string; sessionId?: undefined | string; error?: undefined | string } & { delivery: "new-session"; occurrence: string }))[];+ runs: { id: string; taskId: string; taskName: string; prompt?: undefined | string; trigger: "schedule" | "manual"; status: "queued" | "running" | "succeeded" | "failed" | "interrupted" | "skipped" | "cancelled"; scheduledFor: string; startedAt: string; finishedAt?: undefined | string; sessionId?: undefined | string; error?: undefined | string }[];+ nextBefore?: undefined | string;+ earlierRecordsUnavailable: false | true;+ earlierRecordsPruned: false | true;+ retention: { days: number; records: number };+ });export type GetApiTauriSchedulerHistoryQueryTaskId = undefined | string;-export type DeleteApiTauriSchedulerHistoryResponse = { ok?: undefined | false | true; error?: undefined | string };+export type GetApiTauriSchedulerHistoryQueryLimit = number;+export type GetApiTauriSchedulerHistoryQueryBefore = undefined | string;+export type DeleteApiTauriSchedulerHistoryResponse = { ok?: undefined | false | true; error?: undefined | string; code?: undefined | string };export type GetApiTauriSchedulerOptionsResponse = {workspaces: { id: string; path: string; title: string }[];permissions: { value: string; name: string; description?: undefined | string }[];@@ -112,9 +138,11 @@ export type GetApiTauriSchedulerOptionsResponse = {failures: { provider: string; providerLabel: string; message: string }[];defaultModel: null | { provider: string; providerLabel: string; model: string; label: string; description?: undefined | string; reasoning?: undefined | { efforts: { id: string; name: string; description?: undefined | string }[]; defaultEffort?: undefined | string } };};-export type PostApiTauriSchedulerRunsRecoverResponse = { ok?: undefined | false | true; error?: undefined | string };+export type PostApiTauriSchedulerRunsRecoverResponse = { ok?: undefined | false | true; error?: undefined | string; code?: undefined | string };export interface PostApiTauriSchedulerTasksBody {+ delivery: "this-session" | "new-session";+ sessionId?: undefined | string;name: string;schedule: { kind: "once"; at: string; timeZone?: undefined | string } | { kind: "hourly"; minute: number; timeZone?: undefined | string } | { kind: "daily"; time: string; timeZone?: undefined | string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone?: undefined | string } | { kind: "workdays"; time: string; timeZone?: undefined | string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone?: undefined | string } | { kind: "monthly"; day: number; time: string; timeZone?: undefined | string } | { kind: "custom"; everyDays: number; anchor?: undefined | string; time: string; timeZone?: undefined | string };prompt: string;@@ -128,6 +156,31 @@ export interface PostApiTauriSchedulerTasksBody {}export interface PutApiTauriSchedulerTasksBody {id: string;+ expected: {+ id: string;+ delivery: "this-session" | "new-session";+ status: "active" | "inactive";+ sessionId?: undefined | string;+ name: string;+ schedule: { kind: "once"; at: string; timeZone: string } | { kind: "hourly"; minute: number; timeZone: string } | { kind: "daily"; time: string; timeZone: string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone: string } | { kind: "workdays"; time: string; timeZone: string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone: string } | { kind: "monthly"; day: number; time: string; timeZone: string } | { kind: "custom"; everyDays: number; anchor: string; time: string; timeZone: string };+ prompt: string;+ recommendationId?: undefined | string;+ workspaceId?: undefined | string;+ permission?: undefined | string;+ provider?: undefined | string;+ model?: undefined | string;+ reasoningEffort?: undefined | string;+ module?: undefined | string;+ agentPreset?: undefined | string;+ enabled: false | true;+ createdAt: string;+ updatedAt: string;+ lastRunAt?: undefined | string;+ nextRunAt?: undefined | string;+ waiting?: undefined | false | true;+ };+ delivery?: undefined | "this-session" | "new-session";+ sessionId?: undefined | string;name?: undefined | string;schedule?: undefined | { kind: "once"; at: string; timeZone?: undefined | string } | { kind: "hourly"; minute: number; timeZone?: undefined | string } | { kind: "daily"; time: string; timeZone?: undefined | string } | { kind: "interval"; everyMinutes: number; anchor?: undefined | string; timeZone?: undefined | string } | { kind: "workdays"; time: string; timeZone?: undefined | string } | { kind: "weekly"; weekdays: ("MO" | "TU" | "WE" | "TH" | "FR" | "SA" | "SU")[]; time: string; timeZone?: undefined | string } | { kind: "monthly"; day: number; time: string; timeZone?: undefined | string } | { kind: "custom"; everyDays: number; anchor?: undefined | string; time: string; timeZone?: undefined | string };prompt?: undefined | string;@@ -157,4 +210,6 @@ export interface GetApiTauriSchedulerTasksQuery {}export interface GetApiTauriSchedulerHistoryQuery {taskId?: GetApiTauriSchedulerHistoryQueryTaskId;+ limit: GetApiTauriSchedulerHistoryQueryLimit;+ before?: GetApiTauriSchedulerHistoryQueryBefore;}diff --git a/packages/dsh-tauri-scheduler/src/client/components/ambient-test.harness.ts b/packages/dsh-tauri-scheduler/src/client/components/ambient-test.harness.tsnew file mode 100644index 00000000..73c84e48--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/ambient-test.harness.ts@@ -0,0 +1,59 @@+import type { ConversationTurnDataMap, TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client'+import type { Translate } from '../locales/index.types'+import type { ScheduleTurnData, ScheduleTurnOwner } from '../service/schedule-turn'+import type { TaskView } from '../types'++export const ambientTranslate: Translate = (key, params) => {+ const value = params?.name ?? params?.count+ return value === undefined ? key : `${key}:${value}`+}++export function ambientTask(id: string, changes: Partial<TaskView> = {}): TaskView {+ return {+ id,+ name: `Task ${id}`,+ prompt: 'Reminder',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'owner',+ enabled: true,+ schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' },+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+ ...changes,+ }+}++export function ambientTurn(tasks: readonly TaskView[], cursor = Number.POSITIVE_INFINITY): ScheduleTurnOwner {+ const data: ScheduleTurnData = { created: tasks.map((task, index) => ({ seq: 4 + index * 4, time: 1700000000000 + index, callId: `call-${task.id}`, task })) }+ const values: Partial<ConversationTurnDataMap> = { 'schedule-created': data }+ const turn: TurnLocation = {+ turn: 3,+ status: 'open',+ steps: [],+ start: undefined,+ end: undefined,+ data: { get: key => values[key], source: key => ({ getSnapshot: () => values[key], subscribe: () => () => {} }) },+ }+ return { turn, seq: cursor, openFile: () => {} }+}++export async function ambientClientFacade() {+ return {+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define'),+ ...await import('../../../../dsh-tauri/src/client/modules/reause'),+ ...await import('../../../../dsh-tauri/src/client/modules/date-fns'),+ ...await import('../../../../dsh-tauri/src/client/modules/tailwind-variants'),+ }+}++export async function ambientUiFacade() {+ return {+ ...await import('../../../../dsh-tauri-ui/src/client/components/action'),+ ...await import('../../../../dsh-tauri-ui/src/client/components/button'),+ ...await import('../../../../dsh-tauri-ui/src/client/components/card'),+ ...await import('../../../../dsh-tauri-ui/src/client/components/icon'),+ ...await import('../../../../dsh-tauri-ui/src/client/components/icons'),+ ...await import('./ambient-test.ui').then(ui => ({ Menu: ui.AmbientMenu, Modal: ui.AmbientModal, Toast: ui.AmbientToast })),+ }+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/ambient-test.ui.tsx b/packages/dsh-tauri-scheduler/src/client/components/ambient-test.ui.tsxnew file mode 100644index 00000000..3cc74971--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/ambient-test.ui.tsx@@ -0,0 +1,61 @@+import type { Menu, Modal, Toast } from 'dsh-tauri-ui/client'+import type { ComponentProps, ReactElement } from 'react'+import { createPortal } from 'react-dom'+import { PrimitiveButton } from './scheduler-client.test.ui'++export { PrimitiveButton }++export function AmbientMenu({ open, anchor, children, onClose, portal }: ComponentProps<typeof Menu>): ReactElement {+ const menu = open+ ? (+ <div+ role="menu"+ onKeyDown={(event) => {+ if (event.key === 'Escape')+ onClose()+ }}+ >+ {children}+ </div>+ )+ : null+ return (+ <>+ {anchor}+ {portal && menu ? createPortal(menu, document.body) : menu}+ </>+ )+}++export function AmbientModal({ open, title, description, closeLabel, children, footer, onClose }: ComponentProps<typeof Modal>): ReactElement | null {+ return open+ ? createPortal(+ <div+ role="dialog"+ aria-modal="true"+ aria-label={title}+ onKeyDown={(event) => {+ if (event.key === 'Escape')+ onClose()+ }}+ >+ <h2>{title}</h2>+ <p>{description}</p>+ <button type="button" aria-label={closeLabel} onClick={onClose} />+ {children}+ {footer}+ </div>,+ document.body,+ )+ : null+}++export function AmbientToast({ text, tone, onDone }: ComponentProps<typeof Toast>): ReactElement {+ return createPortal(+ <div role="alert" data-tone={tone}>+ {text}+ <button type="button" aria-label="complete-banner" onClick={onDone} />+ </div>,+ document.body,+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/delivery-history.test.tsx b/packages/dsh-tauri-scheduler/src/client/components/delivery-history.test.tsxnew file mode 100644index 00000000..b35c09cd--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/delivery-history.test.tsx@@ -0,0 +1,402 @@+import type { SessionId } from 'dsh-tauri/client'+// @vitest-environment jsdom+import type { ComponentProps } from 'react'+import type { HistoryPage } from '../types'+import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { StrictMode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { loadTaskHistory } from '../service/scheduler'+import { DeliveryHistory } from './delivery-history'+import { deferred, deliveryFixture, pageFixture, runFixture, sessionsFixture, translate, workspacesFixture } from './scheduler-client.test.harness'++vi.mock('../service/scheduler', () => ({ loadTaskHistory: vi.fn() }))+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => {+ const ui = await import('./scheduler-client.test.ui')+ return { Button: ui.PrimitiveButton, Input: ui.PrimitiveInput, Menu: ui.PrimitiveMenu }+})+vi.mock('dsh-tauri-ui/client', async () => (await import('./scheduler-client.test.ui')).schedulerClientUi())++beforeEach(() => {+ vi.resetAllMocks()+ vi.mocked(loadTaskHistory).mockResolvedValue(pageFixture())+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++async function renderHistory(overrides: Partial<ComponentProps<typeof DeliveryHistory>> = {}, strict = false) {+ const props: ComponentProps<typeof DeliveryHistory> = {+ taskId: 'task-a',+ t: translate,+ timeZone: 'UTC',+ sessions: sessionsFixture(),+ workspaces: workspacesFixture(),+ onOpenSession: vi.fn(),+ ...overrides,+ }+ const view = render(strict ? <StrictMode><DeliveryHistory {...props} /></StrictMode> : <DeliveryHistory {...props} />)+ await act(async () => {})+ return { ...view, props }+}++async function click(view: Awaited<ReturnType<typeof renderHistory>>, name: string): Promise<void> {+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name }))+ })+}++async function resolvePage(response: ReturnType<typeof deferred<HistoryPage>>, page: HistoryPage): Promise<void> {+ await act(async () => {+ response.resolve(page)+ await response.promise+ })+}++async function rejectPage(response: ReturnType<typeof deferred<HistoryPage>>, error: Error): Promise<void> {+ await act(async () => {+ response.reject(error)+ await expect(response.promise).rejects.toBe(error)+ })+}++describe('deliveryHistory rendering and request contract', () => {+ it('keeps the normal timeline to one time and instruction instead of duplicate delivery metadata', async () => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([deliveryFixture('compact')]))+ const view = await renderHistory()+ const row = view.getByRole('listitem')+ expect(row.querySelectorAll('time')).toHaveLength(1)+ expect(within(row).getByText('Prompt compact')).not.toBeNull()+ expect(view.queryByText('delivery.this-session · triggerSchedule')).toBeNull()+ expect(row.textContent).not.toContain('history.scheduled')+ expect(row.textContent).not.toContain('history.delivered')+ expect(row.textContent).not.toContain('history.open')+ expect(view.queryByRole('button', { name: 'refresh' })).toBeNull()+ })++ it('accepts its first page after StrictMode effect replay', async () => {+ const response = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementation(() => response.promise)+ const view = await renderHistory({}, true)+ expect(loadTaskHistory).toHaveBeenCalledWith('task-a', 20, undefined)+ await resolvePage(response, pageFixture([deliveryFixture('strict-current')]))+ expect(view.getAllByRole('listitem')).toHaveLength(1)+ expect(view.getByText('Prompt strict-current').textContent).toBe('Prompt strict-current')+ expect(view.queryByText('loading')).toBeNull()+ expect(view.queryByRole('alert')).toBeNull()+ })++ it('loads the explicit task with limit 20 and renders immutable prompts for both delivery modes', async () => {+ const response = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => response.promise)+ const view = await renderHistory()+ expect(loadTaskHistory).toHaveBeenCalledExactlyOnceWith('task-a', 20, undefined)+ expect(view.getByText('loading').textContent).toBe('loading')+ await resolvePage(response, pageFixture([deliveryFixture('reminder'), runFixture('run')]))+ const records = view.getAllByRole('listitem')+ expect(records).toHaveLength(2)+ expect(within(records[0]!).getByText('Prompt reminder').textContent).toBe('Prompt reminder')+ expect(within(records[1]!).getByText('Prompt run').textContent).toBe('Prompt run')+ expect(within(records[1]!).getByText('Run failed').textContent).toBe('Run failed')+ const format = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone: 'UTC' })+ expect(records.map(record => record.querySelector('time')!.dateTime)).toEqual(['2030-01-02T01:00:00.000Z', '2030-01-02T02:00:00.000Z'])+ expect(records.map(record => record.querySelector('time')!.textContent)).toEqual(['2030-01-02T01:00:00.000Z', '2030-01-02T02:00:00.000Z'].map(at => format.format(new Date(at))))+ expect(records.map(record => record.querySelectorAll('time').length)).toEqual([1, 1])+ expect(view.queryByText('loading')).toBeNull()+ })++ it('shows the empty state only after a successful empty page', async () => {+ const response = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => response.promise)+ const view = await renderHistory({ taskId: 'empty-task' })+ expect(view.queryByText('history.empty')).toBeNull()+ await resolvePage(response, pageFixture())+ expect(view.getByText('history.empty').textContent).toBe('history.empty')+ expect(view.queryAllByRole('listitem')).toHaveLength(0)+ expect(loadTaskHistory).toHaveBeenCalledExactlyOnceWith('empty-task', 20, undefined)+ })++ it('falls back to the original timestamp when the configured timezone cannot be formatted', async () => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([deliveryFixture('reminder')]))+ const view = await renderHistory({ timeZone: 'Invalid/Timezone' })+ expect(view.container.querySelector('time')!.textContent).toBe('2030-01-02T01:00:00.000Z')+ expect(view.container.querySelectorAll('time')).toHaveLength(1)+ })++ it.each([+ [false, false],+ [true, false],+ [false, true],+ [true, true],+ ])('renders unavailable=%s and pruned=%s as distinct retention facts', async (earlierRecordsUnavailable, earlierRecordsPruned) => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([deliveryFixture('record')], {+ earlierRecordsUnavailable,+ earlierRecordsPruned,+ retention: { days: 7, records: 123 },+ }))+ const view = await renderHistory()+ expect(view.queryAllByText('history.unavailable')).toHaveLength(earlierRecordsUnavailable ? 1 : 0)+ expect(view.queryAllByText('history.pruned:days=7;records=123')).toHaveLength(earlierRecordsPruned ? 1 : 0)+ expect(view.getByText('Prompt record').textContent).toBe('Prompt record')+ })+})++describe('deliveryHistory pagination and recovery', () => {+ it('appends before pages without duplicating existing ids or replacing their original content', async () => {+ const second = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('newest'), runFixture('shared')], { nextBefore: 'cursor-first' }))+ .mockImplementationOnce(() => second.promise)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('oldest')]))+ const view = await renderHistory()+ await click(view, 'history.more')+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-a', 20, 'cursor-first']])+ expect((view.getByRole('button', { name: 'history.more' }) as HTMLButtonElement).disabled).toBe(true)+ await resolvePage(second, pageFixture([runFixture('shared', { prompt: 'Do not replace saved snapshot' }), deliveryFixture('older')], { nextBefore: 'cursor-second' }))+ expect(view.getAllByRole('listitem')).toHaveLength(3)+ expect(view.getAllByRole('listitem').map(item => within(item).getByText(/^Prompt /).textContent)).toEqual(['Prompt newest', 'Prompt shared', 'Prompt older'])+ expect(view.queryByText('Do not replace saved snapshot')).toBeNull()+ await click(view, 'history.more')+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-a', 20, 'cursor-first'], ['task-a', 20, 'cursor-second']])+ expect(view.getAllByRole('listitem').map(item => within(item).getByText(/^Prompt /).textContent)).toEqual(['Prompt newest', 'Prompt shared', 'Prompt older', 'Prompt oldest'])+ expect(view.queryByRole('button', { name: 'history.more' })).toBeNull()+ })++ it('does not launch duplicate pagination requests before the loading state rerenders', async () => {+ const next = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('newest')], { nextBefore: 'cursor-first' }))+ .mockImplementationOnce(() => next.promise)+ const view = await renderHistory()+ const more = view.getByRole('button', { name: 'history.more' })+ await act(async () => {+ fireEvent.click(more)+ fireEvent.click(more)+ fireEvent.click(more)+ })+ expect(loadTaskHistory).toHaveBeenCalledTimes(2)+ await resolvePage(next, pageFixture([deliveryFixture('older')]))+ expect(view.getAllByRole('listitem')).toHaveLength(2)+ })++ it('keeps the failed before cursor and existing records available for retry', async () => {+ const failed = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('newest')], { nextBefore: 'cursor-first' }))+ .mockImplementationOnce(() => failed.promise)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('older')]))+ const view = await renderHistory()+ await click(view, 'history.more')+ await rejectPage(failed, new Error('History storage unavailable'))+ expect(view.getByRole('alert').textContent).toBe('History storage unavailable')+ expect(view.getByText('Prompt newest').textContent).toBe('Prompt newest')+ expect((view.getByRole('button', { name: 'history.more' }) as HTMLButtonElement).disabled).toBe(false)+ await click(view, 'history.more')+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-a', 20, 'cursor-first'], ['task-a', 20, 'cursor-first']])+ expect(view.queryByRole('alert')).toBeNull()+ expect(view.getAllByRole('listitem')).toHaveLength(2)+ })++ it('retries a failed initial read through refresh instead of presenting a false empty result', async () => {+ const failed = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockImplementationOnce(() => failed.promise)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('recovered')]))+ const view = await renderHistory()+ await rejectPage(failed, new Error('Initial read failed'))+ expect(view.getByRole('alert').textContent).toBe('Initial read failed')+ expect(view.queryByText('history.empty')).toBeNull()+ await click(view, 'refresh')+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-a', 20, undefined]])+ expect(view.queryByRole('alert')).toBeNull()+ expect(view.getByText('Prompt recovered').textContent).toBe('Prompt recovered')+ })++ it('refreshes from the first page after pruning makes the before cursor invalid', async () => {+ const pruned = deferred<HistoryPage>()+ const fresh = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('stale')], { nextBefore: 'deleted-cursor' }))+ .mockImplementationOnce(() => pruned.promise)+ .mockImplementationOnce(() => fresh.promise)+ const view = await renderHistory()+ await click(view, 'history.more')+ await rejectPage(pruned, Object.assign(new Error('Cursor no longer retained'), { code: 'delivery_cursor_not_found' }))+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-a', 20, 'deleted-cursor'], ['task-a', 20, undefined]])+ expect(view.queryByText('Prompt stale')).toBeNull()+ expect(view.queryByRole('alert')).toBeNull()+ expect(view.getByText('loading').textContent).toBe('loading')+ await resolvePage(fresh, pageFixture([deliveryFixture('fresh')], { earlierRecordsPruned: true, retention: { days: 2, records: 10 } }))+ expect(view.getByText('Prompt fresh').textContent).toBe('Prompt fresh')+ expect(view.getByText('history.pruned:days=2;records=10').textContent).toBe('history.pruned:days=2;records=10')+ expect(view.queryByText('loading')).toBeNull()+ })+})++describe('deliveryHistory request lifetime isolation', () => {+ it('ignores a delayed previous-task page while the new task is still loading', async () => {+ const previous = deferred<HistoryPage>()+ const current = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => previous.promise).mockImplementationOnce(() => current.promise)+ const view = await renderHistory()+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} taskId="task-b" />)+ })+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-b', 20, undefined]])+ await resolvePage(previous, pageFixture([deliveryFixture('previous', { taskId: 'task-a' })]))+ expect(view.queryAllByRole('listitem')).toHaveLength(0)+ expect(view.getByText('loading').textContent).toBe('loading')+ await resolvePage(current, pageFixture([deliveryFixture('current', { taskId: 'task-b' })]))+ expect(view.queryByText('Prompt previous')).toBeNull()+ expect(view.getByText('Prompt current').textContent).toBe('Prompt current')+ })++ it('ignores an earlier navigation response even when navigation returns to the same task id', async () => {+ const firstA = deferred<HistoryPage>()+ const taskB = deferred<HistoryPage>()+ const latestA = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => firstA.promise).mockImplementationOnce(() => taskB.promise).mockImplementationOnce(() => latestA.promise)+ const view = await renderHistory()+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} taskId="task-b" />)+ })+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} taskId="task-a" />)+ })+ await resolvePage(latestA, pageFixture([deliveryFixture('latest-a')]))+ await resolvePage(taskB, pageFixture([deliveryFixture('task-b', { taskId: 'task-b' })]))+ await resolvePage(firstA, pageFixture([deliveryFixture('old-a')]))+ expect(vi.mocked(loadTaskHistory).mock.calls).toEqual([['task-a', 20, undefined], ['task-b', 20, undefined], ['task-a', 20, undefined]])+ expect(view.getAllByRole('listitem')).toHaveLength(1)+ expect(view.getByText('Prompt latest-a').textContent).toBe('Prompt latest-a')+ expect(view.queryByText('Prompt old-a')).toBeNull()+ expect(view.queryByText('Prompt task-b')).toBeNull()+ })++ it('does not merge an earlier before response into a freshly refreshed first page', async () => {+ const older = deferred<HistoryPage>()+ const fresh = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory)+ .mockResolvedValueOnce(pageFixture([deliveryFixture('old-first')], { nextBefore: 'old-cursor' }))+ .mockImplementationOnce(() => older.promise)+ .mockImplementationOnce(() => fresh.promise)+ const view = await renderHistory()+ await click(view, 'history.more')+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} refreshKey="fresh-receipt" />)+ })+ await resolvePage(fresh, pageFixture([deliveryFixture('fresh-first')]))+ await resolvePage(older, pageFixture([deliveryFixture('stale-older')], { nextBefore: 'stale-cursor' }))+ expect(view.getAllByRole('listitem')).toHaveLength(1)+ expect(view.getByText('Prompt fresh-first').textContent).toBe('Prompt fresh-first')+ expect(view.queryByText('Prompt stale-older')).toBeNull()+ expect(view.queryByRole('button', { name: 'history.more' })).toBeNull()+ })++ it('reloads the first page when the successful task refresh key changes', async () => {+ const stale = deferred<HistoryPage>()+ const latest = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => stale.promise).mockImplementationOnce(() => latest.promise)+ const view = await renderHistory({ refreshKey: 'revision-1' })+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} refreshKey="revision-2" />)+ })+ await resolvePage(latest, pageFixture([deliveryFixture('latest')]))+ await resolvePage(stale, pageFixture([deliveryFixture('stale')]))+ expect(loadTaskHistory).toHaveBeenCalledTimes(2)+ expect(view.getByText('Prompt latest').textContent).toBe('Prompt latest')+ expect(view.queryByText('Prompt stale')).toBeNull()+ })++ it('does not allow a stale cursor failure to trigger a refresh in the new task', async () => {+ const stale = deferred<HistoryPage>()+ const current = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => stale.promise).mockImplementationOnce(() => current.promise)+ const view = await renderHistory()+ await act(async () => {+ view.rerender(<DeliveryHistory {...view.props} taskId="task-b" />)+ })+ await rejectPage(stale, Object.assign(new Error('Old cursor missing'), { code: 'delivery_cursor_not_found' }))+ expect(loadTaskHistory).toHaveBeenCalledTimes(2)+ expect(view.queryByRole('alert')).toBeNull()+ expect(view.getByText('loading').textContent).toBe('loading')+ await resolvePage(current, pageFixture([deliveryFixture('current', { taskId: 'task-b' })]))+ expect(view.getByText('Prompt current').textContent).toBe('Prompt current')+ })++ it('ignores success from an unmounted history component without contaminating its replacement', async () => {+ const stale = deferred<HistoryPage>()+ const current = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementationOnce(() => stale.promise).mockImplementationOnce(() => current.promise)+ const previousView = await renderHistory()+ previousView.unmount()+ const view = await renderHistory({ taskId: 'task-b' })+ await resolvePage(current, pageFixture([deliveryFixture('current', { taskId: 'task-b' })]))+ await resolvePage(stale, pageFixture([deliveryFixture('unmounted')]))+ expect(previousView.container.textContent).toBe('')+ expect(view.getAllByRole('listitem')).toHaveLength(1)+ expect(view.getByText('Prompt current').textContent).toBe('Prompt current')+ expect(view.queryByText('Prompt unmounted')).toBeNull()+ expect(previousView.props.onOpenSession).not.toHaveBeenCalled()+ })++ it.each([false, true])('does not retry a cursor failure after its history component unmounts with StrictMode=%s', async (strict) => {+ const response = deferred<HistoryPage>()+ vi.mocked(loadTaskHistory).mockImplementation(() => response.promise)+ const view = await renderHistory({}, strict)+ expect(loadTaskHistory).toHaveBeenCalledWith('task-a', 20, undefined)+ const requests = vi.mocked(loadTaskHistory).mock.calls.length+ view.unmount()+ await rejectPage(response, Object.assign(new Error('Unmounted cursor missing'), { code: 'delivery_cursor_not_found' }))+ expect(loadTaskHistory).toHaveBeenCalledTimes(requests)+ expect(view.container.textContent).toBe('')+ expect(view.props.onOpenSession).not.toHaveBeenCalled()+ })+})++describe('deliveryHistory linked session reads', () => {+ it.each([+ ['available', sessionsFixture(), workspacesFixture()],+ ['loading', sessionsFixture({ phase: 'pending' }), workspacesFixture()],+ ['loading', sessionsFixture(), workspacesFixture({ phase: 'pending' })],+ ['archived', sessionsFixture(), workspacesFixture({ archivedSessionIds: ['session-a' as SessionId] })],+ ['unavailable', sessionsFixture({ ids: [], byId: {} }), workspacesFixture()],+ ['unavailable', sessionsFixture(), workspacesFixture({ state: 'error' })],+ ] as const)('retains inactive session history while its navigation state is %s', async (state, sessions, workspaces) => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([deliveryFixture('record')]))+ const view = await renderHistory({ sessions, workspaces })+ expect(loadTaskHistory).toHaveBeenCalledExactlyOnceWith('task-a', 20, undefined)+ expect(view.getByText('Prompt record').textContent).toBe('Prompt record')+ const button = view.getByRole('button', { name: state === 'unavailable' && sessions.ids.length === 0 ? 'history.open: session-a' : 'history.open: Session A' }) as HTMLButtonElement+ expect(button.title).toBe(`session.${state}`)+ expect(button.disabled).toBe(state !== 'available')+ fireEvent.click(button)+ expect(vi.mocked(view.props.onOpenSession).mock.calls).toEqual(state === 'available' ? [['session-a']] : [])+ })++ it('updates link availability without refetching or discarding the saved history', async () => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([deliveryFixture('record')]))+ const view = await renderHistory({ sessions: sessionsFixture({ phase: 'pending', ids: [], byId: {} }) })+ expect((view.getByRole('button', { name: 'history.open: session-a' }) as HTMLButtonElement).disabled).toBe(true)+ view.rerender(<DeliveryHistory {...view.props} sessions={sessionsFixture()} />)+ const available = view.getByRole('button', { name: 'history.open: Session A' }) as HTMLButtonElement+ expect(available.disabled).toBe(false)+ fireEvent.click(available)+ view.rerender(<DeliveryHistory {...view.props} sessions={sessionsFixture()} workspaces={workspacesFixture({ archivedSessionIds: ['session-a' as SessionId] })} />)+ expect((view.getByRole('button', { name: 'history.open: Session A' }) as HTMLButtonElement).disabled).toBe(true)+ expect(view.getByText('Prompt record').textContent).toBe('Prompt record')+ expect(loadTaskHistory).toHaveBeenCalledTimes(1)+ expect(view.props.onOpenSession).toHaveBeenCalledExactlyOnceWith('session-a')+ })++ it('does not invent a navigation control for legacy history without a linked session', async () => {+ vi.mocked(loadTaskHistory).mockResolvedValueOnce(pageFixture([runFixture('legacy', { sessionId: undefined, finishedAt: undefined, error: undefined, prompt: undefined })]))+ const view = await renderHistory()+ expect(view.getAllByRole('listitem')).toHaveLength(1)+ expect(view.queryByRole('button', { name: /^history.open:/ })).toBeNull()+ expect(view.queryByText(/^history.finished:/)).toBeNull()+ expect(view.queryByText('Run failed')).toBeNull()+ expect(view.queryByText('Prompt legacy')).toBeNull()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/delivery-history.tsx b/packages/dsh-tauri-scheduler/src/client/components/delivery-history.tsxnew file mode 100644index 00000000..6ec755c2--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/delivery-history.tsx@@ -0,0 +1,163 @@+import type { SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { HistoryPage } from '../types'+import { Button, ChevronDown, ChevronUp, Clock, Icon, Text } from 'dsh-tauri-ui/client'+import { cn, useMount, useResizeObserver, useUnmount, useWatchImmediate } from 'dsh-tauri/client'+import { useId, useRef, useState } from 'react'+import { loadTaskHistory } from '../service/scheduler'+import { sessionLabel, sessionLinkState } from './session-link'++interface DeliveryHistoryProps {+ taskId: string+ refreshKey?: string+ timeZone?: string+ t: Translate+ sessions: SessionListState+ workspaces: WorkspaceSnapshot+ onOpenSession: (id: string) => void+}++function SavedPrompt({ prompt, t }: { prompt: string, t: Translate }): ReactElement {+ const ref = useRef<HTMLParagraphElement>(null)+ const id = useId()+ const [expanded, setExpanded] = useState(false)+ const [clamped, setClamped] = useState(false)+ function measure(): void {+ if (!expanded && ref.current)+ setClamped(ref.current.scrollHeight > ref.current.clientHeight)+ }+ useResizeObserver(ref, measure)+ useWatchImmediate([prompt, expanded], measure)+ return (+ <>+ <p ref={ref} id={id} className={cn('mt-[6px] mb-0 text-tertiary text-[13px] leading-[22px] whitespace-pre-wrap wrap-anywhere', !expanded && 'line-clamp-2')}>{prompt}</p>+ {clamped+ ? (+ <Button variant="link" className="mt-[2px] ml-[-6px] px-[6px] py-px gap-[2px] rounded-sm text-secondary text-[12px] leading-[20px] hover:bg-hover hover:no-underline" aria-expanded={expanded} aria-controls={id} onClick={() => setExpanded(value => !value)}>+ {t(expanded ? 'history.collapse' : 'history.expand')}+ <Icon as={expanded ? ChevronUp : ChevronDown} size={14} />+ </Button>+ )+ : null}+ </>+ )+}++export function DeliveryHistory({ taskId, refreshKey, timeZone, t, sessions, workspaces, onOpenSession }: DeliveryHistoryProps): ReactElement {+ const [page, setPage] = useState<HistoryPage>()+ const [loading, setLoading] = useState(false)+ const [error, setError] = useState('')+ const requestRef = useRef({ epoch: 0, pending: false, alive: true })+ useMount(() => {+ requestRef.current.alive = true+ })+ useUnmount(() => {+ requestRef.current.alive = false+ requestRef.current.epoch+++ })++ async function load(before?: string): Promise<void> {+ if (requestRef.current.pending || !requestRef.current.alive)+ return+ requestRef.current.pending = true+ const epoch = requestRef.current.epoch+ setLoading(true)+ setError('')+ try {+ const next = await loadTaskHistory(taskId, 20, before)+ if (!requestRef.current.alive || epoch !== requestRef.current.epoch)+ return+ setPage((previous) => {+ if (!before || !previous)+ return next+ const seen = new Set(previous.records.map(record => record.id))+ return { ...next, records: [...previous.records, ...next.records.filter(record => !seen.has(record.id))] }+ })+ }+ catch (failure) {+ if (!requestRef.current.alive || epoch !== requestRef.current.epoch)+ return+ setError(failure instanceof Error ? failure.message : String(failure))+ if (failure && typeof failure === 'object' && 'code' in failure && failure.code === 'delivery_cursor_not_found') {+ requestRef.current.pending = false+ refresh()+ }+ }+ finally {+ if (requestRef.current.alive && epoch === requestRef.current.epoch) {+ requestRef.current.pending = false+ setLoading(false)+ }+ }+ }++ function refresh(): void {+ requestRef.current.epoch+++ requestRef.current.pending = false+ setPage(undefined)+ void load()+ }+ useWatchImmediate([taskId, refreshKey], refresh)++ function format(at: string): string {+ try {+ const year = new Intl.DateTimeFormat('en-US', { year: 'numeric', timeZone })+ const date = new Date(at)+ return new Intl.DateTimeFormat(t('picker.locale'), { ...(year.format(date) === year.format(Date.now()) ? {} : { year: 'numeric' }), month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit', timeZone }).format(date)+ }+ catch {+ return at+ }+ }++ return (+ <section className="flex flex-1 flex-col min-w-0 min-h-0" aria-label={t('history.title')} aria-busy={loading}>+ <div className="flex-1 min-h-0 overflow-auto px-[var(--detail-gutter)] pt-[24px] pb-[28px] [scrollbar-gutter:stable] [--dsh-scrollbar-width:9px] [--dsh-scrollbar-thumb-border:2px]">+ {error+ ? (+ <div className="flex flex-col items-start gap-[8px] mb-[16px]">+ <Text tone="error" role="alert">{error}</Text>+ <Button size="sm" variant="outline" onClick={refresh}>{t('refresh')}</Button>+ </div>+ )+ : null}+ {page?.records.length === 0+ ? (+ <div className="flex flex-col items-center justify-center gap-[16px] min-h-[240px]" role="status">+ <Icon as={Clock} size={24} className="text-tertiary" />+ <Text tone="tertiary" size="sm">{t('history.empty')}</Text>+ </div>+ )+ : null}+ <ul className="m-0 p-0 list-none">+ {page?.records.map((record) => {+ const state = record.sessionId ? sessionLinkState(record.sessionId, sessions, workspaces) : 'unavailable'+ return (+ <li key={record.id} className="relative flex items-start gap-[12px] mx-[-8px] px-[8px] py-[14px] rounded-[8px] text-[14px] leading-[22px] first:pt-0 before:absolute before:left-[15.75px] before:top-0 before:h-[14px] before:w-[0.5px] before:bg-[var(--dsw-alias-border-l3)] before:content-[''] first:before:hidden after:absolute after:left-[15.75px] after:top-[42px] after:bottom-0 after:w-[0.5px] after:bg-[var(--dsw-alias-border-l3)] after:content-[''] first:after:top-[28px] last:after:hidden">+ <Icon as={Clock} size={16} className="shrink-0 mt-[6px] text-tertiary" />+ <div className="flex-1 min-w-0 py-[2px]">+ {record.sessionId+ ? <button type="button" className="block p-0 border-none bg-transparent text-primary [font-family:inherit] text-[14px] leading-[22px] font-medium text-left cursor-pointer hover:not-disabled:underline focus-visible:shadow-focus-ring disabled:cursor-default" disabled={state !== 'available'} title={t(`session.${state}`)} aria-label={`${t('history.open')}: ${sessionLabel(record.sessionId, sessions).text}`} onClick={() => record.sessionId && onOpenSession(record.sessionId)}><time dateTime={record.delivery === 'this-session' ? record.scheduledAt : record.scheduledFor}>{format(record.delivery === 'this-session' ? record.scheduledAt : record.scheduledFor)}</time></button>+ : <time dateTime={record.delivery === 'this-session' ? record.scheduledAt : record.scheduledFor} className="block text-primary text-[14px] leading-[22px] font-medium">{format(record.delivery === 'this-session' ? record.scheduledAt : record.scheduledFor)}</time>}+ {record.prompt ? <SavedPrompt prompt={record.prompt} t={t} /> : null}+ {record.delivery === 'new-session' && record.error ? <Text size="sm" tone="error" role="status">{record.error}</Text> : null}+ </div>+ </li>+ )+ })}+ </ul>+ {loading ? <Text size="sm" tone="secondary">{t('loading')}</Text> : null}+ {page?.nextBefore ? <Button variant="outline" disabled={loading} onClick={() => void load(page.nextBefore)}>{t('history.more')}</Button> : null}+ </div>+ {page?.earlierRecordsUnavailable || page?.earlierRecordsPruned+ ? (+ <footer className="shrink-0 px-[var(--detail-gutter)] pb-[16px] text-tertiary text-[12px] leading-[20px]">+ {page.earlierRecordsUnavailable ? <Text size="sm" tone="tertiary">{t('history.unavailable')}</Text> : null}+ {page.earlierRecordsPruned ? <Text size="sm" tone="tertiary">{t('history.pruned', page.retention)}</Text> : null}+ </footer>+ )+ : null}+ </section>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/model-picker.tsx b/packages/dsh-tauri-scheduler/src/client/components/model-picker.tsxindex ce82040f..cb05c4d6 100644--- a/packages/dsh-tauri-scheduler/src/client/components/model-picker.tsx+++ b/packages/dsh-tauri-scheduler/src/client/components/model-picker.tsx@@ -3,8 +3,8 @@ import type { ReactElement } from 'react'import type { Translate } from '../locales/index.types'import type { ModelCatalogFailure, ModelOption } from '../types'import { ChevronDown, Chip, Icon, Menu } from 'dsh-tauri-ui/client'-import { groupBy } from 'dsh-tauri/client'-import { useEffect, useState } from 'react'+import { groupBy, useEventListener, useWatchImmediate } from 'dsh-tauri/client'+import { useState } from 'react'type Pane = 'root' | 'model' | 'effort'@@ -33,6 +33,7 @@ export function ModelPicker({modelKey,reasoningEffort,onSelection,+ disabled,}: {readonly t: Translatereadonly models: readonly ModelOption[]@@ -40,9 +41,14 @@ export function ModelPicker({readonly modelKey: stringreadonly reasoningEffort: stringreadonly onSelection: (modelKey: string, reasoningEffort: string) => void+ readonly disabled?: boolean}) {const [open, setOpen] = useState(false)const [pane, setPane] = useState<Pane>('root')+ useWatchImmediate(disabled, () => {+ if (disabled)+ setOpen(false)+ })const selected = models.find(item => `${item.provider}::${item.model}` === modelKey)const reasoning = selected?.reasoningconst effectiveEffort = reasoningEffort === 'none'@@ -53,34 +59,25 @@ export function ModelPicker({: effectiveEffort === undefined? t('effort.providerDefault'): reasoning.efforts.find(item => item.id === effectiveEffort)?.name ?? effectiveEffort- const trigger = selected?.label ?? t('trigger.fallback')+ const trigger = selected?.label ?? (modelKey !== 'default' ? modelKey : t('trigger.fallback'))const modelGroups = Object.entries(groupBy(models, 'provider')).map(([provider, group]) => ({provider,label: group[0]?.providerLabel ?? provider,models: group,}))- // Escape 必须拦在 capture 阶段,否则会同时触达外层 Modal 并连带关掉对话框- useEffect(() => {- if (!open)+ useEventListener('keydown', (event) => {+ if (!open || event.key !== 'Escape')+ return+ event.preventDefault()+ event.stopPropagation()+ event.stopImmediatePropagation()+ if (pane !== 'root') {+ setPane('root')return- const onKey = (event: KeyboardEvent): void => {- if (event.key !== 'Escape')- return- event.preventDefault()- event.stopPropagation()- event.stopImmediatePropagation()- if (pane !== 'root') {- setPane('root')- return- }- setOpen(false)- }- window.addEventListener('keydown', onKey, true)- return () => {- window.removeEventListener('keydown', onKey, true)}- }, [open, pane])+ setOpen(false)+ }, true)const selectModel = (value: string): void => {const item = models.find(model => `${model.provider}::${model.model}` === value)@@ -96,22 +93,22 @@ export function ModelPicker({}const rootItems: MenuEntry[] = [- { id: 'pane:model', label: paneRow(t('menu.model'), selected?.label ?? t('trigger.fallback')) },+ { id: 'pane:model', label: paneRow(t('menu.model'), trigger) },]if (reasoning !== undefined)rootItems.push({ id: 'pane:effort', label: paneRow(t('menu.effort'), effortLabel ?? t('effort.providerDefault')) })- const modelItems: MenuEntry[] = failures.map(failure => ({+ const modelItems: MenuEntry[] = [{ id: 'model:default', label: optionCopy(t('followGlobal')) }, ...failures.map<MenuEntry>(failure => ({type: 'label',id: `warning:${failure.provider}`,text: t('warning.groupLoad', { name: failure.providerLabel, message: failure.message }),- }))+ }))]for (const group of modelGroups) {modelItems.push({ type: 'label', id: `group:${group.provider}`, text: group.label })for (const item of group.models)modelItems.push({ id: `model:${item.provider}::${item.model}`, label: optionCopy(item.label, item.description) })}- if (modelItems.length === 0)+ if (modelItems.length === 1)modelItems.push({ type: 'label', id: 'empty:models', text: t('empty.models') })const effortItems: MenuEntry[] = []@@ -132,6 +129,8 @@ export function ModelPicker({: undefinedconst onSelect = (id: string): void => {+ if (disabled)+ returnif (id === 'pane:model') {setPane('model')return@@ -150,7 +149,7 @@ export function ModelPicker({return (<Menu- open={open}+ open={open && !disabled}autoFocusportalside="top"@@ -164,8 +163,9 @@ export function ModelPicker({}}anchor={(<Chip+ disabled={disabled}variant="composerTrigger"- open={open}+ open={open && !disabled}aria-label={selected === undefined? t('trigger.selectAria'): effortLabel === undefineddiff --git a/packages/dsh-tauri-scheduler/src/client/components/prefill-bridge.tsx b/packages/dsh-tauri-scheduler/src/client/components/prefill-bridge.tsxindex 12bb5228..30876674 100644--- a/packages/dsh-tauri-scheduler/src/client/components/prefill-bridge.tsx+++ b/packages/dsh-tauri-scheduler/src/client/components/prefill-bridge.tsx@@ -1,5 +1,4 @@-import { useStore } from 'dsh-tauri/client'-import { useEffect } from 'react'+import { useStore, useWatchImmediate } from 'dsh-tauri/client'import { store } from '../store'import { applyPrefillToComposer } from './prefill-bridge.utils'@@ -10,7 +9,7 @@ interface PrefillBridgeProps {export function PrefillBridge({ inputActions }: PrefillBridgeProps): null {const { pending } = useStore(store.prefill)- useEffect(() => {+ useWatchImmediate([pending, inputActions], () => {if (pending === '')returnif (inputActions !== undefined) {@@ -20,7 +19,7 @@ export function PrefillBridge({ inputActions }: PrefillBridgeProps): null {}if (applyPrefillToComposer(pending))store.prefill.clear()- }, [pending, inputActions])+ })return null}diff --git a/packages/dsh-tauri-scheduler/src/client/components/recommendations.tsx b/packages/dsh-tauri-scheduler/src/client/components/recommendations.tsxindex 83f12ad7..ab2fd00f 100644--- a/packages/dsh-tauri-scheduler/src/client/components/recommendations.tsx+++ b/packages/dsh-tauri-scheduler/src/client/components/recommendations.tsx@@ -2,7 +2,8 @@ import type { IconComponent } from 'dsh-tauri-ui/client'import type { ReactElement } from 'react'import type { LocaleKey, Translate } from '../locales/index.types'import type { ScheduleForm, TaskFormState, TaskView } from '../types'-import { Calendar, Icon, styles as sharedStyles } from 'dsh-tauri-ui/client'+import { Calendar, Icon, styles as sharedStyles, Text } from 'dsh-tauri-ui/client'+import { useRef, useState } from 'react'import { createTask } from '../service/scheduler'import { recommendationMatchesTask } from './recommendations.utils'import { describeSchedule } from './schedule.utils'@@ -27,7 +28,7 @@ export const RECOMMENDATIONS: Recommendation[] = [schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00' },accent: sharedStyles.business,icon: Calendar,- form: t => ({ name: t('recReviewName'), schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00' }, prompt: t('recReviewPrompt'), workspaceId: '', permission: 'read-only', provider: '', model: '', reasoningEffort: '' }),+ form: t => ({ delivery: 'new-session', sessionId: '', enabled: false, name: t('recReviewName'), schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00' }, prompt: t('recReviewPrompt'), workspaceId: '', permission: 'read-only', provider: '', model: '', reasoningEffort: '' }),},{id: 'weekday-briefing',@@ -36,27 +37,45 @@ export const RECOMMENDATIONS: Recommendation[] = [schedule: { kind: 'workdays', time: '08:00' },accent: sharedStyles.success,icon: Calendar,- form: t => ({ name: t('recWeekdayBriefingName'), schedule: { kind: 'workdays', time: '08:00' }, prompt: t('recWeekdayBriefingPrompt'), workspaceId: '', permission: 'read-only', provider: '', model: '', reasoningEffort: '' }),+ form: t => ({ delivery: 'new-session', sessionId: '', enabled: false, name: t('recWeekdayBriefingName'), schedule: { kind: 'workdays', time: '08:00' }, prompt: t('recWeekdayBriefingPrompt'), workspaceId: '', permission: 'read-only', provider: '', model: '', reasoningEffort: '' }),},]export interface RecommendationsProps {t: Translatetasks: readonly TaskView[]+ onSelect?: (form: TaskFormState) => void}-/** 推荐(预置)定时任务列表:点击直接创建,成功后该项从任务列表中消失。 */-export function Recommendations({ t, tasks }: RecommendationsProps): ReactElement {+export function Recommendations({ t, tasks, onSelect }: RecommendationsProps): ReactElement {+ const pendingRef = useRef(false)+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState('')async function add(rec: Recommendation): Promise<void> {- const form = rec.form(t)- await createTask({+ if (pendingRef.current)+ return+ const form = { ...rec.form(t), recommendationId: rec.id }+ if (onSelect) {+ onSelect(form)+ return+ }+ pendingRef.current = true+ setSaving(true)+ setError('')+ const result = await createTask({+ delivery: 'new-session',name: form.name,schedule: form.schedule,prompt: form.prompt,workspaceId: form.workspaceId || undefined,+ permission: form.permission,recommendationId: rec.id,enabled: false,})+ pendingRef.current = false+ setSaving(false)+ if (!result.ok)+ setError(result.error ?? t('createFailed'))}const visible = RECOMMENDATIONS.filter(rec => !tasks.some(task => recommendationMatchesTask(rec, task, t)))@@ -64,13 +83,14 @@ export function Recommendations({ t, tasks }: RecommendationsProps): ReactElemenreturn (<section className="flex flex-col gap-[8px] mt-[20px]" aria-label={t('recommended')}><h2 className="m-0 text-[13px] leading-[20px] font-semibold">{t('recommended')}</h2>+ {error ? <Text tone="error" role="alert">{error}</Text> : null}{visible.length === 0? <p className="m-0 text-secondary text-[12px]">{t('recommendedEmpty')}</p>: (<ul className="flex flex-col gap-[8px] m-0 p-0 list-none">{visible.map(rec => (<li key={rec.id}>- <button type="button" className="box-border flex items-start gap-[10px] w-full min-w-0 px-[12px] py-[10px] border-none rounded-[10px] bg-transparent text-inherit [font-family:inherit] text-[13px] leading-[20px] text-left cursor-pointer hover:bg-hover" onClick={() => void add(rec)}>+ <button type="button" disabled={saving} className="box-border flex items-start gap-[10px] w-full min-w-0 px-[12px] py-[10px] border-none rounded-[10px] bg-transparent text-inherit [font-family:inherit] text-[13px] leading-[20px] text-left cursor-pointer hover:bg-hover" onClick={() => void add(rec)}><span className="flex-none inline-flex mt-[2px] text-[16px]" style={{ color: rec.accent }}><Icon as={rec.icon} /></span>diff --git a/packages/dsh-tauri-scheduler/src/client/components/recommendations.utils.test.ts b/packages/dsh-tauri-scheduler/src/client/components/recommendations.utils.test.tsindex 8ad73d30..5289f6d4 100644--- a/packages/dsh-tauri-scheduler/src/client/components/recommendations.utils.test.ts+++ b/packages/dsh-tauri-scheduler/src/client/components/recommendations.utils.test.ts@@ -18,6 +18,8 @@ function task(overrides: Partial<TaskView>): TaskView {name: '任务',schedule: { kind: 'workdays', time: '08:00', timeZone: 'Asia/Shanghai' },prompt: '任务指令',+ delivery: 'new-session',+ status: 'active',enabled: false,createdAt: '',updatedAt: '',diff --git a/packages/dsh-tauri-scheduler/src/client/components/runs-tab.tsx b/packages/dsh-tauri-scheduler/src/client/components/runs-tab.tsxdeleted file mode 100644index ed02a663..00000000--- a/packages/dsh-tauri-scheduler/src/client/components/runs-tab.tsx+++ /dev/null@@ -1,77 +0,0 @@-import type { ReactElement } from 'react'-import type { LocaleKey, Translate } from '../locales/index.types'-import type { RunView } from '../types'-import { Action, Alarm, Card, CircleCheck, CircleDashed, CircleStop, CircleXmark, Dot, Icon, Text, TrashBin } from 'dsh-tauri-ui/client'-import { formatLocalTime, isRunUnread } from './schedule.utils'--export interface RunsTabProps {- t: Translate- runs: readonly RunView[]- readAt: number- readIds: readonly string[]- emptyLabel: string- onOpen: (run: RunView) => void- onDelete: (id: string) => void-}--const STATUS_KEYS: Record<RunView['status'], LocaleKey> = {- succeeded: 'succeeded',- failed: 'failed',- interrupted: 'interrupted',- skipped: 'skipped',- cancelled: 'cancelled',- queued: 'queued',- running: 'running',-}--const STATUS_ICONS = {- succeeded: CircleCheck,- failed: CircleXmark,- interrupted: CircleXmark,- cancelled: CircleStop,- skipped: CircleDashed,- queued: CircleDashed,- running: Alarm,-}--export function RunsTab({ t, runs, readAt, readIds, emptyLabel, onOpen, onDelete }: RunsTabProps): ReactElement {- if (runs.length === 0)- return <Text size="sm" tone="tertiary" className="py-[48px] text-center">{emptyLabel}</Text>- return (- <Card.List className="gap-[8px]">- {runs.map(run => (- <Card variant="link" key={run.id} className="box-border mx-0 flex justify-between items-center gap-[10px] w-full min-w-0 h-[60px] px-[12px] py-[10px] rounded-[10px] text-inherit [font-family:inherit] text-[13px] leading-[20px] text-left cursor-pointer overflow-hidden" onClick={() => onOpen(run)}>- <div style={{ height: 36 }}>- <span- className="flex-none inline-flex items-center justify-center mt-[2px] w-[16px] h-[16px] text-[16px] text-business data-[status=succeeded]:text-success data-[status=failed]:text-error data-[status=interrupted]:text-error data-[status=running]:text-secondary data-[status=queued]:text-secondary data-[status=cancelled]:text-tertiary data-[status=skipped]:text-tertiary"- data-status={run.status}- role="img"- aria-label={t(STATUS_KEYS[run.status])}- title={t(STATUS_KEYS[run.status])}- >- <Icon as={STATUS_ICONS[run.status]} />- </span>- </div>- <div style={{ flex: 1, minWidth: 0 }}>- <Card.Title className="flex items-center gap-[8px] text-[13px] leading-[18px]" title={run.taskName}>- {run.taskName}- {isRunUnread(run, readAt, readIds) ? <Dot state="done" /> : null}- </Card.Title>- <div className="flex items-center gap-[10px] min-w-0">- <Card.Description className="flex-1 min-w-0 text-[12px] line-clamp-none truncate">{formatLocalTime(run.startedAt) ?? ''}</Card.Description>- </div>- </div>- <Action- variant="action"- icon={<Icon as={TrashBin} size={12} />}- aria-label={t('deleteRun')}- onClick={(event) => {- event.stopPropagation()- onDelete(run.id)- }}- />- </Card>- ))}- </Card.List>- )-}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-ambient.test.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-ambient.test.tsxnew file mode 100644index 00000000..e61dc4b4--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-ambient.test.tsx@@ -0,0 +1,335 @@+// @vitest-environment jsdom+import type { SessionListState } from 'dsh-tauri/client'+import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { Alarm, Clock, Icon } from 'dsh-tauri-ui/client'+import { defineStore, useStore } from 'dsh-tauri/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { requestTaskDeletion } from '../service/deletion'+import { deleteTask, loadScheduler } from '../service/scheduler'+import { store } from '../store'+import { ambientTask, ambientTranslate, ambientTurn } from './ambient-test.harness'+import { ScheduleCatalogAction } from './schedule-catalog-action'+import { ScheduleDeletionOverlay } from './schedule-deletion-overlay'+import { ScheduleTurnCard } from './schedule-turn-card'+import { SessionScheduleHover } from './session-schedule-hover'+import { SessionScheduleMark } from './session-schedule-mark'++vi.mock('dsh-tauri/client', async () => (await import('./ambient-test.harness')).ambientClientFacade())+vi.mock('dsh-tauri-ui/client', async () => (await import('./ambient-test.harness')).ambientUiFacade())+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => ({ Button: (await import('./ambient-test.ui')).PrimitiveButton }))+vi.mock('../service/scheduler', () => ({ loadScheduler: vi.fn(), deleteTask: vi.fn() }))++beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-10-10T09:00:00Z'))+ vi.mocked(loadScheduler).mockReset().mockResolvedValue(undefined)+ vi.mocked(deleteTask).mockReset().mockResolvedValue({ ok: true })+ store.scheduler.$patch({ tasks: [], runs: [], loading: false, error: '', loadToken: 0, successfulReadToken: 0, refreshedAt: 0 })+ store.deletion.$patch({ pendingTask: null, deletingTaskId: null, feedback: null, feedbackSeq: 0 })+ store.navigation.$patch({ target: null, seq: 0, error: '' })+})++afterEach(() => {+ cleanup()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++async function click(element: HTMLElement): Promise<void> {+ await act(async () => {+ fireEvent.click(element)+ })+}++async function patchCatalog(patch: Parameters<typeof store.scheduler.$patch>[0]): Promise<void> {+ await act(async () => {+ store.scheduler.$patch(patch)+ })+}++describe('ambient shared catalog surfaces', () => {+ it('hides empty and excluded owners without fetching per row or header', () => {+ store.scheduler.$patch({ tasks: [+ ambientTask('disabled', { enabled: false }),+ ambientTask('inactive', { status: 'inactive' }),+ ambientTask('independent', { delivery: 'new-session' }),+ ambientTask('other', { sessionId: 'other' }),+ ] })+ const view = render(+ <>+ <ScheduleCatalogAction sessionId="owner" openTaskDetail={vi.fn()} t={ambientTranslate} />+ <SessionScheduleMark sessionId="owner" t={ambientTranslate} />+ <SessionScheduleHover sessionId="owner" t={ambientTranslate} />+ </>,+ )+ expect(view.container.childElementCount).toBe(0)+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('opens one owner-bound task directly without a menu or per-seat request', async () => {+ store.scheduler.$patch({ tasks: [ambientTask('one'), ambientTask('ignored', { delivery: 'new-session' })] })+ const openTaskDetail = vi.fn()+ const view = render(<ScheduleCatalogAction sessionId="owner" openTaskDetail={openTaskDetail} t={ambientTranslate} />)+ const trigger = view.getByRole('button', { name: 'ambient.trigger.one:1' })+ expect(trigger.getAttribute('aria-haspopup')).toBeNull()+ await click(trigger)+ expect(openTaskDetail).toHaveBeenCalledExactlyOnceWith('one')+ expect(view.queryByRole('menu')).toBeNull()+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('orders the multiple-task menu by deadline, renders overdue metadata, and closes on the public onClose contract', async () => {+ store.scheduler.$patch({ tasks: [+ ambientTask('later', { nextRunAt: '2026-10-10T10:00:00Z' }),+ ambientTask('overdue', { nextRunAt: '2026-10-10T08:59:00Z' }),+ ] })+ const view = render(<ScheduleCatalogAction sessionId="owner" openTaskDetail={vi.fn()} t={ambientTranslate} />)+ const trigger = view.getByRole('button', { name: 'ambient.trigger.other:2' })+ trigger.focus()+ await click(trigger)+ const menu = within(document.body).getByRole('menu')+ expect(trigger.getAttribute('aria-expanded')).toBe('true')+ expect(trigger.querySelector('svg')!.getAttribute('width')).toBe('16')+ expect(trigger.querySelector('span[aria-hidden="true"]')).toBeNull()+ expect(within(menu).getAllByRole('menuitem').map(item => item.getAttribute('aria-label'))).toEqual([+ 'ambient.open:Task overdue',+ 'delete Task overdue',+ 'ambient.open:Task later',+ 'delete Task later',+ ])+ expect(within(menu).getByText('ambient.overdue').classList.contains('text-error')).toBe(true)+ expect(menu.querySelector('time')!.getAttribute('datetime')).toBe('2026-10-10T08:59:00Z')+ await act(async () => {+ fireEvent.keyDown(menu, { key: 'Escape' })+ })+ expect(within(document.body).queryByRole('menu')).toBeNull()+ expect(trigger.getAttribute('aria-expanded')).toBe('false')+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('updates an opened catalog deadline without refetching and stops its clock when closed', async () => {+ store.scheduler.$patch({ tasks: [ambientTask('soon', { nextRunAt: '2026-10-10T09:00:02Z' }), ambientTask('later', { nextRunAt: '2026-10-10T10:00:00Z' })] })+ const view = render(<ScheduleCatalogAction sessionId="owner" openTaskDetail={vi.fn()} t={ambientTranslate} />)+ await click(view.getByRole('button', { name: 'ambient.trigger.other:2' }))+ const menu = within(document.body).getByRole('menu')+ expect(within(menu).queryByText('ambient.overdue')).toBeNull()+ await act(async () => {+ await vi.advanceTimersByTimeAsync(3000)+ })+ expect(within(menu).getByText('ambient.overdue')).not.toBeNull()+ await act(async () => {+ fireEvent.keyDown(menu, { key: 'Escape' })+ })+ expect(vi.getTimerCount()).toBe(0)+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('closes the menu when its seat owner changes and routes menu items through the common detail callback', async () => {+ store.scheduler.$patch({ tasks: [ambientTask('one'), ambientTask('two'), ambientTask('other', { sessionId: 'other' })] })+ const openTaskDetail = vi.fn()+ const view = render(<ScheduleCatalogAction sessionId="owner" openTaskDetail={openTaskDetail} t={ambientTranslate} />)+ await click(view.getByRole('button', { name: 'ambient.trigger.other:2' }))+ await click(within(document.body).getByRole('menuitem', { name: 'ambient.open:Task two' }))+ expect(openTaskDetail).toHaveBeenCalledExactlyOnceWith('two')+ expect(within(document.body).queryByRole('menu')).toBeNull()+ await click(view.getByRole('button', { name: 'ambient.trigger.other:2' }))+ view.rerender(<ScheduleCatalogAction sessionId="other" openTaskDetail={openTaskDetail} t={ambientTranslate} />)+ expect(within(document.body).queryByRole('menu')).toBeNull()+ await click(view.getByRole('button', { name: 'ambient.trigger.one:1' }))+ expect(openTaskDetail).toHaveBeenLastCalledWith('other')+ })++ it('keeps settled row marks during catalog refresh and does not activate a row when its mark is clicked', async () => {+ store.scheduler.$patch({ tasks: [ambientTask('one')], successfulReadToken: 1, loading: true })+ const activate = vi.fn()+ const view = render(<div onClick={activate}><SessionScheduleMark sessionId="owner" t={ambientTranslate} /></div>)+ const count = view.getByText('ambient.mark.aria:1')+ await click(count)+ expect(activate).not.toHaveBeenCalled()+ await patchCatalog({ tasks: [] })+ expect(view.queryByText('ambient.mark.aria:1')).toBeNull()+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('marks scheduled execution sessions with Clock and active reminders with Alarm without losing durable origin or reminder facts', async () => {+ const glyphs = render(+ <>+ <Icon as={Alarm} />+ <Icon as={Clock} />+ </>,+ )+ const [alarm, clock] = Array.from(glyphs.container.querySelectorAll('svg'), icon => icon.innerHTML)+ expect(alarm).not.toBe(clock)+ const sessions = defineStore({ state: () => ({+ ids: ['execution', 'plain'],+ byId: {+ execution: { projectionValues: { 'dsh-tauri-scheduler.origin': true } },+ plain: { projectionValues: { 'dsh-tauri-scheduler.origin': false } },+ },+ }) })+ function useSessions<Selected>(selector: (snapshot: SessionListState) => Selected): Selected {+ return selector(useStore(sessions) as unknown as SessionListState)+ }+ const props = { sessionId: 'execution', t: ambientTranslate, useSessions }+ const activate = vi.fn()+ const view = render(+ <div onClick={activate}>+ <SessionScheduleMark {...props} />+ <SessionScheduleHover sessionId="execution" t={ambientTranslate} />+ </div>,+ )+ expect(view.getByText('ambient.mark.origin.aria').textContent).toBe('ambient.mark.origin.aria')+ expect(view.container.querySelector('[data-session-schedule-mark] svg')!.innerHTML).toBe(clock)+ expect(view.container.querySelectorAll('[data-session-schedule-mark]')).toHaveLength(1)+ expect(view.queryByRole('region')).toBeNull()+ await click(view.getByText('ambient.mark.origin.aria'))+ expect(activate).not.toHaveBeenCalled()++ await patchCatalog({ tasks: [ambientTask('reminder', { sessionId: 'execution', nextRunAt: '2026-10-10T09:05:00Z' })], runs: [], loading: true, error: 'History unavailable' })+ expect(view.container.querySelectorAll('[data-session-schedule-mark]')).toHaveLength(1)+ expect(view.getByText('ambient.mark.aria:1').textContent).toBe('ambient.mark.aria:1')+ expect(view.container.querySelector('[data-session-schedule-mark] svg')!.innerHTML).toBe(alarm)+ expect(view.container.querySelector('[data-session-schedule-mark] svg')!.getAttribute('width')).toBe('16')+ expect(within(view.getByRole('region', { name: 'ambient.list.aria' })).getByText('Task reminder').textContent).toBe('Task reminder')+ await patchCatalog({ tasks: [ambientTask('reminder', { sessionId: 'execution', enabled: false })], loading: false, error: '' })+ expect(view.container.querySelector('[data-session-schedule-mark] svg')!.innerHTML).toBe(clock)+ expect(view.getByText('ambient.mark.origin.aria').textContent).toBe('ambient.mark.origin.aria')+ expect(view.queryByRole('region')).toBeNull()+ await patchCatalog({ tasks: [] })+ expect(view.container.querySelector('[data-session-schedule-mark] svg')!.innerHTML).toBe(clock)+ expect(view.getByText('ambient.mark.origin.aria').textContent).toBe('ambient.mark.origin.aria')++ view.rerender(<SessionScheduleMark {...props} sessionId="plain" />)+ expect(view.container.childElementCount).toBe(0)+ await act(async () => {+ sessions.$patch({ ids: ['plain'], byId: { execution: { projectionValues: { 'dsh-tauri-scheduler.origin': false } }, plain: { projectionValues: { 'dsh-tauri-scheduler.origin': true } } } })+ })+ expect(view.getByText('ambient.mark.origin.aria').textContent).toBe('ambient.mark.origin.aria')+ expect(loadScheduler).not.toHaveBeenCalled()+ })++ it('limits hover facts to two overdue-first owner tasks and reports the exact omitted count', () => {+ store.scheduler.$patch({ tasks: [+ ambientTask('later', { nextRunAt: '2026-10-10T12:00:00Z' }),+ ambientTask('soon', { nextRunAt: '2026-10-10T09:05:00Z' }),+ ambientTask('past', { nextRunAt: '2026-10-10T08:00:00Z' }),+ ambientTask('ignored', { status: 'inactive' }),+ ] })+ const view = render(<SessionScheduleHover sessionId="owner" t={ambientTranslate} />)+ const section = view.getByRole('region', { name: 'ambient.list.aria' })+ expect(within(section).getAllByText(/^Task /).map(label => label.textContent)).toEqual(['Task past', 'Task soon'])+ expect(within(section).getByText('ambient.overdue').classList.contains('text-error')).toBe(true)+ expect(within(section).getByText('5unitMinutes').textContent).toBe('5unitMinutes')+ expect(Array.from(section.querySelectorAll('time'), time => time.getAttribute('datetime'))).toEqual(['2026-10-10T08:00:00Z', '2026-10-10T09:05:00Z'])+ expect(within(section).queryByText('Task later')).toBeNull()+ expect(within(section).queryByText('Task ignored')).toBeNull()+ expect(within(section).getByText('ambient.hover.more:1').textContent).toBe('ambient.hover.more:1')+ expect(loadScheduler).not.toHaveBeenCalled()+ })+})++describe('ambient created turn cards', () => {+ it('retains the durable creation snapshot until a causally newer successful read identifies deletion', async () => {+ store.scheduler.$patch({ loadToken: 7, successfulReadToken: 7, tasks: [] })+ const openTaskDetail = vi.fn()+ const view = render(<ScheduleTurnCard {...ambientTurn([ambientTask('created')])} openTaskDetail={openTaskDetail} t={ambientTranslate} />)+ expect(loadScheduler).toHaveBeenCalledTimes(1)+ await click(view.getByRole('button', { name: 'ambient.open:Task created' }))+ expect(openTaskDetail).toHaveBeenCalledExactlyOnceWith('created')+ await patchCatalog({ loadToken: 8, error: 'Catalog failed' })+ expect(view.queryByText('ambient.card.deleted')).toBeNull()+ expect(view.getByRole('button', { name: 'ambient.open:Task created' }).textContent).toBe('ambient.card.open')+ await patchCatalog({ successfulReadToken: 8, tasks: [], error: '' })+ expect(view.getByText('ambient.card.deleted').textContent).toBe('ambient.card.deleted')+ expect(view.queryByRole('button')).toBeNull()+ })++ it('uses the current catalog record after success and renews its read barrier for later creations in the same turn', async () => {+ store.scheduler.$patch({ loadToken: 4, successfulReadToken: 4 })+ const first = ambientTask('first')+ const second = ambientTask('second')+ const view = render(<ScheduleTurnCard {...ambientTurn([first])} openTaskDetail={vi.fn()} t={ambientTranslate} />)+ await patchCatalog({ tasks: [ambientTask('first', { name: 'Updated title' })], loadToken: 5, successfulReadToken: 5 })+ expect(view.getByText('Updated title').textContent).toBe('Updated title')+ view.rerender(<ScheduleTurnCard {...ambientTurn([first, second])} openTaskDetail={vi.fn()} t={ambientTranslate} />)+ expect(loadScheduler).toHaveBeenCalledTimes(2)+ expect(view.getByRole('button', { name: 'ambient.open:Task second' }).textContent).toBe('ambient.card.open')+ expect(view.queryByText('ambient.card.deleted')).toBeNull()+ await patchCatalog({ loadToken: 6, successfulReadToken: 6, tasks: [first, second] })+ expect(view.getAllByRole('button').map(button => button.getAttribute('aria-label'))).toEqual(['ambient.open:Task first', 'ambient.open:Task second'])+ })++ it('does not refresh or render before a creation settles at the visible turn cursor', () => {+ const view = render(<ScheduleTurnCard {...ambientTurn([ambientTask('future')], 3)} openTaskDetail={vi.fn()} t={ambientTranslate} />)+ expect(view.container.childElementCount).toBe(0)+ expect(loadScheduler).not.toHaveBeenCalled()+ })+})++describe('global confirmation and deletion banner', () => {+ it('confirms a menu deletion globally and retains success after the originating surface unmounts', async () => {+ store.scheduler.$patch({ tasks: [ambientTask('one'), ambientTask('two')] })+ const overlay = render(<ScheduleDeletionOverlay t={ambientTranslate} />)+ const origin = render(<ScheduleCatalogAction sessionId="owner" openTaskDetail={vi.fn()} t={ambientTranslate} />)+ await click(origin.getByRole('button', { name: 'ambient.trigger.other:2' }))+ await click(within(document.body).getByRole('menuitem', { name: 'delete Task one' }))+ expect(within(document.body).queryByRole('menu')).toBeNull()+ expect(deleteTask).not.toHaveBeenCalled()+ origin.unmount()+ const dialog = within(document.body).getByRole('dialog', { name: 'deleteConfirmTitle' })+ expect(within(dialog).getByText('Task one').textContent).toBe('Task one')+ await click(within(dialog).getByRole('button', { name: 'deleteConfirmAction' }))+ expect(deleteTask).toHaveBeenCalledExactlyOnceWith('one')+ expect(within(document.body).queryByRole('dialog')).toBeNull()+ const banner = within(document.body).getByRole('alert')+ expect(banner.textContent).toBe('deletion.deleted:Task one')+ expect(overlay.container.contains(banner)).toBe(false)+ expect(store.deletion.feedback?.kind).toBe('deleted')+ await click(within(banner).getByRole('button', { name: 'complete-banner' }))+ expect(within(document.body).queryByRole('alert')).toBeNull()+ expect(store.deletion.feedback).toBeNull()+ })++ it('cancels confirmation without deletion and reports a failed request as a body banner', async () => {+ vi.mocked(deleteTask).mockResolvedValueOnce({ ok: false, error: 'Storage denied' })+ render(<ScheduleDeletionOverlay t={ambientTranslate} />)+ await act(async () => {+ requestTaskDeletion(ambientTask('failed'))+ })+ await click(within(document.body).getByRole('button', { name: 'cancel' }))+ expect(deleteTask).not.toHaveBeenCalled()+ expect(within(document.body).queryByRole('dialog')).toBeNull()+ await act(async () => {+ requestTaskDeletion(ambientTask('failed'))+ })+ await click(within(document.body).getByRole('button', { name: 'deleteConfirmAction' }))+ expect(within(document.body).getByRole('alert').textContent).toBe('deletion.failed:Task failed: Storage denied')+ expect(store.deletion.feedback?.kind).toBe('deleteFailed')+ })++ it('disables duplicate actions while deleting and keeps the in-flight confirmation open on Escape', async () => {+ let resolve!: (value: { ok: boolean }) => void+ vi.mocked(deleteTask).mockReturnValueOnce(new Promise((done) => {+ resolve = done+ }))+ render(<ScheduleDeletionOverlay t={ambientTranslate} />)+ await act(async () => {+ requestTaskDeletion(ambientTask('slow'))+ })+ const confirm = within(document.body).getByRole('button', { name: 'deleteConfirmAction' }) as HTMLButtonElement+ await click(confirm)+ expect(confirm.disabled).toBe(true)+ expect((within(document.body).getByRole('button', { name: 'cancel' }) as HTMLButtonElement).disabled).toBe(true)+ expect(within(document.body).getByRole('status').textContent).toBe('deletion.pending:Task slow')+ await click(confirm)+ await act(async () => {+ fireEvent.keyDown(within(document.body).getByRole('dialog', { name: 'deleteConfirmTitle' }), { key: 'Escape' })+ })+ expect(within(document.body).getByRole('dialog', { name: 'deleteConfirmTitle' }).getAttribute('aria-modal')).toBe('true')+ expect(deleteTask).toHaveBeenCalledExactlyOnceWith('slow')+ await act(async () => {+ resolve({ ok: true })+ })+ expect(within(document.body).getByRole('alert').textContent).toBe('deletion.deleted:Task slow')+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-catalog-action.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-catalog-action.tsxnew file mode 100644index 00000000..a7a1c445--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-catalog-action.tsx@@ -0,0 +1,91 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { ScheduleTurnCardInjected } from './schedule-turn-card'+import { Action, Button, Clock, Icon, Menu, TrashBin } from 'dsh-tauri-ui/client'+import { useStore, useTimeoutPoll, useWatchImmediate } from 'dsh-tauri/client'+import { useState } from 'react'+import { requestTaskDeletion } from '../service/deletion'+import { activeSessionTasks, isTaskOverdue, orderSessionTasks } from '../service/session-schedule'+import { store } from '../store'+import { ScheduleTaskTiming } from './schedule-task-timing'++export interface ScheduleCatalogActionInjected extends ScheduleTurnCardInjected {+ readonly sessionId: string+}++export function ScheduleCatalogAction({ sessionId, openTaskDetail, t }: ScheduleCatalogActionInjected & { t: Translate }): ReactElement | null {+ const catalog = useStore(store.scheduler)+ const [open, setOpen] = useState(false)+ const [now, setNow] = useState(() => Date.now())+ const clock = useTimeoutPoll(() => setNow(Date.now()), 1000, { immediate: false })+ useWatchImmediate(open, () => open ? clock.resume() : clock.pause())+ const tasks = orderSessionTasks(activeSessionTasks(catalog.tasks, sessionId), now)+ useWatchImmediate([sessionId, tasks.length], () => setOpen(false))+ if (tasks.length === 0)+ return null+ const multiple = tasks.length > 1+ const label = t(multiple ? 'ambient.trigger.other' : 'ambient.trigger.one', { count: tasks.length })+ return (+ <Menu+ open={multiple && open}+ onClose={() => setOpen(false)}+ align="end"+ portal+ autoFocus+ listClassName="w-[336px] max-w-[calc(100vw-32px)] max-h-[min(420px,calc(100dvh-48px))] p-[3px] rounded-[16px]"+ anchor={(+ <Action+ variant="round"+ className="ml-[4px] rounded-full text-tertiary"+ icon={<Icon as={Clock} size={16} aria-hidden="true" />}+ aria-label={label}+ title={label}+ aria-haspopup={multiple ? 'menu' : undefined}+ aria-expanded={multiple ? open : undefined}+ onClick={() => {+ if (!multiple) {+ openTaskDetail(tasks[0]!.id)+ return+ }+ setNow(Date.now())+ setOpen(value => !value)+ }}+ />+ )}+ >+ <div aria-label={t('ambient.list.aria')}>+ {tasks.map(task => (+ <div key={task.id} data-overdue={isTaskOverdue(task, now) || undefined} className="flex min-w-0 items-start gap-[8px] rounded-[13px] pr-[6px] hover:bg-hover focus-within:bg-hover">+ <Button+ variant="link"+ role="menuitem"+ className="flex-1 min-w-0 min-h-[48px] items-start justify-start text-primary text-left px-[12px] py-[10px] rounded-[13px] no-underline hover:no-underline"+ aria-label={t('ambient.open', { name: task.name })}+ onClick={() => {+ setOpen(false)+ openTaskDetail(task.id)+ }}+ >+ <span className="flex flex-col gap-[2px] min-w-0 flex-1">+ <span className="block whitespace-normal wrap-anywhere text-[13px] leading-[18px]">{task.name}</span>+ <ScheduleTaskTiming task={task} now={now} t={t} variant="menu" />+ </span>+ </Button>+ <Action+ variant="round"+ className="w-[20px] h-[20px] mt-[8px] rounded-full"+ role="menuitem"+ aria-label={`${t('delete')} ${task.name}`}+ title={t('delete')}+ icon={<Icon as={TrashBin} size={14} aria-hidden="true" />}+ onClick={() => {+ setOpen(false)+ requestTaskDeletion(task)+ }}+ />+ </div>+ ))}+ </div>+ </Menu>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-created-card.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-created-card.tsxnew file mode 100644index 00000000..62b41916--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-created-card.tsx@@ -0,0 +1,33 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { TaskView } from '../types'+import { Button, Card, Clock, Icon } from 'dsh-tauri-ui/client'+import { describeSchedule } from './schedule.utils'++export function ScheduleCreatedCard({ task, currentTask, openTaskDetail, t }: {+ readonly task: TaskView+ readonly currentTask: TaskView | null | undefined+ readonly openTaskDetail: (id: string) => void+ readonly t: Translate+}): ReactElement {+ const current = currentTask ?? task+ const deleted = currentTask === null+ return (+ <Card data-tool="scheduler_create" className="mx-0 max-w-[520px]">+ <Card.Header>+ <Card.Icon className="h-[32px] w-[32px] border-none"><Icon as={Clock} size={18} aria-hidden="true" /></Card.Icon>+ <Card.Content>+ <Card.TitleRow><Card.Title>{current.name}</Card.Title></Card.TitleRow>+ <Card.Description>{deleted ? t('ambient.card.deleted') : describeSchedule(current.schedule, t)}</Card.Description>+ </Card.Content>+ {!deleted && (+ <Card.End>+ <Button variant="outline" size="sm" aria-label={t('ambient.open', { name: current.name })} onClick={() => openTaskDetail(task.id)}>+ {t('ambient.card.open')}+ </Button>+ </Card.End>+ )}+ </Card.Header>+ </Card>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-current-cards.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-current-cards.tsxnew file mode 100644index 00000000..0e0b682e--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-current-cards.tsx@@ -0,0 +1,33 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { ScheduleCreatedTask } from '../service/schedule-turn'+import { Card } from 'dsh-tauri-ui/client'+import { useStore, useWatchImmediate } from 'dsh-tauri/client'+import { useState } from 'react'+import { loadScheduler } from '../service/scheduler'+import { store } from '../store'+import { ScheduleCreatedCard } from './schedule-created-card'++export function ScheduleCurrentCards({ created, openTaskDetail, t }: {+ readonly created: readonly ScheduleCreatedTask[]+ readonly openTaskDetail: (id: string) => void+ readonly t: Translate+}): ReactElement {+ const catalog = useStore(store.scheduler)+ const [requestAtMount] = useState(() => store.scheduler.loadToken)+ useWatchImmediate(requestAtMount, () => void loadScheduler())+ const records = catalog.successfulReadToken > requestAtMount ? catalog.tasks : undefined+ return (+ <Card.List className="my-[8px] gap-[8px]">+ {created.map(result => (+ <ScheduleCreatedCard+ key={result.callId}+ task={result.task}+ currentTask={records?.find(task => task.id === result.task.id) ?? (records === undefined ? undefined : null)}+ openTaskDetail={openTaskDetail}+ t={t}+ />+ ))}+ </Card.List>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-deletion-overlay.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-deletion-overlay.tsxnew file mode 100644index 00000000..1eae841e--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-deletion-overlay.tsx@@ -0,0 +1,57 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import { Button, Icon, Modal, Toast, TriangleExclamation } from 'dsh-tauri-ui/client'+import { useStore } from 'dsh-tauri/client'+import { cancelTaskDeletion, confirmTaskDeletion, dismissDeletionFeedback } from '../service/deletion'+import { store } from '../store'++export function ScheduleDeletionOverlay({ t }: { t: Translate }): ReactElement {+ const { pendingTask, deletingTaskId, feedback } = useStore(store.deletion)+ const navigation = useStore(store.navigation)+ const deleting = deletingTaskId !== null+ const close = () => cancelTaskDeletion()+ return (+ <>+ <Modal+ open={pendingTask !== null}+ onClose={close}+ title={t('deleteConfirmTitle')}+ description={t('deleteConfirmBody')}+ closeLabel={t('close')}+ footer={(+ <>+ <Button disabled={deleting} onClick={close}>{t('cancel')}</Button>+ <Button variant="danger" disabled={deleting} onClick={() => void confirmTaskDeletion()}>+ {t('deleteConfirmAction')}+ </Button>+ </>+ )}+ >+ <p className="m-0 break-words text-secondary">{pendingTask?.name}</p>+ {deleting && <p role="status" className="text-tertiary">{t('deletion.pending', { name: pendingTask?.name ?? '' })}</p>}+ </Modal>+ {navigation.error && (+ <Toast+ key={`schedule-navigation-${navigation.seq}`}+ icon={<Icon as={TriangleExclamation} size={16} aria-hidden="true" />}+ text={navigation.error}+ onDone={() => {+ if (store.navigation.seq === navigation.seq)+ store.navigation.dismiss()+ }}+ />+ )}+ {feedback !== null && (+ <Toast+ key={`schedule-delete-${feedback.seq}`}+ tone={feedback.kind === 'deleted' ? 'success' : undefined}+ icon={feedback.kind === 'deleteFailed' ? <Icon as={TriangleExclamation} size={16} aria-hidden="true" /> : undefined}+ text={feedback.kind === 'deleted'+ ? t('deletion.deleted', { name: feedback.name })+ : `${t('deletion.failed', { name: feedback.name })}${feedback.error ? `: ${feedback.error}` : ''}`}+ onDone={() => dismissDeletionFeedback(feedback.seq)}+ />+ )}+ </>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-task-timing.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-task-timing.tsxnew file mode 100644index 00000000..aa032199--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-task-timing.tsx@@ -0,0 +1,28 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { TaskView } from '../types'+import { isTaskOverdue } from '../service/session-schedule'+import { describeSchedule, formatLocalTime, formatRelative } from './schedule.utils'++export function ScheduleTaskTiming({ task, now, t, variant = 'menu' }: { task: TaskView, now: number, t: Translate, variant?: 'menu' | 'hover' }): ReactElement {+ const overdue = isTaskOverdue(task, now)+ const absolute = formatLocalTime(task.nextRunAt)+ return (+ <span className={variant === 'hover' ? 'flex flex-col gap-[2px] text-[12px] leading-[16px]' : 'flex flex-col gap-[2px] text-[10px] leading-[15px]'}>+ <span className={variant === 'hover' ? 'text-[#CFD3D6]' : 'text-tertiary'}>{describeSchedule(task.schedule, t)}</span>+ <span className={variant === 'hover' ? 'text-[#ADB2B8]' : 'text-tertiary'}>+ {absolute === undefined+ ? t('waiting')+ : (+ <>+ <time dateTime={task.nextRunAt}>{absolute}</time>+ {' '}+ <span className={overdue ? 'text-error' : undefined}>+ {overdue ? t('ambient.overdue') : formatRelative(task.nextRunAt, now, t)}+ </span>+ </>+ )}+ </span>+ </span>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule-turn-card.tsx b/packages/dsh-tauri-scheduler/src/client/components/schedule-turn-card.tsxnew file mode 100644index 00000000..5a72b3e4--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule-turn-card.tsx@@ -0,0 +1,17 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { ScheduleTurnOwner } from '../service/schedule-turn'+import { selectScheduleTasks } from '../service/schedule-turn'+import { ScheduleCurrentCards } from './schedule-current-cards'++export interface ScheduleTurnCardInjected {+ readonly openTaskDetail: (id: string) => void+}++export function ScheduleTurnCard(props: ScheduleTurnOwner & ScheduleTurnCardInjected & { t: Translate }): ReactElement | null {+ const matched = selectScheduleTasks(props)+ if (matched === null)+ return null+ const latest = matched.created[matched.created.length - 1]!+ return <ScheduleCurrentCards key={`${props.turn.turn}:${latest.callId}:${latest.seq}`} created={matched.created} openTaskDetail={props.openTaskDetail} t={props.t} />+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.harness.ts b/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.harness.tsnew file mode 100644index 00000000..1020b372--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.harness.ts@@ -0,0 +1,125 @@+import type { SessionId, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { Translate } from '../locales/index.types'+import type { HistoryPage, HistoryRecord, SchedulerOptions, TaskFormState, TaskView } from '../types'++export function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason: unknown) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, resolve, reject }+}++export const translate: Translate = (key, params) => key === 'picker.locale'+ ? 'en-US'+ : key === 'history.pruned'+ ? `${key}:days=${params?.days};records=${params?.records}`+ : key++export function optionsFixture(overrides: Partial<SchedulerOptions> = {}): SchedulerOptions {+ return {+ workspaces: [{ id: 'workspace-a', title: 'Workspace A', path: '/isolated/workspace-a' }],+ permissions: [{ value: 'workspace-write', name: 'Write' }, { value: 'read-only', name: 'Read' }],+ defaultPermission: 'workspace-write',+ models: [],+ failures: [],+ defaultModel: { provider: 'provider-a', providerLabel: 'Provider A', model: 'model-a', label: 'Model A', reasoning: { efforts: [{ id: 'high', name: 'High' }], defaultEffort: 'high' } },+ ...overrides,+ }+}++export function taskFixture(overrides: Partial<TaskView> = {}): TaskView {+ return {+ id: 'task-a',+ name: 'Task A',+ prompt: 'Original instruction',+ delivery: 'new-session',+ status: 'active',+ enabled: true,+ schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' },+ recommendationId: 'recommendation-a',+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ createdAt: '2030-01-01T00:00:00.000Z',+ updatedAt: '2030-01-02T00:00:00.000Z',+ ...overrides,+ }+}++export function formFixture(overrides: Partial<TaskFormState> = {}): TaskFormState {+ return {+ name: 'Draft task',+ prompt: 'Draft instruction',+ delivery: 'new-session',+ sessionId: 'session-a',+ enabled: true,+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ recommendationId: 'recommendation-a',+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ ...overrides,+ }+}++export function sessionsFixture(overrides: Partial<SessionListState> = {}): SessionListState {+ const id = 'session-a' as SessionId+ return {+ ids: [id],+ phase: 'ready',+ projectionsBySession: {},+ byId: { [id]: { id, title: 'Session A', displayTitle: 'Session A', running: false, blank: false, updatedAt: 0, retainedBy: {} } },+ ...overrides,+ }+}++export function workspacesFixture(overrides: Partial<WorkspaceSnapshot> = {}): WorkspaceSnapshot {+ return { items: [], archivedSessionIds: [], pinnedSessionIds: [], phase: 'ready', state: 'idle', error: null, ...overrides }+}++export function deliveryFixture(id: string, overrides: Partial<Extract<HistoryRecord, { delivery: 'this-session' }>> = {}): Extract<HistoryRecord, { delivery: 'this-session' }> {+ return {+ id,+ taskId: 'task-a',+ taskName: 'Task A',+ delivery: 'this-session',+ occurrence: `occurrence-${id}`,+ trigger: 'schedule',+ sessionId: 'session-a',+ scheduledAt: '2030-01-02T01:00:00.000Z',+ deliveredAt: '2030-01-02T01:00:02.000Z',+ messageId: `message-${id}`,+ prompt: `Prompt ${id}`,+ ...overrides,+ }+}++export function runFixture(id: string, overrides: Partial<Extract<HistoryRecord, { delivery: 'new-session' }>> = {}): Extract<HistoryRecord, { delivery: 'new-session' }> {+ return {+ id,+ taskId: 'task-a',+ taskName: 'Task A',+ delivery: 'new-session',+ occurrence: `occurrence-${id}`,+ trigger: 'manual',+ status: 'failed',+ sessionId: 'session-a',+ scheduledFor: '2030-01-02T02:00:00.000Z',+ startedAt: '2030-01-02T02:00:03.000Z',+ finishedAt: '2030-01-02T02:00:07.000Z',+ error: 'Run failed',+ prompt: `Prompt ${id}`,+ ...overrides,+ }+}++export function pageFixture(records: HistoryRecord[] = [], overrides: Partial<HistoryPage> = {}): HistoryPage {+ return { records, earlierRecordsUnavailable: false, earlierRecordsPruned: false, retention: { days: 30, records: 500 }, ...overrides }+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.ui.tsx b/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.ui.tsxnew file mode 100644index 00000000..eed28f5a--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/scheduler-client.test.ui.tsx@@ -0,0 +1,80 @@+import type { MenuEntry } from 'dsh-tauri-ui/client'+import type { ButtonHTMLAttributes, InputHTMLAttributes, ReactElement, ReactNode } from 'react'+import { createPortal } from 'react-dom'++export function PrimitiveButton({ variant: _variant, size: _size, icon, children, ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { variant?: string, size?: string, icon?: ReactNode }): ReactElement {+ return (+ <button type="button" {...props}>+ {icon}+ {children}+ </button>+ )+}++export function PrimitiveInput(props: InputHTMLAttributes<HTMLInputElement>): ReactElement {+ return <input {...props} />+}++export function PrimitiveMenu({ open, anchor, items = [], onSelect, portal, children, onClose }: { open: boolean, anchor: ReactNode, items?: readonly MenuEntry[], onSelect?: (id: string) => void, portal?: boolean, children?: ReactNode, onClose?: () => void }): ReactElement {+ const menu = open+ ? (+ <div+ role="menu"+ onKeyDown={(event) => {+ if (event.key === 'Escape')+ onClose?.()+ }}+ >+ {children}+ {items.map(item => 'type' in item+ ? item.type === 'label' ? <span key={item.id}>{item.text}</span> : <hr key={item.id} />+ : <button type="button" role="menuitem" key={item.id} disabled={item.disabled} onClick={() => onSelect?.(item.id)}>{item.label}</button>)}+ </div>+ )+ : null+ return (+ <>+ {anchor}+ {portal && menu ? createPortal(menu, document.body) : menu}+ </>+ )+}++export async function schedulerClientUi() {+ const [action, button, card, checkbox, chip, icon, icons, segmented, select, tag, text, textarea, theme] = await Promise.all([+ import('../../../../dsh-tauri-ui/src/client/components/action'),+ import('../../../../dsh-tauri-ui/src/client/components/button'),+ import('../../../../dsh-tauri-ui/src/client/components/card'),+ import('../../../../dsh-tauri-ui/src/client/components/checkbox'),+ import('../../../../dsh-tauri-ui/src/client/components/chip'),+ import('../../../../dsh-tauri-ui/src/client/components/icon'),+ import('../../../../dsh-tauri-ui/src/client/components/icons'),+ import('../../../../dsh-tauri-ui/src/client/components/segmented-control'),+ import('../../../../dsh-tauri-ui/src/client/components/select'),+ import('../../../../dsh-tauri-ui/src/client/components/tag'),+ import('../../../../dsh-tauri-ui/src/client/components/text'),+ import('../../../../dsh-tauri-ui/src/client/components/textarea'),+ import('../../../../dsh-tauri-ui/src/client/constants/theme'),+ ])+ return {+ ...icons,+ Action: action.Action,+ Button: button.Button,+ Card: card.Card,+ Panel: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ Checkbox: checkbox.Checkbox,+ Chip: chip.Chip,+ Icon: icon.Icon,+ SegmentedControl: segmented.SegmentedControl,+ Select: select.Select,+ Tag: tag.Tag,+ Text: text.Text,+ Textarea: textarea.Textarea,+ Input: PrimitiveInput,+ Menu: PrimitiveMenu,+ Toast: () => null,+ DatePicker: ({ value, label, onChange }: { value: string, label: string, onChange: (value: string) => void }) => <input type="date" aria-label={label} value={value} onChange={event => onChange(event.target.value)} />,+ TimePicker: ({ value, label, onChange, seconds }: { value: string, label: string, onChange: (value: string) => void, seconds?: boolean }) => <input type="time" step={seconds === false ? 60 : 1} aria-label={label} value={value} onChange={event => onChange(event.target.value)} />,+ styles: theme.styles,+ }+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.test.tsx b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.test.tsxnew file mode 100644index 00000000..40c3b818--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.test.tsx@@ -0,0 +1,113 @@+// @vitest-environment jsdom+import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { loadOptions, loadScheduler, updateTask } from '../service/scheduler'+import { store } from '../store'+import { optionsFixture, sessionsFixture, taskFixture, translate, workspacesFixture } from './scheduler-client.test.harness'+import { SchedulerPanel } from './scheduler-panel'++vi.mock('../service/scheduler', () => ({ createTask: vi.fn(), updateTask: vi.fn(), runTask: vi.fn(), toggleTask: vi.fn(), loadScheduler: vi.fn(), loadOptions: vi.fn(), loadTaskHistory: vi.fn(async () => ({ records: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false, retention: { days: 30, records: 200 } })) }))+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => {+ const ui = await import('./scheduler-client.test.ui')+ return { Button: ui.PrimitiveButton, Input: ui.PrimitiveInput, Menu: ui.PrimitiveMenu }+})+vi.mock('dsh-tauri-ui/client', async () => (await import('./scheduler-client.test.ui')).schedulerClientUi())++const sessions = sessionsFixture()+const workspaces = workspacesFixture()+function source<T>(value: T) {+ return {+ value,+ getSnapshot() {+ return this.value+ },+ subscribe(_listener: () => void) {+ expect(this.value).toBe(value)+ return () => {}+ },+ }+}+const runtime = { sessionsRuntime: { list: source(sessions) }, workspacesRuntime: { list: source(workspaces) }, openHistorySession: vi.fn(async () => ({ ok: true })) }++beforeEach(() => {+ vi.mocked(loadScheduler).mockResolvedValue(undefined)+ vi.mocked(loadOptions).mockResolvedValue(undefined)+ store.scheduler.$patch({ options: optionsFixture() })+ store.scheduler.$patch({ tasks: [], loading: false, error: '' })+ store.navigation.$patch({ target: null, seq: 0, error: '' })+})+afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++it('renders the task catalog without redundant page tabs and keeps both creation actions', () => {+ const onViaChat = vi.fn()+ const view = render(<SchedulerPanel {...runtime} t={translate} onViaChat={onViaChat} />)+ expect(view.queryByRole('tablist')).toBeNull()+ fireEvent.click(view.getByRole('button', { name: 'createManual' }))+ expect(store.navigation.target).toBeNull()+ expect(view.getByRole('complementary', { name: 'createDialogTitle' })).not.toBeNull()+ fireEvent.click(view.getByRole('button', { name: 'viaChat' }))+ expect(onViaChat).toHaveBeenCalledTimes(1)+})++it.each(['new-session', 'this-session'] as const)('opens a %s task inside the catalog without requesting session navigation', async (delivery) => {+ const task = taskFixture({ delivery, sessionId: delivery === 'this-session' ? 'session-a' : undefined })+ store.scheduler.$patch({ tasks: [task] })+ const view = render(<SchedulerPanel {...runtime} t={translate} onViaChat={vi.fn()} />)+ await act(async () => {+ fireEvent.click(view.getByText('Task A'))+ })+ expect(store.navigation.seq).toBe(0)+ expect(store.navigation.target).toBeNull()+ expect(runtime.openHistorySession).not.toHaveBeenCalled()+ const detail = view.getByRole('complementary', { name: 'Task A' })+ expect(view.getByRole('heading', { name: 'scheduler', level: 1 })).not.toBeNull()+ fireEvent.click(within(detail).getByRole('button', { name: 'close' }))+ expect(view.queryByRole('complementary')).toBeNull()+})++it('reseeds the exact expected snapshot after a save so a second edit does not conflict or cancel to old values', async () => {+ const task = taskFixture()+ store.scheduler.$patch({ tasks: [task] })+ const saved = { ...task, name: 'First save', updatedAt: '2030-05-06T08:08:09.000Z' }+ vi.mocked(updateTask).mockResolvedValueOnce({ ok: true, task: saved }).mockResolvedValueOnce({ ok: true, task: { ...saved, name: 'Second save' } })+ const view = render(<SchedulerPanel {...runtime} t={translate} onViaChat={vi.fn()} />)+ await act(async () => {+ fireEvent.click(view.getByText('Task A'))+ })+ const name = () => view.getByRole('textbox', { name: 'taskName' }) as HTMLInputElement+ fireEvent.change(name(), { target: { value: 'First save' } })+ await act(async () => {+ fireEvent.submit(name().closest('form')!)+ })+ expect(name().value).toBe('First save')+ expect(view.queryByRole('button', { name: 'save' })).toBeNull()+ fireEvent.change(name(), { target: { value: 'Second save' } })+ await act(async () => {+ fireEvent.submit(name().closest('form')!)+ })+ expect(vi.mocked(updateTask).mock.calls[1]![2]).toEqual(saved)+ expect(name().value).toBe('Second save')+ fireEvent.change(name(), { target: { value: 'Discard me' } })+ fireEvent.click(view.getByRole('button', { name: 'cancel' }))+ expect(name().value).toBe('Second save')+})++it('puts a small session chip after the reminder title and keeps global task titles unmarked', () => {+ store.scheduler.$patch({ tasks: [taskFixture({ name: 'Global task' }), taskFixture({ id: 'reminder', name: 'Reminder', delivery: 'this-session', sessionId: 'session-a' })] })+ const view = render(<SchedulerPanel {...runtime} t={translate} onViaChat={vi.fn()} />)+ const global = view.getByText('Global task').closest('li')!+ const reminder = view.getByText('Reminder').closest('li')!+ expect(within(global).queryByLabelText('delivery.new-session')).toBeNull()+ const chip = within(reminder).getByText('task.session')+ expect(chip.querySelector('svg')).toBeNull()+ expect(chip.classList.contains('h-[18px]')).toBe(true)+ expect(view.getByText('Reminder').compareDocumentPosition(chip) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0)+ expect(within(global).queryByText('task.session')).toBeNull()+ expect(within(reminder).queryByLabelText('delivery.this-session')).toBeNull()+ fireEvent.change(view.getByRole('searchbox'), { target: { value: 'Reminder' } })+ expect(view.queryByText('Global task')).toBeNull()+ expect(view.getByText('Reminder').textContent).toBe('Reminder')+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsxindex 7b17550d..5a4df7d6 100644--- a/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx+++ b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx@@ -1,186 +1,106 @@+import type { ClientContext } from 'dsh-tauri/client'import type { ReactElement } from 'react'import type { Translate } from '../locales/index.types'-import type { RunView, TaskFormState, TaskView } from '../types'-import { Button, Card, Check, CommentPlus, Icon, Input, Magnifier, Plus, SegmentedControl, Text } from 'dsh-tauri-ui/client'-import { filter, includes, isEmpty, lowerCase, omit, useEventListener, useStore } from 'dsh-tauri/client'-import { useCallback, useEffect, useRef, useState } from 'react'-import { REFRESH_INTERVAL_MS } from '../constants'-import { deleteRun, loadScheduler } from '../service/scheduler'+import type { TaskTabNavigation } from '../types/task-tab'+import { Button, Card, CommentPlus, Icon, Input, Magnifier, Panel, Plus, Text } from 'dsh-tauri-ui/client'+import { filter, includes, isEmpty, lowerCase, useStore } from 'dsh-tauri/client'+import { useMemo, useState, useSyncExternalStore } from 'react'import { store } from '../store'import { Recommendations } from './recommendations'-import { RunsTab } from './runs-tab'-import { countUnreadRuns, describeSchedule, formatRelative } from './schedule.utils'+import { describeSchedule, formatRelative } from './schedule.utils'import { TaskCard } from './task-card'-import { TaskCreateDialog } from './task-create-dialog'+import { TaskDetail } from './task-detail'interface SchedulerPanelProps {t: TranslateonViaChat: () => void- onOpenSession: (sessionId: string) => 'opened' | 'archived' | 'unavailable'+ sessionsRuntime: Pick<ClientContext['sessions'], 'list'>+ workspacesRuntime: Pick<ClientContext['workspaces'], 'list'>+ openHistorySession: (id: string) => Promise<{ ok: boolean, error?: string }>}-type DialogState = { taskId?: string, initial?: TaskFormState } | null--/** 由任务视图构造编辑表单(去掉 timeZone 等宿主字段)。 */-function taskToForm(task: TaskView): TaskFormState {- return {- name: task.name,- schedule: omit(task.schedule, 'timeZone') as TaskFormState['schedule'],- prompt: task.prompt,- workspaceId: task.workspaceId ?? '',- permission: task.permission || 'read-only',- provider: task.provider ?? '',- model: task.model ?? '',- // 编辑旧任务(无显式推理等级)时不预填。- reasoningEffort: task.reasoningEffort || '',- }-}--export function SchedulerPanel({ t, onViaChat, onOpenSession }: SchedulerPanelProps): ReactElement {+export function SchedulerPanel({ t, onViaChat, sessionsRuntime, workspacesRuntime, openHistorySession }: SchedulerPanelProps): ReactElement {const state = useStore(store.scheduler)- const [tab, setTab] = useState<'tasks' | 'runs'>('tasks')+ const navigation = useStore(store.navigation)const [search, setSearch] = useState('')- const [dialog, setDialog] = useState<DialogState>(null)- const [openError, setOpenError] = useState('')- // 相对「下次运行」以刷新时刻为基准,避免每次渲染抖动。- const [now, setNow] = useState(() => Date.now())-- // 首帧载入:面板打开时拉一次全量(含对话框选项)。轮询只做增量刷新。- useEffect(() => {- void loadScheduler(true)- }, [])-- // 拉取由注册层轮询(面板关闭时也要更新未读角标),这里只推进相对时间基准。- useEffect(() => {- const timer = setInterval(() => setNow(Date.now()), REFRESH_INTERVAL_MS)- return () => clearInterval(timer)- }, [])-- // 回到前台 / 重新聚焦时立刻补一次刷新(离开期间轮询可能被浏览器节流)- const refreshOnResume = useCallback((): void => {- if (document.visibilityState === 'visible')- void loadScheduler(false)- }, [])- const documentRef = useRef<Document | null | undefined>(typeof document === 'undefined' ? undefined : document)- const windowRef = useRef<Window | null | undefined>(typeof window === 'undefined' ? undefined : window)- useEventListener(documentRef, 'visibilitychange', refreshOnResume)- useEventListener(windowRef, 'focus', refreshOnResume)-+ const [target, setTarget] = useState<TaskTabNavigation>()+ const sessionsSource = useMemo(() => ({ subscribe: sessionsRuntime.list.subscribe.bind(sessionsRuntime.list), getSnapshot: sessionsRuntime.list.getSnapshot.bind(sessionsRuntime.list) }), [sessionsRuntime.list])+ const workspacesSource = useMemo(() => ({ subscribe: workspacesRuntime.list.subscribe.bind(workspacesRuntime.list), getSnapshot: workspacesRuntime.list.getSnapshot.bind(workspacesRuntime.list) }), [workspacesRuntime.list])+ const sessions = useSyncExternalStore(sessionsSource.subscribe, sessionsSource.getSnapshot)+ const workspaces = useSyncExternalStore(workspacesSource.subscribe, workspacesSource.getSnapshot)const filtered = filter(state.tasks, task =>isEmpty(search) || includes(lowerCase(`${task.name} ${task.prompt}`), lowerCase(search)))- const filteredRuns = filter(state.runs, run =>- isEmpty(search) || includes(lowerCase(run.taskName), lowerCase(search)))- const unread = countUnreadRuns(state.runs, state.readAt, state.readIds)-- function onOpenRun(run: RunView): void {- // 点开即视为看过:归档或不可用也不留下永远消不掉的未读。- store.scheduler.markRunRead(run.id)- if (run.sessionId === undefined) {- setOpenError(t('openRunFailed'))- return- }- const outcome = onOpenSession(run.sessionId)- if (outcome === 'archived') {- setOpenError(t('runSessionArchived'))- return- }- if (outcome === 'unavailable') {- setOpenError(t('openRunFailed'))- return- }- setOpenError('')- }return (- <div className="box-border font-sans text-primary text-[13px] leading-[1.5]">- <header className="flex justify-between items-start gap-[16px] mb-[12px]">- <div className="min-w-0">- <h1 className="m-0 text-[20px] leading-[28px] font-medium">{t('scheduler')}</h1>- <p className="mt-[4px] mx-0 mb-0 text-secondary text-[13px] leading-[20px]">{t('subtitle')}</p>- </div>- <div className="flex justify-end items-center gap-[16px]">- <Button style={{ flexShrink: 0 }} variant="addGhost" icon={<Icon as={CommentPlus} />} onClick={onViaChat}>- {t('viaChat')}- </Button>- <Button style={{ flexShrink: 0 }} variant="add" icon={<Icon as={Plus} size={13} />} onClick={() => setDialog({})}>- {t('createManual')}- </Button>- </div>- </header>+ <section+ className="flex w-full h-full min-w-0 min-h-0 overflow-hidden bg-[var(--dsw-alias-bg-base)]"+ onKeyDown={(event) => {+ if (event.key === 'Escape' && !event.defaultPrevented && !store.deletion.pendingTask) {+ event.preventDefault()+ setTarget(undefined)+ }+ }}+ >+ <div className={target ? 'flex-1 min-w-0 min-h-0 max-[760px]:hidden' : 'flex-1 min-w-0 min-h-0'}>+ <Panel>+ <div className="box-border font-sans text-primary text-[13px] leading-[1.5]">+ <header className="flex justify-between items-start gap-[16px] mb-[12px]">+ <div className="min-w-0">+ <h1 className="m-0 text-[20px] leading-[28px] font-medium">{t('scheduler')}</h1>+ <p className="mt-[4px] mx-0 mb-0 text-secondary text-[13px] leading-[20px]">{t('subtitle')}</p>+ </div>+ <div className="flex justify-end items-center gap-[16px]">+ <Button style={{ flexShrink: 0 }} variant="addGhost" icon={<Icon as={CommentPlus} />} onClick={onViaChat}>+ {t('viaChat')}+ </Button>+ <Button style={{ flexShrink: 0 }} variant="add" icon={<Icon as={Plus} size={13} />} onClick={() => setTarget({ draft: true })}>+ {t('createManual')}+ </Button>+ </div>+ </header>- <div className="flex justify-between items-center mb-[12px]">- <Input- className="flex-[0_1_280px] min-w-0 max-w-[280px] max-[680px]:max-w-[160px]"- type="search"- icon={<Icon as={Magnifier} />}- aria-label={t('searchPlaceholder')}- placeholder={t('searchPlaceholder')}- value={search}- onChange={event => setSearch(event.target.value)}- />- {tab === 'runs' && unread > 0- ? (- <Button variant="ghost" size="sm" icon={<Icon as={Check} />} onClick={() => store.scheduler.markAllRunsRead()}>- {t('markAllRead')}- </Button>- )- : null}- </div>+ <div className="flex justify-between items-center mb-[12px]">+ <Input+ className="flex-[0_1_280px] min-w-0 max-w-[280px] max-[680px]:max-w-[160px]"+ type="search"+ icon={<Icon as={Magnifier} />}+ aria-label={t('searchPlaceholder')}+ placeholder={t('searchPlaceholder')}+ value={search}+ onChange={event => setSearch(event.target.value)}+ />+ </div>- <div className="flex mt-[4px] mb-[14px]">- <SegmentedControl- id="dshp-scheduler-tabs"- label={t('scheduler')}- value={tab}- options={[- { value: 'tasks', label: t('tasksTab') },- { value: 'runs', label: t('runsTab') },- ]}- onChange={next => setTab(next === 'runs' ? 'runs' : 'tasks')}- />+ {state.error ? <Text tone="error" role="alert">{state.error}</Text> : null}+ {navigation.error ? <Text tone="error" role="alert">{navigation.error}</Text> : null}+ {filtered.length === 0+ ? <Text size="sm" tone="tertiary" className="py-[48px] text-center">{search ? t('noMatch') : t('emptyTasks')}</Text>+ : (+ <Card.List className="gap-[8px]">+ {filtered.map(task => (+ <TaskCard+ key={task.id}+ task={task}+ t={t}+ describe={describeSchedule(task.schedule, t)}+ nextRun={task.enabled && task.status === 'active' ? formatRelative(task.nextRunAt, state.refreshedAt, t) : undefined}+ paused={!task.enabled}+ onEdit={task => setTarget({ id: task.id, sessionId: task.sessionId })}+ />+ ))}+ </Card.List>+ )}+ <Recommendations t={t} tasks={state.tasks} onSelect={initial => setTarget({ draft: true, initial })} />+ </div>+ </Panel></div>-- {state.error ? <Text tone="error" role="alert">{state.error}</Text> : null}- {openError ? <Text tone="error" role="alert">{openError}</Text> : null}-- {tab === 'tasks'+ {target? (- <>- {filtered.length === 0- ? <Text size="sm" tone="tertiary" className="py-[48px] text-center">{search ? t('noMatch') : t('emptyTasks')}</Text>- : (- <Card.List className="gap-[8px]">- {filtered.map(task => (- <TaskCard- key={task.id}- task={task}- t={t}- describe={describeSchedule(task.schedule, t)}- nextRun={task.enabled ? formatRelative(task.nextRunAt, now, t) : undefined}- paused={!task.enabled}- onEdit={task => setDialog({ taskId: task.id, initial: taskToForm(task) })}- />- ))}- </Card.List>- )}- <Recommendations t={t} tasks={state.tasks} />- </>+ <div className="flex flex-[0_0_47%] min-w-0 min-h-0 border-l-[0.5px] border-border-l4 max-[760px]:flex-1 max-[760px]:border-l-0">+ <TaskDetail key={target.draft ? `draft/${target.initial?.recommendationId ?? ''}` : target.id} target={target} t={t} sessions={sessions} workspaces={workspaces} onClose={() => setTarget(undefined)} onNavigate={setTarget} openHistorySession={openHistorySession} />+ </div>)- : (- <RunsTab- t={t}- runs={filteredRuns}- readAt={state.readAt}- readIds={state.readIds}- emptyLabel={search ? t('noMatchRuns') : t('emptyRuns')}- onOpen={onOpenRun}- onDelete={id => void deleteRun(id)}- />- )}-- {dialog- ? <TaskCreateDialog t={t} options={state.options} initial={dialog.initial} taskId={dialog.taskId} onClose={() => setDialog(null)} />: null}- </div>+ </section>)}diff --git a/packages/dsh-tauri-scheduler/src/client/components/session-link.ts b/packages/dsh-tauri-scheduler/src/client/components/session-link.tsnew file mode 100644index 00000000..e5c75b9e--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/session-link.ts@@ -0,0 +1,20 @@+import type { SessionId, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'++export type SessionLinkState = 'available' | 'loading' | 'archived' | 'unavailable'++export function sessionLinkState(id: string, sessions: SessionListState, workspaces: WorkspaceSnapshot): SessionLinkState {+ if (workspaces.state === 'error')+ return 'unavailable'+ if (sessions.phase === 'pending' || workspaces.phase === 'pending')+ return 'loading'+ if (workspaces.archivedSessionIds.includes(id as SessionId))+ return 'archived'+ if (!sessions.ids.includes(id as SessionId))+ return 'unavailable'+ return 'available'+}++export function sessionLabel(id: string, sessions: SessionListState): { text: string, titled: boolean } {+ const title = sessions.byId[id as SessionId]?.title+ return title?.trim() ? { text: title, titled: true } : { text: id, titled: false }+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/session-schedule-hover.tsx b/packages/dsh-tauri-scheduler/src/client/components/session-schedule-hover.tsxnew file mode 100644index 00000000..af724c99--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/session-schedule-hover.tsx@@ -0,0 +1,38 @@+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import { Clock, Icon } from 'dsh-tauri-ui/client'+import { useStore, useTimeoutPoll } from 'dsh-tauri/client'+import { useState } from 'react'+import { activeSessionTasks, isTaskOverdue, orderSessionTasks } from '../service/session-schedule'+import { store } from '../store'+import { ScheduleTaskTiming } from './schedule-task-timing'++interface SessionScheduleProps {+ readonly sessionId: string+ readonly t: Translate+}++export function SessionScheduleHover({ sessionId, t }: SessionScheduleProps): ReactElement | null {+ const catalog = useStore(store.scheduler)+ const [now, setNow] = useState(() => Date.now())+ useTimeoutPoll(() => setNow(Date.now()), 1000)+ const tasks = orderSessionTasks(activeSessionTasks(catalog.tasks, sessionId), now)+ if (tasks.length === 0)+ return null+ const shown = tasks.slice(0, 2)+ const omitted = tasks.length - shown.length+ return (+ <section data-session-schedule-tasks="" aria-label={t('ambient.list.aria')} className="flex flex-col gap-[8px]">+ {shown.map(task => (+ <div key={task.id} className="flex min-w-0 gap-[6px]" data-session-schedule-task="" data-overdue={isTaskOverdue(task, now) || undefined}>+ <Icon as={Clock} size={12} aria-hidden="true" className="mt-[2px] shrink-0 text-[#CFD3D6]" />+ <span className="flex flex-col gap-[2px] min-w-0 flex-1">+ <span className="block whitespace-normal wrap-anywhere text-[12px] leading-[16px] text-white">{task.name}</span>+ <ScheduleTaskTiming task={task} now={now} t={t} variant="hover" />+ </span>+ </div>+ ))}+ {omitted > 0 && <span className="text-[12px] leading-[16px] text-[#ADB2B8]">{t('ambient.hover.more', { count: omitted })}</span>}+ </section>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/session-schedule-mark.tsx b/packages/dsh-tauri-scheduler/src/client/components/session-schedule-mark.tsxnew file mode 100644index 00000000..bd3096f9--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/session-schedule-mark.tsx@@ -0,0 +1,28 @@+import type { GlobalStandardProps } from '@deepseek-ai/dsh-client-ui-slots'+import type { SessionId } from 'dsh-tauri/client'+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import { Alarm, Clock, Icon } from 'dsh-tauri-ui/client'+import { useStore } from 'dsh-tauri/client'+import { SESSION_SCHEDULE_ORIGIN_PROJECTION } from '../../shared/constants'+import { activeSessionTasks } from '../service/session-schedule'+import { store } from '../store'++export function SessionScheduleMark({ sessionId, useSessions, t }: { sessionId: string, t: Translate } & Partial<Pick<GlobalStandardProps, 'useSessions'>>): ReactElement | null {+ const catalog = useStore(store.scheduler)+ const tasks = activeSessionTasks(catalog.tasks, sessionId)+ const scheduledOrigin = useSessions?.(sessions => sessions.byId[sessionId as SessionId]?.projectionValues?.[SESSION_SCHEDULE_ORIGIN_PROJECTION] === true) ?? false+ if (tasks.length === 0 && !scheduledOrigin)+ return null+ const label = tasks.length > 0 ? t('ambient.mark.aria', { count: tasks.length }) : t('ambient.mark.origin.aria')+ return (+ <span+ data-session-schedule-mark=""+ className="inline-flex h-[20px] w-[16px] shrink-0 items-center justify-center text-tertiary"+ onClick={event => event.stopPropagation()}+ >+ <Icon as={tasks.length > 0 ? Alarm : Clock} size={16} aria-hidden="true" />+ <span className="sr-only">{label}</span>+ </span>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-card.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-card.tsxindex 175a0f35..d10a3161 100644--- a/packages/dsh-tauri-scheduler/src/client/components/task-card.tsx+++ b/packages/dsh-tauri-scheduler/src/client/components/task-card.tsx@@ -2,10 +2,11 @@ import type { MenuEntry } from 'dsh-tauri-ui/client'import type { ReactElement } from 'react'import type { LocaleKey, Translate } from '../locales/index.types'import type { TaskView } from '../types'-import { Action, Button, Card, CirclePause, CirclePlay, EllipsisVertical, Icon, Menu, Modal, Tag, Text, Toast, TrashBin, TriangleExclamation as Warning } from 'dsh-tauri-ui/client'+import { Action, Card, CirclePause, CirclePlay, EllipsisVertical, Icon, Menu, Tag, Text, Toast, TrashBin, TriangleExclamation as Warning } from 'dsh-tauri-ui/client'import { cn } from 'dsh-tauri/client'import { useRef, useState } from 'react'-import { deleteTask, runTask, toggleTask } from '../service/scheduler'+import { requestTaskDeletion } from '../service/deletion'+import { runTask, toggleTask } from '../service/scheduler'export interface TaskCardProps {task: TaskView@@ -18,15 +19,12 @@ export interface TaskCardProps {export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCardProps): ReactElement {const [menuOpen, setMenuOpen] = useState(false)- const [confirmOpen, setConfirmOpen] = useState(false)const [actionError, setActionError] = useState('')const [toast, setToast] = useState<{ text: string, seq: number } | null>(null)const cardRef = useRef<HTMLLIElement | null>(null)+ const inactive = task.status === 'inactive'- async function runAction(- action: () => Promise<{ ok: boolean, error?: string }>,- errorKey: LocaleKey,- ): Promise<void> {+ async function runAction(action: () => Promise<{ ok: boolean, error?: string }>, errorKey: LocaleKey): Promise<void> {const result = await action()if (!result.ok) {const message = result.error ?? t(errorKey)@@ -38,36 +36,10 @@ export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCarsetToast(null)}- async function onRun(): Promise<void> {- try {- await runAction(() => runTask(task.id), 'runFailed')- }- catch (error) {- const message = error instanceof Error ? error.message : String(error)- console.error(error)- setActionError(message)- setToast({ text: message, seq: Date.now() })- }- }- async function onToggle(): Promise<void> {- await runAction(() => toggleTask(task.id, paused), 'toggleFailed')- }- async function onDelete(): Promise<void> {- setConfirmOpen(false)- const result = await deleteTask(task.id)- if (!result.ok) {- const message = result.error ?? t('deleteFailed')- setActionError(message)- setToast({ text: message, seq: Date.now() })- return- }- setActionError('')- }-const items: MenuEntry[] = [{ id: 'edit', label: t('edit'), icon: <Icon as={CirclePlay} /> },- { id: 'run', label: t('runNow'), icon: <Icon as={CirclePlay} /> },- { id: 'toggle', label: paused ? t('resume') : t('pause'), icon: <Icon as={CirclePause} /> },+ { id: 'run', label: t('runNow'), icon: <Icon as={CirclePlay} />, disabled: inactive },+ { id: 'toggle', label: paused ? t('resume') : t('pause'), icon: <Icon as={CirclePause} />, disabled: inactive },{ type: 'separator', id: 'sep' },{ id: 'delete', label: t('delete'), icon: <Icon as={TrashBin} />, danger: true },]@@ -76,10 +48,8 @@ export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCar<Cardref={cardRef}variant="link"- className={cn('box-border mx-0 flex justify-between items-center gap-[10px] w-full min-w-0 h-[60px] px-[12px] py-[10px] rounded-[10px] text-inherit [font-family:inherit] text-[13px] leading-[20px] text-left cursor-pointer overflow-hidden', paused && 'opacity-60')}+ className={cn('box-border mx-0 flex justify-between items-center gap-[10px] w-full min-w-0 h-[60px] px-[12px] py-[10px] rounded-[10px] text-inherit [font-family:inherit] text-[13px] leading-[20px] text-left cursor-pointer overflow-hidden', (paused || inactive) && 'opacity-60')}onClick={(event) => {- // 仅当点击落在卡片本体(title/meta 文本)时打开编辑;portaled 的菜单列表 /- // Modal 不是 li 的 DOM 后代,contains() 为 false,不触发编辑(避免误开弹窗)。if (event.currentTarget.contains(event.target as Node))onEdit(task)}}@@ -87,37 +57,35 @@ export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCar<div style={{ height: 36 }}><Actionvariant="action"+ disabled={inactive}icon={paused ? <Icon as={CirclePlay} /> : <Icon as={CirclePause} />}aria-label={paused ? t('resume') : t('pause')}onClick={(event) => {event.stopPropagation()- void onToggle()+ void runAction(() => toggleTask(task.id, paused), 'toggleFailed')}}/></div>- <div style={{ flex: 1 }}>- <Card.Title className="flex items-center gap-[8px] text-[13px] leading-[18px]" title={task.name}>- {task.name}- </Card.Title>+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-[6px] min-w-0">+ <Card.Title className="min-w-0 text-[13px] leading-[18px]" title={task.name}>{task.name}</Card.Title>+ {task.delivery === 'this-session' ? <Tag variant="status" className="box-border shrink-0">{t('task.session')}</Tag> : null}+ </div><div className="flex items-center gap-[10px] min-w-0"><Card.Description className="flex-1 min-w-0 text-[12px] line-clamp-none truncate">{describe}{' · '}{nextRun !== undefined? (- <>- <strong>- {t('nextRun')}- {' '}- {nextRun}- </strong>- </>+ <strong>+ {t('nextRun')}+ {' '}+ {nextRun}+ </strong>)- : <strong>{t('paused')}</strong>}+ : <strong>{t(inactive ? 'task.inactive' : 'paused')}</strong>}</Card.Description>- {task.waiting === true- ? <Tag variant="status" tone="info">{t('waiting')}</Tag>- : null}+ {task.waiting === true ? <Tag variant="status" tone="info">{t('waiting')}</Tag> : null}</div></div><Menu@@ -127,12 +95,12 @@ export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCarsetMenuOpen(false)if (id === 'edit')onEdit(task)- else if (id === 'run')- onRun()- else if (id === 'toggle')- onToggle()+ else if (id === 'run' && !inactive)+ void runAction(() => runTask(task.id), 'runFailed')+ else if (id === 'toggle' && !inactive)+ void runAction(() => toggleTask(task.id, paused), 'toggleFailed')else if (id === 'delete')- setConfirmOpen(true)+ requestTaskDeletion(task)}}items={items}portal@@ -152,31 +120,7 @@ export function TaskCard({ task, t, describe, nextRun, paused, onEdit }: TaskCar)}/>{actionError ? <Text tone="error" role="alert">{actionError}</Text> : null}- {toast !== null- ? (- <Toast- key={toast.seq}- text={toast.text}- icon={<Icon as={Warning} />}- anchor={cardRef.current}- onDone={() => setToast(null)}- />- )- : null}-- <Modal- open={confirmOpen}- onClose={() => setConfirmOpen(false)}- title={`${t('deleteConfirmTitle')} ${task.name}?`}- description={t('deleteConfirmBody')}- closeLabel={t('close')}- footer={(- <>- <Button variant="outline" onClick={() => setConfirmOpen(false)}>{t('cancel')}</Button>- <Button variant="danger" onClick={() => void onDelete()}>{t('deleteConfirmAction')}</Button>- </>- )}- />+ {toast !== null ? <Toast key={toast.seq} text={toast.text} icon={<Icon as={Warning} />} anchor={cardRef.current} onDone={() => setToast(null)} /> : null}</Card>)}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-create-dialog.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-create-dialog.tsxdeleted file mode 100644index 8c1ff6be..00000000--- a/packages/dsh-tauri-scheduler/src/client/components/task-create-dialog.tsx+++ /dev/null@@ -1,358 +0,0 @@-import type { SelectOption } from 'dsh-tauri-ui/client'-import type { ReactElement, ReactNode } from 'react'-import type { LocaleKey, Translate } from '../locales/index.types'-import type { ScheduleForm, ScheduleKind, SchedulerOptions, TaskFormState, TaskInput, Weekday } from '../types'-import { Button, Input, Modal, Select, Text, Textarea } from 'dsh-tauri-ui/client'-import { isEmpty, map, omitBy, pick, range } from 'dsh-tauri/client'-import { useRef, useState } from 'react'-import { SCHEDULE_KINDS } from '../../shared/constants'-import { createTask, updateTask } from '../service/scheduler'-import { ModelPicker } from './model-picker'--export interface TaskCreateDialogProps {- t: Translate- options: SchedulerOptions- /** 关闭回调(保存中忽略)。 */- onClose: () => void- /** 编辑模式:传入任务 id 时保存走 updateTask。 */- taskId?: string- /** 初始表单(编辑预填 / 推荐预填);不传则新建空表单。 */- initial?: TaskFormState-}--const WEEKDAYS: Weekday[] = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']-const PERMISSION_LABEL_KEYS: Record<string, LocaleKey> = {- 'read-only': 'permissionReadOnly',- 'workspace-write': 'permissionWrite',- 'danger-full-access': 'permissionFullAccess',-}-const WEEKDAY_KEYS: Record<Weekday, LocaleKey> = {- MO: 'dayMon',- TU: 'dayTue',- WE: 'dayWed',- TH: 'dayThu',- FR: 'dayFri',- SA: 'daySat',- SU: 'daySun',-}-const SCHEDULE_KIND_KEYS: Record<ScheduleKind, LocaleKey> = {- once: 'scheduleOnce',- hourly: 'scheduleHourly',- daily: 'scheduleDaily',- interval: 'scheduleInterval',- workdays: 'scheduleWorkdays',- weekly: 'scheduleWeekly',- monthly: 'scheduleMonthly',- custom: 'scheduleCustom',-}--/** 时间段选项:00:00 ~ 23:45,每 15 分钟一档。 */-const TIME_OPTIONS: SelectOption[] = range(96).map((index) => {- const total = index * 15- const h = String(Math.floor(total / 60)).padStart(2, '0')- const m = String(total % 60).padStart(2, '0')- const time = `${h}:${m}`- return { value: time, label: time }-})--/** 整点分钟选项。 */-const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, minute) => ({- value: String(minute),- label: `: ${String(minute).padStart(2, '0')}`,-}))--/** 表单里「空串即缺省」的可选字段(写入宿主前剔除)。 */-const OPTIONAL_INPUT_FIELDS = ['workspaceId', 'permission', 'provider', 'model', 'reasoningEffort'] as const--/** 间隔时长选项(分钟)。 */-const INTERVAL_OPTIONS = [5, 10, 15, 30, 45, 60, 90, 120, 180, 240, 360, 720, 1440]--/** 各计划模式的默认参数(切换模式时初始化,保证字段齐整)。 */-function defaultScheduleFor(kind: ScheduleForm['kind']): ScheduleForm {- switch (kind) {- case 'once':- return { kind: 'once', at: new Date(Date.now() + 60 * 60 * 1000).toISOString() }- case 'hourly':- return { kind: 'hourly', minute: 0 }- case 'interval':- return { kind: 'interval', everyMinutes: 30 }- case 'monthly':- return { kind: 'monthly', day: 1, time: '09:00' }- case 'custom':- return { kind: 'custom', everyDays: 2, time: '09:00' }- case 'weekly':- return { kind: 'weekly', weekdays: ['MO'], time: '09:00' }- case 'workdays':- return { kind: 'workdays', time: '09:00' }- default:- return { kind: 'daily', time: '09:00' }- }-}--/** 对话框内的字段:字段名 + 控件的紧凑堆叠(多控件字段用 `div`,单控件用 `label` 自动关联)。 */-function TaskField({ label, as = 'div', children }: { label: ReactNode, as?: 'label' | 'div', children?: ReactNode }): ReactElement {- const Tag = as- return (- <Tag className="flex flex-col gap-[2px] min-w-0 text-[13px]">- <span className="inline-flex items-center gap-[10px] text-secondary text-[12px] font-medium leading-[18px]">{label}</span>- {children}- </Tag>- )-}--export function TaskCreateDialog({ t, options, onClose, taskId, initial }: TaskCreateDialogProps): ReactElement {- const [form, setForm] = useState<TaskFormState>(() => initial ?? {- name: '',- schedule: { kind: 'daily', time: '09:00' },- prompt: '',- workspaceId: '',- permission: options.defaultPermission || 'read-only',- provider: options.defaultModel?.provider ?? '',- model: options.defaultModel?.model ?? '',- reasoningEffort: options.defaultModel?.reasoning?.defaultEffort ?? '',- })- const [saving, setSaving] = useState(false)- const [error, setError] = useState('')- // 保存中禁止关闭(Esc / 遮罩 / 关闭按钮):用 ref 供稳定闭包读取最新值。- const savingRef = useRef(false)- savingRef.current = saving-- function closeSafe(): void {- if (savingRef.current)- return- onClose()- }-- function setSchedule(patch: Partial<ScheduleForm>): void {- setForm(state => ({ ...state, schedule: { ...state.schedule, ...patch } as ScheduleForm }))- }-- async function onSave(): Promise<void> {- setSaving(true)- setError('')- const input: TaskInput = {- name: form.name,- schedule: form.schedule,- prompt: form.prompt,- ...omitBy(pick(form, ...OPTIONAL_INPUT_FIELDS), isEmpty),- }- const result = await (taskId ? updateTask(taskId, input) : createTask(input))- setSaving(false)- if (!result.ok) {- setError(result.error ?? t('createFailed'))- return- }- onClose()- }-- const scheduleKind = form.schedule.kind- const currentTime = ('time' in form.schedule) ? form.schedule.time : '09:00'- const currentEveryMinutes = form.schedule.kind === 'interval' ? form.schedule.everyMinutes : 30- const currentWeekday: Weekday = form.schedule.kind === 'weekly' ? (form.schedule.weekdays[0] ?? 'MO') : 'MO'-- const workspaceOptions: SelectOption[] = [- // 空 id 由宿主解释为默认/未分组工作区,必须保留。- { value: '', label: t('workspaceDefault') },- ...options.workspaces.map(ws => ({ value: ws.id, label: ws.title || ws.path })),- ]- // 权限选项:来自宿主 permissionPresets;缺失降级为常见三项(含完全访问)。- const fallbackPermissions: SelectOption[] = [- { value: 'read-only', label: t('permissionReadOnly') },- { value: 'workspace-write', label: t('permissionWrite') },- { value: 'danger-full-access', label: t('permissionFullAccess') },- ]- const permissionOptions: SelectOption[] = isEmpty(options.permissions)- ? fallbackPermissions- : map(options.permissions, option => ({- value: option.value,- label: PERMISSION_LABEL_KEYS[option.value] ? t(PERMISSION_LABEL_KEYS[option.value]) : option.name,- }))- // 编辑旧任务:当前值不在选项里时补一项,避免显示空值。- if (form.permission && !permissionOptions.some(option => option.value === form.permission))- permissionOptions.unshift({ value: form.permission, label: form.permission })-- const modelKey = form.provider && form.model ? `${form.provider}::${form.model}` : 'default'-- return (- <Modal- open- onClose={closeSafe}- title={taskId ? t('editDialogTitle') : t('createDialogTitle')}- description={t('dialogHint')}- closeLabel={t('close')}- className="w-[min(640px,100%)]!"- footer={(- <>- <Button variant="outline" disabled={saving} onClick={closeSafe}>{t('cancel')}</Button>- <Button variant="primary" disabled={saving} onClick={() => void onSave()}>- {t('save')}- </Button>- </>- )}- >- <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>- <TaskField as="label" label={t('taskName')}>- <Input- type="text"- value={form.name}- placeholder={t('taskNamePlaceholder')}- onChange={event => setForm(state => ({ ...state, name: event.target.value }))}- />- </TaskField>-- <TaskField label={t('schedule')}>- <div className="flex flex-wrap gap-[8px] items-center">- <Select- label={t('schedule')}- value={scheduleKind}- options={SCHEDULE_KINDS.map(kind => ({ value: kind, label: t(SCHEDULE_KIND_KEYS[kind]) }))}- onChange={value => setForm(state => ({ ...state, schedule: defaultScheduleFor(value as ScheduleForm['kind']) }))}- />-- {scheduleKind === 'once'- ? (- <Input- className="flex-1 min-w-0"- type="datetime-local"- value={String(form.schedule.at).slice(0, 16)}- onChange={event => setSchedule({ kind: 'once', at: new Date(event.target.value).toISOString() })}- />- )- : scheduleKind === 'hourly'- ? (- <Select- label={t('scheduleHourly')}- value={String(form.schedule.minute)}- options={MINUTE_OPTIONS}- onChange={value => setSchedule({ kind: 'hourly', minute: Number(value) })}- />- )- : scheduleKind === 'monthly'- ? (- <>- <Input- type="number"- min={1}- max={31}- value={form.schedule.kind === 'monthly' ? form.schedule.day : 1}- aria-label={t('scheduleMonthDay')}- onChange={event => setSchedule({ kind: 'monthly', day: Number(event.target.value), time: currentTime })}- />- <Select- label={t('scheduleTime')}- value={currentTime}- options={TIME_OPTIONS}- onChange={value => setSchedule({ kind: 'monthly', day: form.schedule.kind === 'monthly' ? form.schedule.day : 1, time: value })}- />- </>- )- : scheduleKind === 'custom'- ? (- <>- <Input- type="number"- min={1}- max={366}- value={form.schedule.kind === 'custom' ? form.schedule.everyDays : 1}- aria-label={t('scheduleEveryDays')}- onChange={event => setSchedule({ kind: 'custom', everyDays: Number(event.target.value), time: currentTime })}- />- <span>{t('dayShort')}</span>- <Select- label={t('scheduleTime')}- value={currentTime}- options={TIME_OPTIONS}- onChange={value => setSchedule({ kind: 'custom', everyDays: form.schedule.kind === 'custom' ? form.schedule.everyDays : 1, time: value })}- />- </>- )- : scheduleKind === 'interval'- ? (- <Select- label={t('scheduleEveryMinutes')}- value={String(currentEveryMinutes)}- options={INTERVAL_OPTIONS.map(minutes => ({ value: String(minutes), label: `${minutes} ${t('minuteShort')}` }))}- onChange={value => setSchedule({ kind: 'interval', everyMinutes: Number(value), anchor: form.schedule.kind === 'interval' ? form.schedule.anchor : undefined })}- />- )- : scheduleKind === 'weekly'- ? (- <>- <Select- label={t('scheduleWeekdays')}- value={currentWeekday}- options={WEEKDAYS.map(day => ({ value: day, label: t(WEEKDAY_KEYS[day]) }))}- onChange={value => setSchedule({ kind: 'weekly', weekdays: [value as Weekday], time: currentTime })}- />- <Select- label={t('scheduleTime')}- value={currentTime}- options={TIME_OPTIONS}- onChange={value => setSchedule({ ...form.schedule, time: value } as ScheduleForm)}- />- </>- )- : (- <Select- label={t('scheduleTime')}- value={currentTime}- options={TIME_OPTIONS}- onChange={value => setSchedule({ ...form.schedule, time: value } as ScheduleForm)}- />- )}- </div>- </TaskField>-- <TaskField label={t('schedulePrompt')}>- <div className="relative flex flex-col items-end gap-[8px]">- <Textarea- className="min-h-[240px] pb-[46px] border-[0.5px] border-border-l4 [font-family:inherit] text-[14px] leading-[1.55]"- value={form.prompt}- placeholder={t('schedulePromptPlaceholder')}- onChange={event => setForm(state => ({ ...state, prompt: event.target.value }))}- />- <div className="flex gap-[8px] items-center">- <Select- label={t('workspace')}- value={form.workspaceId}- variant="composerTrigger"- options={workspaceOptions}- onChange={id => setForm(state => ({ ...state, workspaceId: id }))}- />- <Select- label={t('permission')}- value={form.permission}- variant="composerTrigger"- options={permissionOptions}- onChange={id => setForm(state => ({ ...state, permission: id }))}- />- <div style={{ flex: 1 }} />- <ModelPicker- t={t}- models={options.models ?? []}- failures={options.failures ?? []}- modelKey={modelKey}- reasoningEffort={form.reasoningEffort === '' ? 'none' : form.reasoningEffort}- onSelection={(nextKey, effort) => {- // 照搬 dsh-automation:modelKey = `${provider}::${model}`;'default' 仅在- // 目录无默认模型时出现(trigger 显示官方 fallback「选择模型」)。- const sep = nextKey.indexOf('::')- const provider = sep >= 0 ? nextKey.slice(0, sep) : ''- const model = sep >= 0 ? nextKey.slice(sep + 2) : ''- setForm(state => ({- ...state,- provider,- model,- // 'none' = 提供商默认 → 落库空串。- reasoningEffort: effort === 'none' ? '' : effort,- }))- }}- />- </div>- </div>- </TaskField>- </div>- {error ? <Text tone="error" role="alert">{error}</Text> : null}- </Modal>- )-}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-detail.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-detail.tsxnew file mode 100644index 00000000..8fa631b8--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-detail.tsx@@ -0,0 +1,162 @@+import type { SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { TaskView } from '../types'+import type { TaskTabNavigation } from '../types/task-tab'+import { Action, Button, ChevronRight, Clock, Ellipsis, Icon, Menu, SegmentedControl, Text, TrashBin, Xmark } from 'dsh-tauri-ui/client'+import { cloneDeep, cn, useMount, useStore, useWatchImmediate } from 'dsh-tauri/client'+import { useId, useState } from 'react'+import { requestTaskDeletion } from '../service/deletion'+import { loadOptions, loadScheduler } from '../service/scheduler'+import { store } from '../store'+import { DeliveryHistory } from './delivery-history'+import { Recommendations } from './recommendations'+import { sessionLabel, sessionLinkState } from './session-link'+import { TaskForm } from './task-form'++interface TaskDetailProps {+ target?: TaskTabNavigation+ withinSession?: string+ t: Translate+ sessions: SessionListState+ workspaces: WorkspaceSnapshot+ onClose: () => void+ onNavigate: (target: TaskTabNavigation) => void+ onMissing?: () => void+ openHistorySession: (id: string) => Promise<{ ok: boolean, error?: string }>+}++export function TaskDetail({ target, withinSession, t, sessions, workspaces, onClose, onNavigate, onMissing, openHistorySession }: TaskDetailProps): ReactElement {+ const state = useStore(store.scheduler)+ const deletion = useStore(store.deletion)+ const id = useId()+ const [view, setView] = useState<'rule' | 'records'>('rule')+ const [menuOpen, setMenuOpen] = useState(false)+ const [baseline] = useState(() => store.scheduler.loadToken)+ const [feedbackBaseline] = useState(() => store.deletion.feedbackSeq)+ const [optionsReady, setOptionsReady] = useState(false)+ const [openError, setOpenError] = useState('')+ const [savedRevision, setSavedRevision] = useState(0)+ const record = target && !target.draft ? state.tasks.find(task => task.id === target.id) : undefined+ const [retained, setRetained] = useState<TaskView | undefined>(() => record ? cloneDeep(record) : undefined)+ const answered = state.successfulReadToken > baseline+ const task = retained ?? record+ const inactive = record?.status === 'inactive' || task?.status === 'inactive'++ useMount(() => {+ void loadScheduler()+ void loadOptions().then(() => setOptionsReady(true)).catch(error => setOpenError(error instanceof Error ? error.message : String(error)))+ })+ useWatchImmediate(record, () => {+ if (!retained && record)+ setRetained(cloneDeep(record))+ })+ useWatchImmediate([answered, record !== undefined], () => {+ if (answered && !record && !target?.draft)+ onMissing?.()+ })+ useWatchImmediate(deletion.feedbackSeq, () => {+ if (task && deletion.feedback?.seq && deletion.feedback.seq > feedbackBaseline && deletion.feedback.kind === 'deleted' && deletion.feedback.taskId === task.id)+ onClose()+ })++ async function openSession(sessionId: string): Promise<void> {+ const result = await openHistorySession(sessionId)+ setOpenError(result.ok ? '' : result.error ?? t('openRunFailed'))+ }++ if (!target || (!target.draft && !task)) {+ return (+ <div className="flex flex-1 h-full min-h-0 flex-col items-center justify-center gap-[16px] p-[24px]">+ <Icon as={Clock} size={24} className="text-tertiary" />+ <Text size="sm" tone={state.error ? 'error' : 'secondary'} role="status">{answered ? t(target ? 'task.missing' : 'task.unbound') : state.error || t('loading')}</Text>+ <Button variant="outline" onClick={() => void loadScheduler()}>{t('refresh')}</Button>+ {!withinSession ? <Button variant="ghost" onClick={onClose}>{t('close')}</Button> : null}+ </div>+ )+ }++ const linkedId = task?.delivery === 'this-session' ? task.sessionId : undefined+ const link = linkedId ? sessionLinkState(linkedId, sessions, workspaces) : undefined+ const showLink = view === 'rule' && linkedId && linkedId !== withinSession+ const feedback = (+ <>+ {state.error ? <Text tone="error" role="alert">{state.error}</Text> : null}+ {openError ? <Text tone="error" role="alert">{openError}</Text> : null}+ {inactive && task?.status !== 'inactive' ? <Text tone="secondary">{t('task.inactive')}</Text> : null}+ {task && answered && !record ? <Text tone="error" role="status">{t('task.missing')}</Text> : null}+ </>+ )+ const recommendations = target.draft ? <Recommendations t={t} tasks={state.tasks} onSelect={initial => onNavigate({ draft: true, sessionId: target.sessionId ?? withinSession, initial })} /> : undefined+ const history = task && view === 'records' ? <DeliveryHistory taskId={task.id} refreshKey={record?.lastRunAt} timeZone={task.schedule.timeZone} t={t} sessions={sessions} workspaces={workspaces} onOpenSession={sessionId => void openSession(sessionId)} /> : undefined+ return (+ <aside aria-label={target.draft ? t('createDialogTitle') : task?.name} className="relative flex flex-1 flex-col h-full min-w-0 min-h-0 bg-[var(--dsw-alias-bg-base)] text-primary [--detail-gutter:24px] max-[1100px]:[--detail-gutter:20px] max-[400px]:[--detail-gutter:16px]">+ <h2 className="sr-only">{target.draft ? t('createDialogTitle') : task?.name}</h2>+ <div className={cn('box-border flex shrink-0 items-center justify-between gap-[20px] px-[var(--detail-gutter)] border-b-[0.5px] border-border-l3', withinSession ? 'h-[37px] min-h-[37px]' : 'h-[44px] min-h-[44px]')}>+ <SegmentedControl id={id} variant="underline" label={t('detail.tabs')} value={view} options={[{ value: 'rule', label: t('detail.rule') }, ...(!target.draft ? [{ value: 'records', label: t('detail.records') }] : [])]} onChange={value => setView(value === 'records' ? 'records' : 'rule')} />+ <div className={cn('flex shrink-0 items-center gap-[8px] max-[400px]:gap-0', withinSession ? 'mr-[calc(6px-var(--detail-gutter))]' : 'mr-[-8px]')}>+ {showLink && link+ ? (+ <Button variant="ghost" size="sm" className="h-[28px] px-[8px] rounded-[14px] text-secondary text-[13px] max-w-[200px] min-w-0" disabled={link !== 'available'} aria-label={`${t('session.link')}: ${sessionLabel(linkedId, sessions).text}`} title={sessionLabel(linkedId, sessions).text} onClick={() => void openSession(linkedId)}>+ <span className="truncate">{t('session.link')}</span>+ <Icon as={ChevronRight} size={14} />+ </Button>+ )+ : null}+ {task+ ? (+ <Menu+ open={menuOpen}+ onClose={() => setMenuOpen(false)}+ align="end"+ portal+ items={[{ id: 'delete', label: t('delete'), icon: <Icon as={TrashBin} />, danger: true, disabled: !record || deletion.deletingTaskId === task.id }]}+ onSelect={() => {+ setMenuOpen(false)+ requestTaskDeletion(task)+ }}+ anchor={<Action variant="round" className="text-tertiary" icon={<Icon as={Ellipsis} size={16} />} aria-label={t('detail.more')} aria-haspopup="menu" aria-expanded={menuOpen} onClick={() => setMenuOpen(value => !value)} />}+ />+ )+ : null}+ {!withinSession ? <Action variant="round" icon={<Icon as={Xmark} size={16} />} aria-label={t('close')} onClick={onClose} /> : null}+ </div>+ </div>+ {optionsReady+ ? (+ <TaskForm+ key={savedRevision}+ t={t}+ task={task}+ currentTask={record}+ initial={target.draft ? target.initial : undefined}+ options={state.options}+ sessions={sessions}+ workspaces={workspaces}+ defaultSessionId={target.sessionId ?? withinSession ?? sessions.ids[0] ?? ''}+ disabled={!!task && (inactive || (answered && !record))}+ id={id}+ view={view}+ feedback={feedback}+ onClose={onClose}+ onSaved={(saved) => {+ setRetained(cloneDeep(saved))+ setSavedRevision(value => value + 1)+ onNavigate({ id: saved.id, sessionId: saved.sessionId })+ }}+ recommendations={recommendations}+ history={history}+ />+ )+ : (+ <div className="flex flex-1 min-h-0 flex-col gap-[8px] p-[24px]">+ {feedback}+ <Text tone="secondary">{t('loading')}</Text>+ {recommendations}+ {history}+ </div>+ )}+ {showLink && link !== 'available' ? <Text role="status" className="shrink-0 px-[var(--detail-gutter)] pb-[6px]">{t(`session.${link!}`)}</Text> : null}+ </aside>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-form.test.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-form.test.tsxnew file mode 100644index 00000000..864734bb--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-form.test.tsx@@ -0,0 +1,432 @@+import type { SessionId } from 'dsh-tauri/client'+// @vitest-environment jsdom+import type { ComponentProps } from 'react'+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { StrictMode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createTask, updateTask } from '../service/scheduler'+import { deferred, formFixture, optionsFixture, sessionsFixture, taskFixture, translate, workspacesFixture } from './scheduler-client.test.harness'+import { TaskForm } from './task-form'++vi.mock('../service/scheduler', () => ({ createTask: vi.fn(), updateTask: vi.fn() }))+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => {+ const ui = await import('./scheduler-client.test.ui')+ return { Button: ui.PrimitiveButton, Input: ui.PrimitiveInput, Menu: ui.PrimitiveMenu }+})+vi.mock('dsh-tauri-ui/client', async () => (await import('./scheduler-client.test.ui')).schedulerClientUi())++beforeEach(() => {+ vi.resetAllMocks()+ vi.mocked(createTask).mockResolvedValue({ ok: true, task: taskFixture() })+ vi.mocked(updateTask).mockResolvedValue({ ok: true, task: taskFixture() })+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+})++function renderForm(overrides: Partial<ComponentProps<typeof TaskForm>> = {}, strict = false) {+ const props: ComponentProps<typeof TaskForm> = {+ t: translate,+ options: optionsFixture(),+ sessions: sessionsFixture(),+ workspaces: workspacesFixture(),+ onClose: vi.fn(),+ onSaved: vi.fn(),+ defaultSessionId: 'session-a',+ initial: formFixture(),+ ...overrides,+ }+ const view = render(strict ? <StrictMode><TaskForm {...props} /></StrictMode> : <TaskForm {...props} />)+ return { ...view, props }+}++async function submit(view: ReturnType<typeof renderForm>): Promise<void> {+ const form = view.container.querySelector('form')+ expect(form).not.toBeNull()+ await act(async () => {+ fireEvent.submit(form!)+ })+}++async function select(label: string, option: string): Promise<void> {+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: label }))+ })+ await act(async () => {+ fireEvent.click(screen.getByRole('menuitem', { name: option }))+ })+}++describe('taskForm official detail layout', () => {+ it('places the editable name and compact instruction before the run-time rows with a separate save footer', () => {+ const view = renderForm()+ const name = view.getByLabelText('taskName')+ const instruction = view.getByPlaceholderText('schedulePromptPlaceholder')+ const runtime = view.getByRole('region', { name: 'detail.runtime' })+ expect(name.classList.contains('text-[20px]')).toBe(true)+ expect(instruction.classList.contains('min-h-[112px]')).toBe(true)+ expect(instruction.classList.contains('max-h-[160px]')).toBe(true)+ expect(instruction.compareDocumentPosition(runtime) & Node.DOCUMENT_POSITION_FOLLOWING).not.toBe(0)+ const footer = view.getByRole('button', { name: 'save' }).closest('footer')!+ expect(footer).not.toBeNull()+ expect(runtime.parentElement?.contains(footer)).toBe(false)+ expect(footer.textContent).toContain('detail.unsaved')+ })++ it('keeps an unsaved rule and its independent resources when changing to records and back', async () => {+ const view = renderForm({ id: 'task-detail', history: <p>Saved history</p> })+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'Unsaved rule' } })+ view.rerender(<TaskForm {...view.props} view="records" history={<p>Saved history</p>} />)+ expect(view.getByRole('tabpanel').textContent).toContain('Saved history')+ expect(view.queryByRole('textbox', { name: 'taskName' })).toBeNull()+ view.rerender(<TaskForm {...view.props} view="rule" />)+ expect((view.getByLabelText('taskName') as HTMLInputElement).value).toBe('Unsaved rule')+ await submit(view)+ expect(vi.mocked(createTask).mock.calls[0]![0]).toMatchObject({ name: 'Unsaved rule', workspaceId: 'workspace-a', permission: 'workspace-write', provider: 'provider-a', model: 'model-a', reasoningEffort: 'high' })+ })+})++describe('taskForm schedule editing', () => {+ it('keeps the exact saved schedule when selecting the already selected repeat kind', async () => {+ const schedule = { kind: 'custom', everyDays: 4, time: '16:45', anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Pacific/Auckland' } as const+ const view = renderForm({ task: taskFixture({ schedule }) })+ await select('schedule', 'scheduleCustom')+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'Only rename' } })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual(schedule)+ })++ it('preserves one-shot milliseconds when editing the date but drops them only when editing the clock', async () => {+ const task = taskFixture({ schedule: { kind: 'once', at: '2030-05-06T07:08:09.125Z', timeZone: 'Asia/Tokyo' } })+ const view = renderForm({ task })+ fireEvent.change(view.getByLabelText('picker.date'), { target: { value: '2030-05-07' } })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual({ kind: 'once', at: '2030-05-07T07:08:09.125Z', timeZone: 'Asia/Tokyo' })+ fireEvent.change(view.getByLabelText('scheduleTime'), { target: { value: '16:09:10' } })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[1]![1].schedule).toEqual({ kind: 'once', at: '2030-05-07T07:09:10.000Z', timeZone: 'Asia/Tokyo' })+ })++ it('does not move a later DST-fold instant when reselecting the current date or zone', async () => {+ const schedule = { kind: 'once', at: '2030-11-03T06:30:00.125Z', timeZone: 'America/New_York' } as const+ const view = renderForm({ task: taskFixture({ schedule }) })+ fireEvent.change(view.getByLabelText('picker.date'), { target: { value: '2030-11-03' } })+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'timeZone' }))+ })+ fireEvent.change(view.getByRole('searchbox', { name: 'picker.zoneSearch' }), { target: { value: 'America/New_York' } })+ await act(async () => {+ fireEvent.click(within(view.getByRole('menu')).getByTitle('America/New_York'))+ })+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'No timing changes' } })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual(schedule)+ })++ it('updates runtime status from a fresh record without replacing an unsaved rule or its expected record', async () => {+ const original = taskFixture()+ const view = renderForm({ task: original })+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'Unsaved' } })+ view.rerender(<TaskForm {...view.props} currentTask={{ ...original, enabled: false }} />)+ expect(view.getByText('paused').textContent).toBe('paused')+ expect((view.getByLabelText('taskName') as HTMLInputElement).value).toBe('Unsaved')+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![2]).toEqual(original)+ })++ it('closes a portal control before a disabled or saving form can accept later selections', async () => {+ const view = renderForm()+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'schedule' }))+ })+ expect(view.getByRole('menu')).not.toBeNull()+ view.rerender(<TaskForm {...view.props} disabled />)+ expect(view.queryByRole('menu')).toBeNull()+ expect((view.getByRole('button', { name: 'timeZone' }) as HTMLButtonElement).disabled).toBe(true)+ expect((view.getByRole('button', { name: 'schedule' }) as HTMLButtonElement).disabled).toBe(true)+ })++ it('preserves a custom schedule anchor when editing its days and wall time', async () => {+ const view = renderForm({ task: taskFixture({ schedule: { kind: 'custom', everyDays: 4, time: '16:45', anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Pacific/Auckland' } }) })+ fireEvent.change(view.getByRole('spinbutton', { name: 'scheduleEveryDays' }), { target: { value: '6' } })+ fireEvent.change(view.getByLabelText('scheduleTime'), { target: { value: '18:19' } })+ await submit(view)+ expect(updateTask).toHaveBeenCalledTimes(1)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual({ kind: 'custom', everyDays: 6, time: '18:19', anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Pacific/Auckland' })+ })++ it('preserves an interval anchor when editing its minutes and timezone', async () => {+ const view = renderForm({ task: taskFixture({ schedule: { kind: 'interval', everyMinutes: 17, anchor: '2030-05-01T05:06:07.000Z', timeZone: 'America/New_York' } }) })+ fireEvent.change(view.getByRole('spinbutton', { name: 'scheduleEveryMinutes' }), { target: { value: '23' } })+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'timeZone' }))+ })+ fireEvent.change(view.getByRole('searchbox', { name: 'picker.zoneSearch' }), { target: { value: 'Europe/Berlin' } })+ await act(async () => {+ fireEvent.click(view.getByTitle('Europe/Berlin'))+ })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual({ kind: 'interval', everyMinutes: 23, anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Europe/Berlin' })+ })++ it('retains all selected weekdays during unrelated edits and changes only the toggled days', async () => {+ const view = renderForm({ task: taskFixture() })+ expect((view.getByRole('checkbox', { name: 'dayMon' }) as HTMLInputElement).checked).toBe(true)+ expect(view.getByRole('checkbox', { name: 'dayMon' }).classList.contains('w-[12px]')).toBe(true)+ expect((view.getByRole('checkbox', { name: 'dayWed' }) as HTMLInputElement).checked).toBe(true)+ expect((view.getByRole('checkbox', { name: 'dayFri' }) as HTMLInputElement).checked).toBe(true)+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'Renamed weekly task' } })+ fireEvent.click(view.getByRole('checkbox', { name: 'dayTue' }))+ fireEvent.click(view.getByRole('checkbox', { name: 'dayWed' }))+ fireEvent.change(view.getByLabelText('scheduleTime'), { target: { value: '11:12' } })+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1]).toMatchObject({ name: 'Renamed weekly task', schedule: { kind: 'weekly', weekdays: ['MO', 'FR', 'TU'], time: '11:12', timeZone: 'Asia/Shanghai' } })+ })++ it.each([+ { kind: 'daily', time: '09:30', timeZone: 'UTC' },+ { kind: 'workdays', time: '09:30', timeZone: 'UTC' },+ { kind: 'weekly', weekdays: ['MO', 'WE'], time: '09:30', timeZone: 'UTC' },+ { kind: 'monthly', day: 7, time: '09:30', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 4, anchor: '2030-05-01T05:06:07.000Z', time: '09:30', timeZone: 'UTC' },+ ] as const)('accepts minute-only wall time with step 60 for $kind schedules', async (schedule) => {+ const view = renderForm({ task: taskFixture({ schedule }) })+ const time = view.getByLabelText('scheduleTime') as HTMLInputElement+ expect(time.type).toBe('time')+ expect(time.step).toBe('60')+ expect(time.value).toBe('09:30')+ fireEvent.change(time, { target: { value: '18:19' } })+ expect(time.checkValidity()).toBe(true)+ await submit(view)+ expect(updateTask).toHaveBeenCalledTimes(1)+ expect(vi.mocked(updateTask).mock.calls[0]![1].schedule).toEqual({ ...schedule, time: '18:19' })+ })++ it('allows a fractional interval of 1.5 minutes to pass native validation and submit', async () => {+ const view = renderForm({ initial: formFixture({ schedule: { kind: 'interval', everyMinutes: 30, timeZone: 'UTC' } }) })+ const interval = view.getByRole('spinbutton', { name: 'scheduleEveryMinutes' }) as HTMLInputElement+ expect(interval.step).toBe('any')+ expect(Number(interval.min)).toBeGreaterThan(0)+ expect(Number(interval.min)).toBeLessThan(1.5)+ fireEvent.change(interval, { target: { value: '1.5' } })+ expect(interval.value).toBe('1.5')+ expect(interval.checkValidity()).toBe(true)+ await submit(view)+ expect(createTask).toHaveBeenCalledTimes(1)+ expect(vi.mocked(createTask).mock.calls[0]![0].schedule).toEqual({ kind: 'interval', everyMinutes: 1.5, timeZone: 'UTC' })+ })++ it('keeps the explicitly chosen timezone when changing schedule kind', async () => {+ const view = renderForm({ initial: formFixture({ schedule: { kind: 'daily', time: '13:00', timeZone: 'Pacific/Auckland' } }) })+ await select('schedule', 'scheduleInterval')+ await submit(view)+ expect(vi.mocked(createTask).mock.calls[0]![0].schedule).toEqual({ kind: 'interval', everyMinutes: 30, timeZone: 'Pacific/Auckland' })+ })+})++describe('taskForm delivery conversion', () => {+ it('hides and omits independent resources for a new this-session reminder', async () => {+ const view = renderForm({ initial: formFixture({ delivery: 'this-session' }) })+ expect(view.queryByRole('button', { name: 'workspace' })).toBeNull()+ expect(view.queryByRole('button', { name: 'permission' })).toBeNull()+ expect(view.queryByRole('button', { name: 'trigger.selectAria' })).toBeNull()+ expect(view.getByText('delivery.inherited').textContent).toBe('delivery.inherited')+ await submit(view)+ expect(createTask).toHaveBeenCalledExactlyOnceWith({+ delivery: 'this-session',+ sessionId: 'session-a',+ name: 'Draft task',+ prompt: 'Draft instruction',+ enabled: true,+ recommendationId: 'recommendation-a',+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ })+ })++ it('clears stale resources when an independent task is converted to this-session', async () => {+ const view = renderForm({ task: taskFixture() })+ await select('delivery', 'delivery.this-session')+ await submit(view)+ expect(updateTask).toHaveBeenCalledTimes(1)+ expect(vi.mocked(updateTask).mock.calls[0]![1]).toEqual({+ delivery: 'this-session',+ sessionId: 'session-a',+ name: 'Task A',+ prompt: 'Original instruction',+ enabled: true,+ recommendationId: 'recommendation-a',+ schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: '',+ permission: '',+ provider: '',+ model: '',+ reasoningEffort: '',+ })+ })++ it('clears an old linked session when a reminder is converted to an independent task', async () => {+ const view = renderForm({ task: taskFixture({ delivery: 'this-session', sessionId: 'session-a' }) })+ await select('delivery', 'delivery.new-session')+ await submit(view)+ expect(vi.mocked(updateTask).mock.calls[0]![1]).toEqual({+ delivery: 'new-session',+ sessionId: '',+ name: 'Task A',+ prompt: 'Original instruction',+ enabled: true,+ recommendationId: 'recommendation-a',+ schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ })++ it.each([+ ['loading', sessionsFixture({ phase: 'pending' }), workspacesFixture()],+ ['loading', sessionsFixture(), workspacesFixture({ phase: 'pending' })],+ ['archived', sessionsFixture(), workspacesFixture({ archivedSessionIds: ['session-a' as SessionId] })],+ ['unavailable', sessionsFixture({ ids: [], byId: {} }), workspacesFixture()],+ ['unavailable', sessionsFixture(), workspacesFixture({ state: 'error' })],+ ] as const)('blocks submission when the linked session is %s', async (state, sessions, workspaces) => {+ const view = renderForm({ initial: formFixture({ delivery: 'this-session' }), sessions, workspaces })+ expect((view.getByRole('button', { name: 'save' }) as HTMLButtonElement).disabled).toBe(true)+ expect(view.getByRole('alert').textContent).toBe(`session.${state}`)+ await submit(view)+ expect(createTask).not.toHaveBeenCalled()+ })++ it('allows submission after an unopened linked session arrives in the list', async () => {+ const view = renderForm({ initial: formFixture({ delivery: 'this-session' }), sessions: sessionsFixture({ phase: 'pending', ids: [], byId: {} }) })+ expect((view.getByRole('button', { name: 'save' }) as HTMLButtonElement).disabled).toBe(true)+ view.rerender(<TaskForm {...view.props} sessions={sessionsFixture()} />)+ expect((view.getByRole('button', { name: 'save' }) as HTMLButtonElement).disabled).toBe(false)+ await submit(view)+ expect(createTask).toHaveBeenCalledTimes(1)+ })+})++describe('taskForm submission lifetime', () => {+ it('accepts a completed save after StrictMode effect replay', async () => {+ const response = deferred<Awaited<ReturnType<typeof createTask>>>()+ vi.mocked(createTask).mockImplementationOnce(() => response.promise)+ const view = renderForm({}, true)+ await submit(view)+ expect(createTask).toHaveBeenCalledTimes(1)+ await act(async () => {+ response.resolve({ ok: true, task: taskFixture() })+ await response.promise+ })+ expect(view.props.onSaved).toHaveBeenCalledExactlyOnceWith(taskFixture())+ expect((view.getByRole('button', { name: 'save' }) as HTMLButtonElement).disabled).toBe(false)+ })++ it('sends the original expected snapshot even after the external task is mutated and rerendered', async () => {+ const original = taskFixture()+ const view = renderForm({ task: original })+ original.prompt = 'External replacement'+ original.updatedAt = '2030-01-03T00:00:00.000Z'+ original.schedule.timeZone = 'UTC'+ if (original.schedule.kind !== 'weekly')+ throw new Error('Expected weekly task fixture')+ original.schedule.time = '20:00'+ original.schedule.weekdays = ['TU']+ view.rerender(<TaskForm {...view.props} task={original} />)+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'My retained draft' } })+ await submit(view)+ expect(updateTask).toHaveBeenCalledTimes(1)+ const [id, input, expected] = vi.mocked(updateTask).mock.calls[0]!+ expect(id).toBe('task-a')+ expect(input).toMatchObject({ name: 'My retained draft', prompt: 'Original instruction', schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' } })+ expect(expected).toEqual(taskFixture())+ expect(expected).not.toBe(original)+ expect(expected.schedule).not.toBe(original.schedule)+ })++ it('retains the complete draft after an asynchronous save failure and permits a retry', async () => {+ const first = deferred<Awaited<ReturnType<typeof createTask>>>()+ vi.mocked(createTask).mockImplementationOnce(() => first.promise)+ const view = renderForm({ initial: formFixture({ schedule: { kind: 'custom', everyDays: 4, time: '16:45', anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Pacific/Auckland' } }) })+ fireEvent.change(view.getByLabelText('taskName'), { target: { value: 'Unsaved task' } })+ fireEvent.change(view.getByPlaceholderText('schedulePromptPlaceholder'), { target: { value: 'Unsaved multiline\ninstruction' } })+ fireEvent.change(view.getByRole('spinbutton', { name: 'scheduleEveryDays' }), { target: { value: '7' } })+ await submit(view)+ await act(async () => {+ first.resolve({ ok: false, error: 'Storage unavailable' })+ await first.promise+ })+ expect(view.getByRole('alert').textContent).toBe('Storage unavailabletask.conflictHint')+ expect((view.getByLabelText('taskName') as HTMLInputElement).value).toBe('Unsaved task')+ expect((view.getByPlaceholderText('schedulePromptPlaceholder') as HTMLTextAreaElement).value).toBe('Unsaved multiline\ninstruction')+ expect((view.getByRole('spinbutton', { name: 'scheduleEveryDays' }) as HTMLInputElement).value).toBe('7')+ expect(view.getByRole('button', { name: 'timeZone' }).title).toBe('Pacific/Auckland')+ expect(view.props.onSaved).not.toHaveBeenCalled()+ await submit(view)+ expect(createTask).toHaveBeenCalledTimes(2)+ expect(vi.mocked(createTask).mock.calls[1]![0]).toEqual({+ delivery: 'new-session',+ sessionId: undefined,+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Unsaved task',+ prompt: 'Unsaved multiline\ninstruction',+ schedule: { kind: 'custom', everyDays: 7, time: '16:45', anchor: '2030-05-01T05:06:07.000Z', timeZone: 'Pacific/Auckland' },+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ expect(view.props.onSaved).toHaveBeenCalledExactlyOnceWith(taskFixture())+ expect(view.queryByRole('alert')).toBeNull()+ })++ it('guards duplicate submit events before React can render the saving state', async () => {+ const response = deferred<Awaited<ReturnType<typeof createTask>>>()+ vi.mocked(createTask).mockImplementationOnce(() => response.promise)+ const view = renderForm()+ const form = view.container.querySelector('form')!+ await act(async () => {+ fireEvent.submit(form)+ fireEvent.submit(form)+ fireEvent.submit(form)+ })+ expect(createTask).toHaveBeenCalledTimes(1)+ expect((view.getByRole('button', { name: 'loading' }) as HTMLButtonElement).disabled).toBe(true)+ expect((view.getByRole('button', { name: 'cancel' }) as HTMLButtonElement).disabled).toBe(true)+ await act(async () => {+ response.resolve({ ok: true, task: taskFixture() })+ await response.promise+ })+ expect(view.props.onSaved).toHaveBeenCalledExactlyOnceWith(taskFixture())+ })++ it.each([false, true])('does not call onSaved after a pending save outlives an unmounted form with StrictMode=%s', async (strict) => {+ const response = deferred<Awaited<ReturnType<typeof createTask>>>()+ vi.mocked(createTask).mockImplementationOnce(() => response.promise)+ const view = renderForm({}, strict)+ await submit(view)+ view.unmount()+ await act(async () => {+ response.resolve({ ok: true, task: taskFixture() })+ await response.promise+ })+ expect(view.props.onSaved).not.toHaveBeenCalled()+ expect(createTask).toHaveBeenCalledTimes(1)+ expect(view.container.textContent).toBe('')+ })++ it('never submits a form disabled by an inactive task owner', async () => {+ const view = renderForm({ task: taskFixture({ status: 'inactive', enabled: false }), disabled: true })+ expect(view.queryByRole('button', { name: 'save' })).toBeNull()+ expect(view.queryByRole('textbox', { name: 'taskName' })).toBeNull()+ expect(view.getByText('task.inactive').textContent).toBe('task.inactive')+ await submit(view)+ expect(updateTask).not.toHaveBeenCalled()+ expect(view.props.onSaved).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-form.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-form.tsxnew file mode 100644index 00000000..1c8d861f--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-form.tsx@@ -0,0 +1,450 @@+import type { SelectOption } from 'dsh-tauri-ui/client'+import type { SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { ReactElement, ReactNode } from 'react'+import type { LocaleKey, Translate } from '../locales/index.types'+import type { ScheduleForm, ScheduleKind, SchedulerOptions, TaskFormState, TaskView, Weekday } from '../types'+import { Button, Checkbox, ChevronDown, DatePicker, Icon, Menu, Select, Text, TimePicker } from 'dsh-tauri-ui/client'+import { cloneDeep, isEmpty, isEqual, map, useMount, useTimeoutPoll, useUnmount, useWatchImmediate } from 'dsh-tauri/client'+import { useId, useMemo, useRef, useState } from 'react'+import { SCHEDULE_KINDS } from '../../shared/constants'+import { createTask, updateTask } from '../service/scheduler'+import { ModelPicker } from './model-picker'+import { formatRelative } from './schedule.utils'+import { sessionLabel, sessionLinkState } from './session-link'+import { absoluteDateTime, defaultScheduleFor, emptyTaskForm, localDateTime, taskFormInput, taskToForm } from './task-form.utils'++interface TaskFormProps {+ t: Translate+ options: SchedulerOptions+ sessions: SessionListState+ workspaces: WorkspaceSnapshot+ onClose: () => void+ onSaved: (task: TaskView) => void+ task?: TaskView+ currentTask?: TaskView+ initial?: TaskFormState+ defaultSessionId: string+ disabled?: boolean+ id?: string+ view?: 'rule' | 'records'+ feedback?: ReactNode+ recommendations?: ReactNode+ history?: ReactNode+}++const WEEKDAYS: Weekday[] = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']+const PERMISSION_KEYS: Record<string, LocaleKey> = {+ 'read-only': 'permissionReadOnly',+ 'workspace-write': 'permissionWrite',+ 'danger-full-access': 'permissionFullAccess',+}+const WEEKDAY_KEYS: Record<Weekday, LocaleKey> = {+ MO: 'dayMon',+ TU: 'dayTue',+ WE: 'dayWed',+ TH: 'dayThu',+ FR: 'dayFri',+ SA: 'daySat',+ SU: 'daySun',+}+const SCHEDULE_KEYS: Record<ScheduleKind, LocaleKey> = {+ once: 'scheduleOnce',+ hourly: 'scheduleHourly',+ daily: 'scheduleDaily',+ interval: 'scheduleInterval',+ workdays: 'scheduleWorkdays',+ weekly: 'scheduleWeekly',+ monthly: 'scheduleMonthly',+ custom: 'scheduleCustom',+}+const MINUTE_OPTIONS: SelectOption[] = Array.from({ length: 60 }, (_, minute) => ({ value: String(minute), label: `: ${String(minute).padStart(2, '0')}` }))+const VALUE_CLASS = 'flex-[0_1_auto] min-w-0 max-w-full min-h-[32px] h-auto gap-[6px] px-[8px] rounded-[18px] bg-transparent text-primary [font-family:inherit] text-[14px] font-normal leading-[1.6] hover:not-disabled:bg-hover focus-visible:shadow-focus-ring'+const INPUT_CLASS = 'flex-[0_1_58%] min-w-0 px-[8px] py-[5px] border-none rounded-[18px] bg-transparent text-primary [font-family:inherit] text-[14px] leading-[1.6] text-right outline-none hover:not-disabled:bg-hover focus-visible:shadow-focus-ring'++function RuleRow({ label, children }: { label: ReactNode, children: ReactNode }): ReactElement {+ return (+ <div className="box-border flex w-full items-center justify-between gap-[12px] min-h-[48px] border-b-[0.5px] border-border-l3 last:border-b-0">+ <span className="shrink-0 text-primary text-[14px] leading-[1.6]">{label}</span>+ {children}+ </div>+ )+}++const RECENT_KEY = 'dsh.schedule.recent-time-zones.v1'++function zoneLabel(zone: string, locale: string, system: string, systemLabel: string, at: number): { label: string, offset: number } {+ try {+ const offset = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'longOffset' }).formatToParts(at).find(part => part.type === 'timeZoneName')?.value ?? 'GMT'+ const match = /^GMT([+-])(\d{2}):(\d{2})$/.exec(offset)+ const minutes = match ? (Number(match[2]) * 60 + Number(match[3])) * (match[1] === '-' ? -1 : 1) : 0+ const name = new Intl.DateTimeFormat(locale, { timeZone: zone, timeZoneName: 'longGeneric' }).formatToParts(at).find(part => part.type === 'timeZoneName')?.value+ const stamp = offset === 'GMT' ? 'UTC+00:00' : offset.replace('GMT', 'UTC')+ return { label: `${name && !name.startsWith('GMT') ? `${stamp} · ${name}` : stamp}${zone === system ? systemLabel : ''}`, offset: minutes }+ }+ catch {+ return { label: zone, offset: Number.POSITIVE_INFINITY }+ }+}++function recentZones(system: string): string[] {+ try {+ const parsed: unknown = JSON.parse(localStorage.getItem(RECENT_KEY) ?? 'null')+ if (Array.isArray(parsed)) {+ const zones = [...new Set(parsed.filter((zone): zone is string => typeof zone === 'string' && !!zone))].slice(0, 5)+ if (zones.length)+ return zones+ }+ }+ catch {}+ return [...new Set([system, 'UTC'])]+}++function TimeZonePicker({ value, onChange, t, disabled }: { value: string, onChange: (value: string) => void, t: Translate, disabled?: boolean }): ReactElement {+ const [open, setOpen] = useState(false)+ const [query, setQuery] = useState('')+ const system = new Intl.DateTimeFormat().resolvedOptions().timeZone+ const [recent, setRecent] = useState(() => recentZones(system))+ const [at, setAt] = useState(() => Date.now())+ const locale = t('picker.locale')+ useWatchImmediate(disabled, () => {+ if (disabled)+ setOpen(false)+ })+ const choices = useMemo(() => {+ if (!open)+ return []+ let inventory: string[] = []+ try {+ inventory = Intl.supportedValuesOf('timeZone')+ }+ catch {}+ const zones = [...new Set([system, 'UTC', value, ...inventory])].map(id => ({ id, ...zoneLabel(id, locale, system, t('picker.system'), at) }))+ zones.sort((a, b) => a.id === system ? -1 : b.id === system ? 1 : a.offset - b.offset || a.id.localeCompare(b.id))+ const grouped = new Map<string, { id: string, label: string, zones: string[] }>()+ for (const zone of zones) {+ const existing = grouped.get(zone.label)+ if (existing) {+ existing.zones.push(zone.id)+ if (zone.id === value)+ existing.id = value+ }+ else {+ grouped.set(zone.label, { id: zone.id, label: zone.label, zones: [zone.id] })+ }+ }+ return [...grouped.values()]+ }, [open, value, system, locale, t, at])+ const normalized = query.trim().toLocaleLowerCase(locale)+ const matches = choices.filter(item => `${item.label} ${item.zones.join(' ')}`.toLocaleLowerCase(locale).includes(normalized)).map((item) => {+ const ids = item.zones.filter(id => id.toLocaleLowerCase(locale).includes(normalized))+ const exact = ids.find(id => id.toLocaleLowerCase(locale) === normalized)+ return { ...item, id: exact ?? (ids.includes(item.id) ? item.id : ids[0]) ?? item.id }+ })+ const recentItems = normalized+ ? []+ : recent.flatMap((id) => {+ const item = choices.find(choice => choice.zones.includes(id))+ return item ? [{ ...item, id }] : []+ }).filter((item, index, items) => items.findIndex(other => other.label === item.label) === index)+ const recentLabels = new Set(recentItems.map(item => item.label))+ const remaining = matches.filter(item => !recentLabels.has(item.label))+ function choose(zone: string): void {+ if (disabled)+ return+ const next = [zone, ...recent.filter(item => item !== zone)].slice(0, 5)+ setRecent(next)+ try {+ localStorage.setItem(RECENT_KEY, JSON.stringify(next))+ }+ catch {}+ setOpen(false)+ setQuery('')+ onChange(zone)+ }+ return (+ <Menu+ open={open && !disabled}+ onClose={() => {+ setOpen(false)+ setQuery('')+ }}+ portal+ align="end"+ listClassName="w-[360px] max-w-[calc(100vw-32px)] max-h-[min(420px,calc(100dvh-48px))] rounded-[16px] p-[3px]"+ anchor={(+ <button+ type="button"+ disabled={disabled}+ aria-label={t('timeZone')}+ title={value}+ aria-haspopup="menu"+ aria-expanded={open}+ className="inline-flex min-w-0 items-center justify-end gap-[6px] min-h-[32px] px-[8px] border-none rounded-[18px] bg-transparent text-primary [font-family:inherit] text-[14px] leading-[1.6] text-right cursor-pointer hover:not-disabled:bg-hover focus-visible:shadow-focus-ring disabled:text-tertiary"+ onClick={() => {+ setAt(Date.now())+ setQuery('')+ setOpen(value => !value)+ }}+ >+ <span className="truncate">{zoneLabel(value, locale, system, t('picker.system'), at).label}</span>+ <Icon as={ChevronDown} size={14} className="shrink-0 text-tertiary" />+ </button>+ )}+ >+ <div className="sticky top-0 z-[1] px-[4px] pb-[4px] bg-[var(--dsw-specific-menu)]">+ <input type="search" aria-label={t('picker.zoneSearch')} placeholder={t('picker.zoneSearch')} value={query} disabled={disabled} onChange={event => setQuery(event.target.value)} className="box-border w-full px-[8px] py-[6px] border-[0.5px] border-border-l2 rounded-[7px] outline-none bg-[var(--dsw-alias-bg-base)] text-primary [font-family:inherit] text-[13px] leading-[20px] focus:border-business" />+ </div>+ {recentItems.map(item => <button key={`recent-${item.id}`} type="button" disabled={disabled} role="menuitem" title={item.id} className="block w-full text-left px-[12px] py-[8px] rounded-[10px] border-none bg-transparent text-primary [font-family:inherit] text-[13px] leading-[20px] cursor-pointer hover:bg-hover focus-visible:bg-hover focus-visible:outline-none" onClick={() => choose(item.id)}>{item.label}</button>)}+ {recentItems.length && remaining.length ? <hr role="separator" className="h-[0.5px] mx-[4px] my-[6px] border-none bg-[var(--dsw-alias-border-l3)]" /> : null}+ {remaining.map(item => <button key={item.id} type="button" disabled={disabled} role="menuitem" title={item.id} className="block w-full text-left px-[12px] py-[8px] rounded-[10px] border-none bg-transparent text-primary [font-family:inherit] text-[13px] leading-[20px] cursor-pointer hover:bg-hover focus-visible:bg-hover focus-visible:outline-none" onClick={() => choose(item.id)}>{item.label}</button>)}+ </Menu>+ )+}++export function TaskForm({ t, options, sessions, workspaces, onClose, onSaved, task, currentTask, initial, defaultSessionId, disabled, id, view = 'rule', feedback, recommendations, history }: TaskFormProps): ReactElement {+ const fallbackId = useId()+ const panelId = id ?? fallbackId+ const [expected] = useState(() => task ? cloneDeep(task) : undefined)+ const [baseline] = useState(() => task ? taskToForm(task) : cloneDeep(initial ?? emptyTaskForm(options, defaultSessionId)))+ const [form, setForm] = useState<TaskFormState>(() => cloneDeep(baseline))+ const [onceWall, setOnceWall] = useState(() => baseline.schedule.kind === 'once' ? localDateTime(baseline.schedule.at, baseline.schedule.timeZone) : '')+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState('')+ const [now, setNow] = useState(() => Date.now())+ const pendingRef = useRef(false)+ const aliveRef = useRef(true)+ const clock = useTimeoutPoll(() => setNow(Date.now()), 1000, { immediate: false })+ useWatchImmediate(view, () => view === 'rule' ? clock.resume() : clock.pause())+ useMount(() => {+ aliveRef.current = true+ })+ useUnmount(() => {+ aliveRef.current = false+ })+ const link = sessionLinkState(form.sessionId, sessions, workspaces)+ const dirty = !task || !isEqual(form, baseline)+ const locked = !!disabled || saving+ const blocked = locked || (form.delivery === 'this-session' && (!form.sessionId || link !== 'available'))+ const zone = form.schedule.timeZone ?? new Intl.DateTimeFormat().resolvedOptions().timeZone++ function setSchedule(patch: Partial<ScheduleForm>): void {+ if (locked)+ return+ setForm(state => ({ ...state, schedule: { ...state.schedule, ...patch } as ScheduleForm }))+ }++ function editOnce(wall: string): void {+ if (locked || wall === onceWall)+ return+ setOnceWall(wall)+ setSchedule({ at: absoluteDateTime(wall, zone) })+ }++ function chooseKind(kind: ScheduleKind): void {+ if (locked || kind === form.schedule.kind)+ return+ const schedule = defaultScheduleFor(kind, zone)+ setOnceWall(schedule.kind === 'once' ? localDateTime(schedule.at, zone) : '')+ setForm(state => ({ ...state, schedule }))+ }++ function cancelDraft(): void {+ if (!task) {+ onClose()+ return+ }+ setForm(cloneDeep(baseline))+ setOnceWall(baseline.schedule.kind === 'once' ? localDateTime(baseline.schedule.at, baseline.schedule.timeZone) : '')+ setError('')+ }++ async function onSave(): Promise<void> {+ if (pendingRef.current || blocked)+ return+ pendingRef.current = true+ setSaving(true)+ setError('')+ const input = taskFormInput(form, !!expected)+ const result = expected ? await updateTask(expected.id, input, expected) : await createTask(input)+ pendingRef.current = false+ if (!aliveRef.current)+ return+ setSaving(false)+ if (!result.ok || !result.task) {+ setError(result.error ?? t('createFailed'))+ return+ }+ onSaved(result.task)+ }++ const workspaceOptions: SelectOption[] = [{ value: '', label: t('workspaceDefault') }, ...options.workspaces.map(ws => ({ value: ws.id, label: ws.title || ws.path }))]+ if (form.workspaceId && !workspaceOptions.some(item => item.value === form.workspaceId))+ workspaceOptions.push({ value: form.workspaceId, label: form.workspaceId })+ const permissionOptions: SelectOption[] = isEmpty(options.permissions)+ ? Object.entries(PERMISSION_KEYS).map(([value, key]) => ({ value, label: t(key) }))+ : map(options.permissions, option => ({ value: option.value, label: PERMISSION_KEYS[option.value] ? t(PERMISSION_KEYS[option.value]) : option.name }))+ if (form.permission && !permissionOptions.some(option => option.value === form.permission))+ permissionOptions.unshift({ value: form.permission, label: form.permission })+ const sessionOptions: SelectOption[] = [{ value: '', label: t('session.select') }, ...sessions.ids.map(value => ({ value, label: sessionLabel(value, sessions).text }))]+ if (form.sessionId && !sessionOptions.some(item => item.value === form.sessionId))+ sessionOptions.push({ value: form.sessionId, label: sessionLabel(form.sessionId, sessions).text })+ const modelKey = form.provider && form.model ? `${form.provider}::${form.model}` : 'default'+ const current = currentTask ?? task+ let nextRun = current?.nextRunAt+ try {+ if (nextRun)+ nextRun = new Intl.DateTimeFormat(t('picker.locale'), { month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23', timeZone: zone }).format(new Date(nextRun))+ }+ catch {+ nextRun = current?.nextRunAt+ }++ return (+ <form+ className="flex flex-1 flex-col min-w-0 min-h-0 [--detail-gutter:24px] max-[1100px]:[--detail-gutter:20px] max-[400px]:[--detail-gutter:16px]"+ onSubmit={(event) => {+ event.preventDefault()+ void onSave()+ }}+ >+ <div hidden={view !== 'rule'} role="tabpanel" id={`${panelId}-rule-panel`} aria-labelledby={id ? `${id}-rule` : undefined} className="flex-1 min-h-0 overflow-auto px-[var(--detail-gutter)] pt-[24px] pb-[28px] [scrollbar-gutter:stable] [--dsh-scrollbar-width:9px] [--dsh-scrollbar-thumb-border:2px] max-[760px]:pt-[20px]">+ {feedback}+ <fieldset disabled={disabled || saving} className="border-none p-0 m-0 min-w-0">+ <header className="flex items-start gap-[10px] mb-[4px]">+ {current?.status === 'inactive'+ ? <h2 className="flex-1 min-w-0 m-0 py-[2px] text-[20px] leading-[28px] font-medium wrap-anywhere">{form.name}</h2>+ : <input className="flex-1 w-full min-w-0 min-h-[32px] p-0 border-none outline-none bg-transparent text-primary [font-family:inherit] text-[20px] leading-[28px] font-medium hover:shadow-[0_1px_var(--dsw-alias-border-l3)] focus:shadow-[0_1px_var(--dsw-alias-state-business-primary)]" type="text" aria-label={t('taskName')} required maxLength={120} value={form.name} placeholder={t('taskNamePlaceholder')} onChange={event => setForm(state => ({ ...state, name: event.target.value }))} />}+ </header>+ <div className="min-h-[20px] mb-[20px] text-tertiary text-[13px] leading-[20px] wrap-anywhere">+ {task+ ? current?.status === 'inactive'+ ? t('task.inactive')+ : !current?.enabled+ ? t('paused')+ : nextRun+ ? (+ <>+ {t('nextRun')}+ {' '}+ <time dateTime={current?.nextRunAt}>{nextRun}</time>+ {' '}+ (+ {formatRelative(current?.nextRunAt, now, t)}+ )+ </>+ )+ : null+ : null}+ </div>+ {current?.status === 'inactive'+ ? <p className="m-0 text-[14px] leading-[24px] whitespace-pre-wrap wrap-anywhere">{form.prompt}</p>+ : <textarea className="box-border block w-full max-w-full min-h-[112px] max-h-[160px] [field-sizing:content] m-0 p-[12px] border-[0.5px] border-border-l3 rounded-[16px] outline-none bg-[var(--dsw-alias-bg-base)] text-primary [font-family:inherit] text-[14px] leading-[24px] resize-none transition-colors hover:border-border-l2 focus:border-business [--dsh-scrollbar-width:9px] [--dsh-scrollbar-thumb-border:2px] [--dsh-scrollbar-track-margin:12px]" aria-label={t('schedulePrompt')} required maxLength={64000} value={form.prompt} placeholder={t('schedulePromptPlaceholder')} onChange={event => setForm(state => ({ ...state, prompt: event.target.value }))} />}+ <section className="mt-[28px]" aria-label={t('detail.runtime')}>+ <h3 className="mt-0 mr-0 mb-[8px] ml-[10px] text-tertiary text-[13px] leading-[20px] font-normal">{t('detail.runtime')}</h3>+ <div className="flex flex-col px-[12px] border-[0.5px] border-border-l3 rounded-[16px]">+ <RuleRow label={t('detail.repeat')}>+ <Select disabled={locked} label={t('schedule')} variant="seat" className={VALUE_CLASS} value={form.schedule.kind} options={SCHEDULE_KINDS.map(kind => ({ value: kind, label: t(SCHEDULE_KEYS[kind]) }))} onChange={value => chooseKind(value as ScheduleKind)} />+ </RuleRow>+ {form.schedule.kind === 'once'+ ? (+ <>+ <RuleRow label={t('picker.date')}><DatePicker disabled={locked} value={onceWall.slice(0, 10)} label={t('picker.date')} locale={t('picker.locale')} previousMonthLabel={t('picker.prevMonth')} nextMonthLabel={t('picker.nextMonth')} onChange={date => editOnce(`${date}T${onceWall.slice(11) || '00:00:00'}`)} /></RuleRow>+ <RuleRow label={t('scheduleTime')}><TimePicker disabled={locked} value={onceWall.slice(11)} label={t('scheduleTime')} hourLabel={t('picker.hour')} minuteLabel={t('picker.minute')} secondLabel={t('picker.second')} onChange={time => editOnce(`${onceWall.slice(0, 10)}T${time}`)} /></RuleRow>+ </>+ )+ : form.schedule.kind === 'hourly'+ ? <RuleRow label={t('picker.minute')}><Select disabled={locked} variant="seat" className={VALUE_CLASS} label={t('scheduleHourly')} value={String(form.schedule.minute)} options={MINUTE_OPTIONS} onChange={value => setSchedule({ minute: Number(value) })} /></RuleRow>+ : form.schedule.kind === 'interval'+ ? <RuleRow label={t('scheduleEveryMinutes')}><input className={INPUT_CLASS} type="number" min={Number.MIN_VALUE} step="any" max={525600} required value={form.schedule.everyMinutes} aria-label={t('scheduleEveryMinutes')} onChange={event => setSchedule({ everyMinutes: Number(event.target.value) })} /></RuleRow>+ : (+ <>+ {form.schedule.kind === 'monthly' ? <RuleRow label={t('scheduleMonthDay')}><input className={INPUT_CLASS} type="number" min={1} max={31} required value={form.schedule.day} aria-label={t('scheduleMonthDay')} onChange={event => setSchedule({ day: Number(event.target.value) })} /></RuleRow> : null}+ {form.schedule.kind === 'custom' ? <RuleRow label={t('scheduleEveryDays')}><input className={INPUT_CLASS} type="number" min={1} max={366} required value={form.schedule.everyDays} aria-label={t('scheduleEveryDays')} onChange={event => setSchedule({ everyDays: Number(event.target.value) })} /></RuleRow> : null}+ <RuleRow label={t('scheduleTime')}><TimePicker disabled={locked} seconds={false} value={form.schedule.time} label={t('scheduleTime')} hourLabel={t('picker.hour')} minuteLabel={t('picker.minute')} secondLabel={t('picker.second')} onChange={time => setSchedule({ time })} /></RuleRow>+ {form.schedule.kind === 'weekly' ? <RuleRow label={t('scheduleWeekdays')}><div className="flex flex-wrap justify-end gap-[4px] py-[6px]" role="group" aria-label={t('scheduleWeekdays')}>{WEEKDAYS.map(day => <Checkbox key={day} size="xs" checked={form.schedule.kind === 'weekly' && form.schedule.weekdays.includes(day)} onChange={(checked) => { setForm(state => state.schedule.kind !== 'weekly' ? state : { ...state, schedule: { ...state.schedule, weekdays: checked ? [...state.schedule.weekdays, day] : state.schedule.weekdays.filter(value => value !== day) } }) }}>{t(WEEKDAY_KEYS[day])}</Checkbox>)}</div></RuleRow> : null}+ </>+ )}+ <RuleRow label={t('timeZone')}>+ <TimeZonePicker+ value={zone}+ disabled={locked}+ t={t}+ onChange={(timeZone) => {+ if (locked || timeZone === zone)+ return+ if (form.schedule.kind === 'once')+ setSchedule({ timeZone, at: absoluteDateTime(onceWall, timeZone) })+ else+ setSchedule({ timeZone })+ }}+ />+ </RuleRow>+ </div>+ {form.schedule.kind === 'once' ? <Text size="sm" tone="tertiary" className="mt-[8px] ml-[10px]">{t('detail.onceHint')}</Text> : null}+ </section>+ <details className="mt-[28px]" open={task ? undefined : true}>+ <summary className="mb-[8px] ml-[10px] text-tertiary text-[13px] leading-[20px] cursor-pointer">{t('detail.options')}</summary>+ <div className="flex flex-col px-[12px] border-[0.5px] border-border-l3 rounded-[16px]">+ <RuleRow label={t('delivery')}><Select disabled={locked} label={t('delivery')} variant="seat" className={VALUE_CLASS} value={form.delivery} options={[{ value: 'this-session', label: t('delivery.this-session') }, { value: 'new-session', label: t('delivery.new-session') }]} onChange={delivery => setForm(state => ({ ...state, delivery: delivery === 'this-session' ? delivery : 'new-session', sessionId: state.sessionId || defaultSessionId }))} /></RuleRow>+ {form.delivery === 'this-session'+ ? <RuleRow label={t('session.link')}><Select disabled={locked} label={t('session.link')} variant="seat" className={VALUE_CLASS} value={form.sessionId} options={sessionOptions} onChange={sessionId => setForm(state => ({ ...state, sessionId }))} /></RuleRow>+ : (+ <>+ <RuleRow label={t('workspace')}><Select disabled={locked} label={t('workspace')} variant="seat" className={VALUE_CLASS} value={form.workspaceId} options={workspaceOptions} onChange={workspaceId => setForm(state => ({ ...state, workspaceId }))} /></RuleRow>+ <RuleRow label={t('permission')}><Select disabled={locked} label={t('permission')} variant="seat" className={VALUE_CLASS} value={form.permission} options={permissionOptions} onChange={permission => setForm(state => ({ ...state, permission }))} /></RuleRow>+ <RuleRow label={t('menu.model')}>+ <ModelPicker+ disabled={locked}+ t={t}+ models={options.models}+ failures={options.failures}+ modelKey={modelKey}+ reasoningEffort={form.reasoningEffort || 'none'}+ onSelection={(nextKey, effort) => {+ if (locked)+ return+ const sep = nextKey.indexOf('::')+ setForm(state => ({ ...state, provider: sep >= 0 ? nextKey.slice(0, sep) : '', model: sep >= 0 ? nextKey.slice(sep + 2) : '', reasoningEffort: effort === 'none' ? '' : effort }))+ }}+ />+ </RuleRow>+ </>+ )}+ <RuleRow label={t('resume')}><Checkbox checked={form.enabled} aria-label={t('resume')} onChange={enabled => setForm(state => ({ ...state, enabled }))} /></RuleRow>+ </div>+ </details>+ {form.delivery === 'this-session' ? <Text size="sm" tone={link === 'available' ? 'tertiary' : 'error'} role={link === 'available' ? undefined : 'alert'} className="mt-[8px] ml-[10px]">{link === 'available' ? t('delivery.inherited') : t(`session.${link}`)}</Text> : <Text size="sm" tone="tertiary" className="mt-[8px] ml-[10px]">{t('dialogHint')}</Text>}+ </fieldset>+ {recommendations}+ </div>+ <div hidden={view !== 'records'} role="tabpanel" id={`${panelId}-records-panel`} aria-labelledby={id ? `${id}-records` : undefined} className={view === 'records' ? 'flex flex-1 min-h-0 flex-col' : 'hidden'}>+ {view === 'records'+ ? (+ <>+ <div className="px-[var(--detail-gutter)]">{feedback}</div>+ {history}+ </>+ )+ : null}+ </div>+ {error+ ? (+ <Text tone="error" role="alert" className="shrink-0 px-[var(--detail-gutter)] pt-[12px]">+ {error}+ <br />+ {t('task.conflictHint')}+ </Text>+ )+ : null}+ {dirty && !disabled+ ? (+ <footer className="flex shrink-0 items-center justify-end gap-[8px] px-[var(--detail-gutter)] py-[20px] border-t-[0.5px] border-border-l4 bg-[var(--dsw-alias-bg-base)] [&>button]:h-[32px] [&>button]:text-[13px] [&>button:last-child]:mr-[-8px]">+ <span className="mr-auto text-tertiary text-[12px] max-[760px]:hidden">{t('detail.unsaved')}</span>+ <Button disabled={saving} onClick={cancelDraft}>{t('cancel')}</Button>+ <Button variant="primary" type="submit" disabled={blocked}>{saving ? t('loading') : t('save')}</Button>+ </footer>+ )+ : null}+ </form>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.test.ts b/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.test.tsnew file mode 100644index 00000000..ba2e57d0--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.test.ts@@ -0,0 +1,259 @@+import type { ScheduleForm, TaskFormState } from '../types'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { formFixture, optionsFixture, taskFixture } from './scheduler-client.test.harness'+import { absoluteDateTime, defaultScheduleFor, emptyTaskForm, localDateTime, taskFormInput, taskToForm } from './task-form.utils'++afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('defaultScheduleFor', () => {+ it('creates a one-off task exactly one hour ahead in the chosen timezone', () => {+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2030-05-06T07:08:09.000Z'))+ expect(defaultScheduleFor('once', 'Pacific/Auckland')).toEqual({ kind: 'once', at: '2030-05-06T08:08:09.000Z', timeZone: 'Pacific/Auckland' })+ })++ it.each([+ ['hourly', { kind: 'hourly', minute: 0 }],+ ['interval', { kind: 'interval', everyMinutes: 30 }],+ ['monthly', { kind: 'monthly', day: 1, time: '09:00' }],+ ['custom', { kind: 'custom', everyDays: 2, time: '09:00' }],+ ['weekly', { kind: 'weekly', weekdays: ['MO'], time: '09:00' }],+ ['workdays', { kind: 'workdays', time: '09:00' }],+ ['daily', { kind: 'daily', time: '09:00' }],+ ] satisfies [ScheduleForm['kind'], ScheduleForm][])('uses explicit defaults for %s without replacing the timezone', (kind, expected) => {+ expect(defaultScheduleFor(kind, 'Europe/Berlin')).toEqual({ ...expected, timeZone: 'Europe/Berlin' })+ })++ it('creates an independent weekday array for each default form', () => {+ const first = defaultScheduleFor('weekly', 'UTC')+ const second = defaultScheduleFor('weekly', 'UTC')+ expect(first).toEqual({ kind: 'weekly', weekdays: ['MO'], time: '09:00', timeZone: 'UTC' })+ expect(second).toEqual({ kind: 'weekly', weekdays: ['MO'], time: '09:00', timeZone: 'UTC' })+ if (first.kind !== 'weekly' || second.kind !== 'weekly')+ throw new Error('Expected weekly defaults')+ expect(first.weekdays).not.toBe(second.weekdays)+ })+})++describe('emptyTaskForm', () => {+ it('uses unattended resource defaults without making the linked session the delivery target', () => {+ expect(emptyTaskForm(optionsFixture(), 'session-a')).toEqual({+ delivery: 'new-session',+ sessionId: 'session-a',+ enabled: true,+ name: '',+ prompt: '',+ schedule: { kind: 'daily', time: '09:00', timeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone },+ workspaceId: '',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ })++ it('falls back to read-only and no model when defaults are absent', () => {+ expect(emptyTaskForm(optionsFixture({ defaultPermission: '', defaultModel: null }))).toEqual({+ delivery: 'new-session',+ sessionId: '',+ enabled: true,+ name: '',+ prompt: '',+ schedule: { kind: 'daily', time: '09:00', timeZone: new Intl.DateTimeFormat().resolvedOptions().timeZone },+ workspaceId: '',+ permission: 'read-only',+ provider: '',+ model: '',+ reasoningEffort: '',+ })+ })+})++describe('taskToForm', () => {+ it('copies every selected weekday and timezone independently of later task mutations', () => {+ const task = taskFixture()+ const form = taskToForm(task)+ expect(form.schedule).not.toBe(task.schedule)+ if (task.schedule.kind !== 'weekly' || form.schedule.kind !== 'weekly')+ throw new Error('Expected weekly task fixture')+ expect(form.schedule.weekdays).not.toBe(task.schedule.weekdays)+ task.schedule.time = '18:00'+ task.schedule.timeZone = 'UTC'+ task.prompt = 'External update'+ task.enabled = false+ expect(form).toEqual({+ delivery: 'new-session',+ sessionId: '',+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Task A',+ prompt: 'Original instruction',+ schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ })++ it.each([+ { kind: 'interval', everyMinutes: 17, anchor: '2030-05-01T05:06:07.000Z', timeZone: 'America/New_York' },+ { kind: 'custom', everyDays: 4, anchor: '2030-05-01T05:06:07.000Z', time: '16:45', timeZone: 'Pacific/Auckland' },+ ] satisfies ScheduleForm[])('keeps the persisted anchor for $kind forms', (schedule) => {+ const task = taskFixture({ schedule })+ const form = taskToForm(task)+ expect(form.schedule).toEqual(schedule)+ expect(form.schedule).not.toBe(schedule)+ task.schedule.timeZone = 'UTC'+ expect(form.schedule.timeZone).not.toBe('UTC')+ })++ it('represents an inactive linked-session task without inventing a resource selection', () => {+ expect(taskToForm(taskFixture({+ delivery: 'this-session',+ status: 'inactive',+ sessionId: 'archived-session',+ enabled: false,+ recommendationId: undefined,+ workspaceId: undefined,+ permission: undefined,+ provider: undefined,+ model: undefined,+ reasoningEffort: undefined,+ }))).toEqual({+ delivery: 'this-session',+ sessionId: 'archived-session',+ enabled: false,+ recommendationId: undefined,+ name: 'Task A',+ prompt: 'Original instruction',+ schedule: { kind: 'weekly', weekdays: ['MO', 'WE', 'FR'], time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: '',+ permission: 'read-only',+ provider: '',+ model: '',+ reasoningEffort: '',+ })+ })+})++describe('taskFormInput', () => {+ it('omits all independent resource keys when creating a this-session reminder', () => {+ expect(taskFormInput(formFixture({ delivery: 'this-session' }), false)).toEqual({+ delivery: 'this-session',+ sessionId: 'session-a',+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Draft task',+ prompt: 'Draft instruction',+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ })+ })++ it('clears old independent resource keys when converting an edited task to this-session', () => {+ expect(taskFormInput(formFixture({ delivery: 'this-session' }), true)).toEqual({+ delivery: 'this-session',+ sessionId: 'session-a',+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Draft task',+ prompt: 'Draft instruction',+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: '',+ permission: '',+ provider: '',+ model: '',+ reasoningEffort: '',+ })+ })++ it('clears the old session binding when converting an edited reminder to new-session', () => {+ expect(taskFormInput(formFixture(), true)).toEqual({+ delivery: 'new-session',+ sessionId: '',+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Draft task',+ prompt: 'Draft instruction',+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ })++ it('does not send the default linked session when creating an independent task', () => {+ const input = taskFormInput(formFixture(), false)+ expect(input).toEqual({+ delivery: 'new-session',+ sessionId: undefined,+ enabled: true,+ recommendationId: 'recommendation-a',+ name: 'Draft task',+ prompt: 'Draft instruction',+ schedule: { kind: 'daily', time: '09:30', timeZone: 'Asia/Shanghai' },+ workspaceId: 'workspace-a',+ permission: 'workspace-write',+ provider: 'provider-a',+ model: 'model-a',+ reasoningEffort: 'high',+ })+ expect(JSON.parse(JSON.stringify(input))).not.toHaveProperty('sessionId')+ })++ it.each([+ { kind: 'weekly', weekdays: ['TU', 'TH', 'SU'], time: '21:04', timeZone: 'Europe/Berlin' },+ { kind: 'interval', everyMinutes: 17, anchor: '2030-05-01T05:06:07.000Z', timeZone: 'America/New_York' },+ { kind: 'custom', everyDays: 4, anchor: '2030-05-01T05:06:07.000Z', time: '16:45', timeZone: 'Pacific/Auckland' },+ ] satisfies ScheduleForm[])('captures $kind scheduling data independently before a later draft change', (schedule) => {+ const form: TaskFormState = formFixture({ schedule })+ const input = taskFormInput(form, true)+ expect(input.schedule).toEqual(schedule)+ expect(input.schedule).not.toBe(schedule)+ if (form.schedule.kind === 'weekly' && input.schedule.kind === 'weekly')+ expect(input.schedule.weekdays).not.toBe(form.schedule.weekdays)+ form.schedule.timeZone = 'UTC'+ if (form.schedule.kind === 'weekly')+ form.schedule.weekdays = ['MO']+ expect(input.schedule.timeZone).not.toBe('UTC')+ if (input.schedule.kind === 'weekly')+ expect(input.schedule.weekdays).toEqual(['TU', 'TH', 'SU'])+ })+})++describe('datetime form conversion', () => {+ it('reads and writes an absolute task instant in the chosen zone instead of the device zone', () => {+ expect(localDateTime('2030-05-06T07:08:09.000Z', 'Asia/Tokyo')).toBe('2030-05-06T16:08:09')+ expect(absoluteDateTime('2030-05-06T16:08:09', 'Asia/Tokyo')).toBe('2030-05-06T07:08:09.000Z')+ expect(localDateTime('2030-05-06T07:08:09.125Z', 'Asia/Tokyo')).toBe('2030-05-06T16:08:09.125')+ expect(absoluteDateTime('2030-05-06T16:08:09.125', 'Asia/Tokyo')).toBe('2030-05-06T07:08:09.125Z')+ })++ it('rejects skipped wall time and chooses only the earlier repeated instant', () => {+ expect(absoluteDateTime('2030-03-10T02:30:00', 'America/New_York')).toBe('')+ expect(absoluteDateTime('2030-11-03T01:30:00', 'America/New_York')).toBe('2030-11-03T05:30:00.000Z')+ expect(absoluteDateTime('2030-02-30T12:00:00', 'UTC')).toBe('')+ expect(absoluteDateTime('2030-05-06T07:08:09', 'Invalid/Zone')).toBe('')+ expect(absoluteDateTime('0050-05-06T07:08:09', 'UTC')).toBe('0050-05-06T07:08:09.000Z')+ })++ it('shows local datetime components with seconds for an absolute instant', () => {+ const instant = new Date(2030, 4, 6, 7, 8, 9).toISOString()+ expect(localDateTime(instant)).toBe('2030-05-06T07:08:09')+ })++ it('converts a local datetime draft into an absolute ISO instant', () => {+ expect(absoluteDateTime('2030-05-06T07:08:09')).toBe(new Date(2030, 4, 6, 7, 8, 9).toISOString())+ })++ it.each(['', 'invalid-date'])('rejects invalid datetime text %j without inventing an instant', (value) => {+ expect(localDateTime(value)).toBe('')+ expect(absoluteDateTime(value)).toBe('')+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.ts b/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.tsnew file mode 100644index 00000000..43b595dd--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-form.utils.ts@@ -0,0 +1,137 @@+import type { ScheduleForm, SchedulerOptions, TaskFormState, TaskInput, TaskView } from '../types'+import { cloneDeep } from 'dsh-tauri/client'++const DAY_MS = 86_400_000++export function defaultScheduleFor(kind: ScheduleForm['kind'], timeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone): ScheduleForm {+ switch (kind) {+ case 'once': return { kind, at: new Date(Date.now() + 3_600_000).toISOString(), timeZone }+ case 'hourly': return { kind, minute: 0, timeZone }+ case 'interval': return { kind, everyMinutes: 30, timeZone }+ case 'monthly': return { kind, day: 1, time: '09:00', timeZone }+ case 'custom': return { kind, everyDays: 2, time: '09:00', timeZone }+ case 'weekly': return { kind, weekdays: ['MO'], time: '09:00', timeZone }+ case 'workdays': return { kind, time: '09:00', timeZone }+ default: return { kind: 'daily', time: '09:00', timeZone }+ }+}++export function emptyTaskForm(options: SchedulerOptions, sessionId = ''): TaskFormState {+ return {+ delivery: 'new-session',+ sessionId,+ enabled: true,+ name: '',+ prompt: '',+ schedule: defaultScheduleFor('daily'),+ workspaceId: '',+ permission: options.defaultPermission || 'read-only',+ provider: options.defaultModel?.provider ?? '',+ model: options.defaultModel?.model ?? '',+ reasoningEffort: options.defaultModel?.reasoning?.defaultEffort ?? '',+ }+}++export function taskToForm(task: TaskView): TaskFormState {+ return {+ delivery: task.delivery,+ sessionId: task.sessionId ?? '',+ enabled: task.enabled,+ recommendationId: task.recommendationId,+ name: task.name,+ schedule: cloneDeep(task.schedule),+ prompt: task.prompt,+ workspaceId: task.workspaceId ?? '',+ permission: task.permission ?? 'read-only',+ provider: task.provider ?? '',+ model: task.model ?? '',+ reasoningEffort: task.reasoningEffort ?? '',+ }+}++export function taskFormInput(form: TaskFormState, editing: boolean): TaskInput {+ const input: TaskInput = {+ delivery: form.delivery,+ name: form.name,+ prompt: form.prompt,+ schedule: cloneDeep(form.schedule),+ enabled: form.enabled,+ recommendationId: form.recommendationId,+ }+ if (form.delivery === 'this-session') {+ input.sessionId = form.sessionId+ if (editing)+ Object.assign(input, { workspaceId: '', permission: '', provider: '', model: '', reasoningEffort: '' })+ }+ else {+ Object.assign(input, {+ sessionId: editing ? '' : undefined,+ workspaceId: form.workspaceId,+ permission: form.permission,+ provider: form.provider,+ model: form.model,+ reasoningEffort: form.reasoningEffort,+ })+ }+ return input+}++function wallClock(epoch: number, timeZone?: string): string {+ try {+ const parts = new Intl.DateTimeFormat('en-US', {+ timeZone,+ hourCycle: 'h23',+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ }).formatToParts(epoch)+ const at = (type: Intl.DateTimeFormatPartTypes) => parts.find(part => part.type === type)?.value ?? ''+ return `${at('year').padStart(4, '0')}-${at('month')}-${at('day')}T${at('hour')}:${at('minute')}:${at('second')}`+ }+ catch {+ return ''+ }+}++export function localDateTime(at: string, timeZone?: string): string {+ const date = new Date(at)+ if (!Number.isFinite(date.getTime()))+ return ''+ const wall = wallClock(date.getTime(), timeZone)+ return wall && date.getUTCMilliseconds() ? `${wall}.${String(date.getUTCMilliseconds()).padStart(3, '0')}` : wall+}++export function absoluteDateTime(value: string, timeZone?: string): string {+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/.exec(value)+ if (!match)+ return ''+ const [y, mo, d, h, mi, s] = match.slice(1, 7).map(part => Number(part ?? '00'))+ const calendar = new Date(0)+ calendar.setUTCFullYear(y, mo - 1, d)+ calendar.setUTCHours(h, mi, s, 0)+ if (h > 23 || mi > 59 || s > 59+ || calendar.getUTCFullYear() !== y || calendar.getUTCMonth() !== mo - 1 || calendar.getUTCDate() !== d+ || calendar.getUTCHours() !== h || calendar.getUTCMinutes() !== mi || calendar.getUTCSeconds() !== s) {+ return ''+ }+ const local = calendar.getTime()+ const offsets = new Set<number>()+ for (const delta of [-DAY_MS, 0, DAY_MS]) {+ const wall = wallClock(local + delta, timeZone)+ if (wall)+ offsets.add(Date.parse(`${wall}Z`) - (local + delta))+ }+ let earliest: number | undefined+ for (const offset of offsets) {+ const target = local - offset+ const shown = value.slice(0, 19)+ if (wallClock(target, timeZone) === (shown.length === 16 ? `${shown}:00` : shown)) {+ if (earliest === undefined || target < earliest)+ earliest = target+ }+ }+ return earliest === undefined ? '' : new Date(earliest + Number((match[7] ?? '').padEnd(3, '0'))).toISOString()+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-tab-content.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-tab-content.tsxnew file mode 100644index 00000000..a99757d1--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-tab-content.tsx@@ -0,0 +1,36 @@+import type { ReactElement } from 'react'+import type { TaskTabInfo } from '../types/task-tab'+import type { TaskTabProps } from './task-tab'+import { useWatchImmediate } from 'dsh-tauri/client'+import { SCHEDULE_TASK_KIND } from '../constants'+import { useTaskTabTarget } from '../hooks/use-task-tab-target'+import { TaskDetail } from './task-detail'++export function TaskTabContent(props: TaskTabProps & { tab: TaskTabInfo['tab'] }): ReactElement {+ const { sessionId, tab, taskBindings, t, openHistorySession } = props+ const { navigated, navigation, recovered, params } = useTaskTabTarget(sessionId, tab, taskBindings)+ const sessions = props.useSessions(value => value)+ const workspaces = props.useWorkspaces(value => value)+ useWatchImmediate([navigation?.draft, navigation && !navigation.draft ? navigation.id : undefined, navigation?.sessionId], () => {+ if (navigation?.draft)+ taskBindings.forget(sessionId, tab)+ else if (navigation)+ taskBindings.write(sessionId, tab, navigation)+ })+ return (+ <TaskDetail+ target={params}+ withinSession={sessionId}+ t={t}+ sessions={sessions}+ workspaces={workspaces}+ onClose={tab.actions.close}+ onNavigate={target => tab.actions.openTab(SCHEDULE_TASK_KIND, { params: target })}+ onMissing={() => {+ if (!navigated && recovered)+ taskBindings.forget(sessionId, tab)+ }}+ openHistorySession={openHistorySession}+ />+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-tab-title.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-tab-title.tsxnew file mode 100644index 00000000..a9110566--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-tab-title.tsx@@ -0,0 +1,20 @@+import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'+import type { ReactElement } from 'react'+import type { TaskTabInjected } from './task-tab'+import { Clock, Icon } from 'dsh-tauri-ui/client'+import { useStore } from 'dsh-tauri/client'+import { useTaskTabTarget } from '../hooks/use-task-tab-target'+import { store } from '../store'++export function TaskTabTitle({ sessionId, useTabInfo, taskBindings, t }: PropsRuntime<'sidebar.right.pane.tab.title'> & TaskTabInjected): ReactElement {+ const { tab } = useTabInfo()+ const { params } = useTaskTabTarget(sessionId, tab, taskBindings)+ const { tasks } = useStore(store.scheduler)+ const task = params && !params.draft ? tasks.find(item => item.id === params.id) : undefined+ return (+ <>+ <Icon as={Clock} size={16} className="shrink-0 text-secondary" />+ <span>{params?.draft ? t('createDialogTitle') : task?.name ?? t('editDialogTitle')}</span>+ </>+ )+}diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-tab.test.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-tab.test.tsxnew file mode 100644index 00000000..357641a3--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-tab.test.tsx@@ -0,0 +1,516 @@+// @vitest-environment jsdom+import type { SessionId } from 'dsh-tauri/client'+import type { ComponentProps } from 'react'+import type { TaskView } from '../types'+import type { TaskTabInfo } from '../types/task-tab'+import type { DeliveryHistory } from './delivery-history'+import type { TaskForm } from './task-form'+import type { TaskTabProps } from './task-tab'+import { act, cleanup, fireEvent, render, within } from '@testing-library/react'+import { useSyncExternalStore } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { deleteTasks, getHistory, getOptions, getTasks, postTasks } from '../apis'+import { loadScheduler } from '../service/scheduler'+import { TaskTabBindings } from '../service/task-tab-bindings'+import { store } from '../store'+import { deferred, formFixture, sessionsFixture, taskFixture, translate, workspacesFixture } from './scheduler-client.test.harness'+import { TaskTab } from './task-tab'++type FormProps = ComponentProps<typeof TaskForm>+type HistoryProps = ComponentProps<typeof DeliveryHistory>+type TasksReply = Awaited<ReturnType<typeof getTasks>>+type HistoryReply = Awaited<ReturnType<typeof getHistory>>+type OptionsReply = Awaited<ReturnType<typeof getOptions>>++const observed = vi.hoisted(() => ({ form: vi.fn<(props: FormProps) => void>(), history: vi.fn<(props: HistoryProps) => void>() }))++vi.mock('../apis', () => ({+ getTasks: vi.fn(),+ getHistory: vi.fn(),+ getOptions: vi.fn(),+ deleteTasks: vi.fn(),+ deleteHistory: vi.fn(),+ postTasks: vi.fn(),+ putTasks: vi.fn(),+ postTasksToggle: vi.fn(),+ postTasksRun: vi.fn(),+ postRunsRecover: vi.fn(),+}))+vi.mock('./task-form', () => ({+ TaskForm(props: FormProps) {+ observed.form(props)+ return (+ <section aria-label="form projection">+ {props.feedback}+ <div hidden={props.view === 'records'}>+ <button type="button" disabled={props.disabled} onClick={() => props.onSaved(taskFixture({ id: 'saved-task', sessionId: 'session-b' }))}>save projection</button>+ <button type="button" onClick={props.onClose}>close projection</button>+ {props.recommendations}+ </div>+ {props.history}+ </section>+ )+ },+}))+vi.mock('./delivery-history', () => ({+ DeliveryHistory(props: HistoryProps) {+ observed.history(props)+ return <section aria-label="history projection">{props.taskId}</section>+ },+}))+vi.mock('@deepseek-ai/dsh-client-ui-primitives', async () => {+ const ui = await import('./scheduler-client.test.ui')+ return { Button: ui.PrimitiveButton, Input: ui.PrimitiveInput, Menu: ui.PrimitiveMenu }+})+vi.mock('dsh-tauri-ui/client', async () => {+ const ui = await import('./scheduler-client.test.ui')+ const { Calendar } = await import('../../../../dsh-tauri-ui/src/client/components/icons')+ const { styles } = await import('../../../../dsh-tauri-ui/src/client/constants/theme')+ return { ...await ui.schedulerClientUi(), Calendar, styles }+})++function optionsReply(): OptionsReply {+ return { workspaces: [], permissions: [], defaultPermission: 'read-only', models: [], failures: [], defaultModel: null }+}++function tasksReply(tasks: readonly TaskView[]): TasksReply {+ return { tasks: tasks.map(task => ({ ...task, schedule: task.schedule.kind === 'weekly' ? { ...task.schedule, weekdays: [...task.schedule.weekdays] } : { ...task.schedule } })) }+}++function historyReply(): HistoryReply {+ return { ok: true, records: [], runs: [], earlierRecordsUnavailable: false, earlierRecordsPruned: false, retention: { days: 30, records: 500 } }+}++function resetStores(): void {+ store.scheduler.$patch({ tasks: [], runs: [], options: optionsReply(), loading: false, error: '', refreshedAt: 0, loadToken: 0, successfulReadToken: 0, readAt: 0, readIds: [] })+ store.deletion.$patch({ pendingTask: null, deletingTaskId: null, feedback: null, feedbackSeq: 0 })+ store.navigation.$patch({ target: null, seq: 0, error: '' })+}++beforeEach(() => {+ vi.resetAllMocks()+ vi.stubGlobal('localStorage', (globalThis as unknown as { jsdom: { window: Window } }).jsdom.window.localStorage)+ localStorage.clear()+ resetStores()+ vi.mocked(getTasks).mockResolvedValue(tasksReply([taskFixture()]))+ vi.mocked(getHistory).mockResolvedValue(historyReply())+ vi.mocked(getOptions).mockResolvedValue(optionsReply())+})++afterEach(() => {+ cleanup()+ resetStores()+ localStorage.clear()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++function snapshotFeed<T>(initial: T) {+ let value = initial+ const listeners = new Set<() => void>()+ const subscribe = (listener: () => void) => {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+ }+ const getSnapshot = () => value+ function useValue(): T {+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot)+ }+ return {+ useValue,+ useSnapshot<S>(select: (snapshot: T) => S): S {+ return select(useValue())+ },+ publish(next: T): void {+ value = next+ listeners.forEach(listener => listener())+ },+ }+}++function tabFixture(navigation: TaskTabInfo['tab']['navigation'] = { params: { id: 'task-a' }, revision: 1 }, overrides: Partial<TaskTabInfo['tab']> = {}): TaskTabInfo['tab'] {+ return {+ id: 'page-a',+ kind: 'scheduleTask',+ contentId: 'content-a',+ title: 'Task tab',+ visible: true,+ navigation,+ signal: new AbortController().signal,+ actions: { close: vi.fn(), openTab: vi.fn(), bindCommands: vi.fn(() => vi.fn()) },+ ...overrides,+ }+}++async function renderTab(tab = tabFixture(), taskBindings = new TaskTabBindings()) {+ const sessions = snapshotFeed(sessionsFixture())+ const workspaces = snapshotFeed(workspacesFixture())+ const tabs = snapshotFeed<TaskTabInfo>({ tab })+ const boundary: Pick<TaskTabProps, 'sessionId' | 't' | 'taskBindings' | 'openHistorySession' | 'useTabInfo' | 'useSessions' | 'useWorkspaces'> = {+ sessionId: 'session-a' as SessionId,+ t: translate,+ taskBindings,+ openHistorySession: vi.fn(async () => ({ ok: true })),+ useTabInfo: tabs.useValue,+ useSessions: sessions.useSnapshot,+ useWorkspaces: workspaces.useSnapshot,+ }+ const props = boundary as TaskTabProps+ const view = render(<TaskTab {...props} />)+ await act(async () => {})+ return { ...view, props, tab, taskBindings, sessions, workspaces, tabs }+}++function lastForm(): FormProps {+ expect(observed.form).toHaveBeenCalled()+ return observed.form.mock.lastCall![0]+}++async function lastHistory(view: Awaited<ReturnType<typeof renderTab>>): Promise<HistoryProps> {+ await act(async () => {+ fireEvent.click(view.getByRole('tab', { name: 'detail.records' }))+ })+ expect(observed.history).toHaveBeenCalled()+ return observed.history.mock.lastCall![0]+}++function pendingRead() {+ const tasks = deferred<TasksReply>()+ const history = deferred<HistoryReply>()+ vi.mocked(getTasks).mockImplementationOnce(() => tasks.promise)+ vi.mocked(getHistory).mockImplementationOnce(() => history.promise)+ return { tasks, history }+}++async function resolveRead(read: ReturnType<typeof pendingRead>, tasks: readonly TaskView[]): Promise<void> {+ await act(async () => {+ read.tasks.resolve(tasksReply(tasks))+ read.history.resolve(historyReply())+ await Promise.all([read.tasks.promise, read.history.promise])+ })+}++function recoveredTab(targetId = 'task-a') {+ const tab = tabFixture({ revision: 1 })+ new TaskTabBindings().write('session-a', tab, { id: targetId, sessionId: 'session-a' })+ return { tab, bindings: new TaskTabBindings() }+}++async function finishDeletion(task: TaskView, outcome: { ok: boolean, error?: string }): Promise<void> {+ await act(async () => {+ store.deletion.request(task)+ expect(store.deletion.begin()?.id).toBe(task.id)+ store.deletion.finish(task, outcome)+ })+}++describe('taskTab fresh reads and retained editing snapshot', () => {+ it('disables cached active task editing after a fresh inactive record without replacing the editing snapshot', async () => {+ const cached = taskFixture()+ store.scheduler.$patch({ tasks: [cached] })+ const read = pendingRead()+ const view = await renderTab()+ expect((view.getByRole('button', { name: 'save projection' }) as HTMLButtonElement).disabled).toBe(false)+ expect(lastForm().task).toEqual(cached)+ expect(lastForm().task).not.toBe(cached)+ const fresh = taskFixture({ status: 'inactive', name: 'Fresh task name', prompt: 'Fresh instruction', lastRunAt: '2030-01-03T12:00:00.000Z', schedule: { kind: 'daily', time: '10:00', timeZone: 'UTC' } })+ await resolveRead(read, [fresh])+ expect(view.getByText('task.inactive').textContent).toBe('task.inactive')+ expect((view.getByRole('button', { name: 'save projection' }) as HTMLButtonElement).disabled).toBe(true)+ expect(lastForm().disabled).toBe(true)+ expect(lastForm().task).toEqual(cached)+ expect(view.getByRole('heading', { name: 'Task A' }).textContent).toBe('Task A')+ expect(view.queryByText('Fresh task name')).toBeNull()+ expect(await lastHistory(view)).toMatchObject({ taskId: 'task-a', refreshKey: '2030-01-03T12:00:00.000Z', timeZone: 'Asia/Shanghai' })+ })++ it('does not treat a pre-mount successful catalog read as the required fresh missing answer', async () => {+ store.scheduler.$patch({ loadToken: 4, successfulReadToken: 4 })+ const read = pendingRead()+ const view = await renderTab()+ expect(view.getByRole('status').textContent).toBe('loading')+ expect(view.queryByText('task.missing')).toBeNull()+ expect(store.scheduler.loadToken).toBe(5)+ await resolveRead(read, [])+ expect(view.getByRole('status').textContent).toBe('task.missing')+ expect(store.scheduler.successfulReadToken).toBe(5)+ expect(observed.form).not.toHaveBeenCalled()+ })++ it.each(['tasks', 'history'] as const)('keeps a recovered binding and never reports missing after a failed %s read', async (failure) => {+ store.scheduler.$patch({ loadToken: 4, successfulReadToken: 4 })+ const { tab, bindings } = recoveredTab()+ const read = pendingRead()+ const view = await renderTab(tab, bindings)+ expect(view.getByRole('status').textContent).toBe('loading')+ await act(async () => {+ if (failure === 'tasks') {+ const error = new Error('Catalog read failed')+ read.tasks.reject(error)+ read.history.resolve(historyReply())+ await expect(read.tasks.promise).rejects.toBe(error)+ }+ else {+ read.tasks.resolve(tasksReply([]))+ read.history.resolve({ ok: false, error: 'Catalog read failed' })+ await Promise.all([read.tasks.promise, read.history.promise])+ }+ })+ expect(view.getByRole('status').textContent).toBe('Catalog read failed')+ expect(view.queryByText('task.missing')).toBeNull()+ expect(store.scheduler.successfulReadToken).toBe(4)+ expect(bindings.read('session-a', tab)).toEqual({ id: 'task-a', sessionId: 'session-a' })+ expect(new TaskTabBindings().read('session-a', tab)).toEqual({ id: 'task-a', sessionId: 'session-a' })+ expect(observed.form).not.toHaveBeenCalled()+ })++ it('preserves a cached form and binding after a failed read instead of disabling it as missing', async () => {+ store.scheduler.$patch({ tasks: [taskFixture()] })+ const { tab, bindings } = recoveredTab()+ const read = pendingRead()+ const view = await renderTab(tab, bindings)+ await act(async () => {+ read.tasks.resolve(tasksReply([]))+ read.history.resolve({ ok: false, error: 'History read failed' })+ await Promise.all([read.tasks.promise, read.history.promise])+ })+ expect(view.getByRole('alert').textContent).toBe('History read failed')+ expect(view.queryByText('task.missing')).toBeNull()+ expect(lastForm().disabled).toBe(false)+ expect(lastForm().task?.id).toBe('task-a')+ expect(bindings.read('session-a', tab)).toEqual({ id: 'task-a', sessionId: 'session-a' })+ })++ it('forgets recovered identity only after a later successful fresh missing read', async () => {+ const { tab, bindings } = recoveredTab()+ const failed = pendingRead()+ const view = await renderTab(tab, bindings)+ await act(async () => {+ failed.tasks.resolve(tasksReply([]))+ failed.history.resolve({ ok: false, error: 'Read failed, retry' })+ await Promise.all([failed.tasks.promise, failed.history.promise])+ })+ expect(bindings.read('session-a', tab)).toEqual({ id: 'task-a', sessionId: 'session-a' })+ const retry = pendingRead()+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'refresh' }))+ })+ expect(view.getByRole('status').textContent).toBe('loading')+ const pendingBinding = bindings.read('session-a', tab)+ if (!pendingBinding || !('id' in pendingBinding))+ throw new Error('Expected the recovered task binding during retry')+ expect(pendingBinding.id).toBe('task-a')+ await resolveRead(retry, [])+ expect(view.getByRole('status').textContent).toBe('task.missing')+ expect(bindings.read('session-a', tab)).toBeUndefined()+ expect(new TaskTabBindings().read('session-a', tab)).toBeUndefined()+ expect(localStorage.getItem('dsh.schedule.task-tab.v1.session-a')).toBeNull()+ expect(getTasks).toHaveBeenCalledTimes(2)+ })++ it('keeps retained content readable but disables editing when a fresh successful read removes the task', async () => {+ const cached = taskFixture()+ store.scheduler.$patch({ tasks: [cached] })+ const { tab, bindings } = recoveredTab()+ const read = pendingRead()+ const view = await renderTab(tab, bindings)+ await resolveRead(read, [])+ expect(view.getByRole('status').textContent).toBe('task.missing')+ expect(view.getByRole('heading', { name: 'Task A' }).textContent).toBe('Task A')+ expect(lastForm().task).toEqual(cached)+ expect(lastForm().disabled).toBe(true)+ expect((await lastHistory(view)).taskId).toBe('task-a')+ expect(bindings.read('session-a', tab)).toBeUndefined()+ })++ it('ignores an older missing response after a newer successful catalog response', async () => {+ store.scheduler.$patch({ tasks: [taskFixture()] })+ const oldRead = pendingRead()+ const view = await renderTab()+ const newRead = pendingRead()+ let loading!: Promise<void>+ await act(async () => {+ loading = loadScheduler()+ })+ await resolveRead(newRead, [taskFixture()])+ await loading+ await resolveRead(oldRead, [])+ expect(store.scheduler.successfulReadToken).toBe(2)+ expect(store.scheduler.tasks.map(task => task.id)).toEqual(['task-a'])+ expect(view.queryByText('task.missing')).toBeNull()+ expect(lastForm().disabled).toBe(false)+ })+})++describe('taskTab navigation and draft binding', () => {+ it('uses explicit navigation instead of an unrelated recovered binding', async () => {+ const tab = tabFixture({ params: { id: 'task-a', sessionId: 'session-a' }, revision: 1 })+ const bindings = new TaskTabBindings()+ bindings.write('session-a', tab, { id: 'task-b', sessionId: 'session-b' })+ const view = await renderTab(tab, bindings)+ expect(lastForm().task?.id).toBe('task-a')+ expect((await lastHistory(view)).taskId).toBe('task-a')+ expect(bindings.read('session-a', tab)).toEqual({ id: 'task-a', sessionId: 'session-a' })+ expect(view.getByRole('heading', { name: 'Task A' }).textContent).toBe('Task A')+ })++ it('does not fall back to a recovered identity when explicit navigation is malformed', async () => {+ const tab = tabFixture({ params: { id: 42 }, revision: 1 })+ const bindings = new TaskTabBindings()+ bindings.write('session-a', tab, { id: 'task-a' })+ const view = await renderTab(tab, bindings)+ expect(view.getByRole('status').textContent).toBe('task.unbound')+ expect(observed.form).not.toHaveBeenCalled()+ expect(observed.history).not.toHaveBeenCalled()+ expect(bindings.read('session-a', tab)).toEqual({ id: 'task-a', sessionId: undefined })+ })++ it('resets the retained editing snapshot when the same tab navigates to another task revision', async () => {+ const first = taskFixture()+ const second = taskFixture({ id: 'task-b', name: 'Task B', prompt: 'Task B instruction' })+ vi.mocked(getTasks).mockResolvedValue(tasksReply([first, second]))+ store.scheduler.$patch({ tasks: [first, second] })+ const view = await renderTab()+ const next = { ...view.tab, navigation: { params: { id: 'task-b' }, revision: 2 } }+ await act(async () => {+ view.tabs.publish({ tab: next })+ })+ expect(view.getByRole('heading', { name: 'Task B' }).textContent).toBe('Task B')+ expect(lastForm().task).toEqual(second)+ expect(lastForm().task).not.toBe(second)+ expect((await lastHistory(view)).taskId).toBe('task-b')+ expect(view.taskBindings.read('session-a', next)).toEqual({ id: 'task-b', sessionId: undefined })+ expect(getOptions).toHaveBeenCalledTimes(2)+ })++ it('forgets previous identity for a draft and passes its initial state without selecting a cached task', async () => {+ const initial = formFixture({ name: 'Draft navigation', schedule: { kind: 'interval', everyMinutes: 1.5, anchor: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' } })+ const tab = tabFixture({ params: { draft: true, sessionId: 'session-a', initial }, revision: 1 })+ const bindings = new TaskTabBindings()+ bindings.write('session-a', tab, { id: 'task-a' })+ const view = await renderTab(tab, bindings)+ expect(view.getByRole('heading', { name: 'createDialogTitle' }).textContent).toBe('createDialogTitle')+ expect(lastForm()).toMatchObject({ initial, defaultSessionId: 'session-a', disabled: false })+ expect(lastForm().task).toBeUndefined()+ expect(bindings.read('session-a', tab)).toBeUndefined()+ expect(new TaskTabBindings().read('session-a', tab)).toBeUndefined()+ expect(view.queryByRole('button', { name: 'delete' })).toBeNull()+ expect(observed.history).not.toHaveBeenCalled()+ })++ it('keeps a draft unbound and displays options failure without rendering a partially initialized form', async () => {+ vi.mocked(getOptions).mockRejectedValueOnce(new Error('Model options unavailable'))+ const tab = tabFixture({ params: { draft: true, initial: formFixture() }, revision: 1 })+ const bindings = new TaskTabBindings()+ bindings.write('session-a', tab, { id: 'task-a' })+ const view = await renderTab(tab, bindings)+ expect(view.getByRole('alert').textContent).toBe('Model options unavailable')+ expect(view.getByRole('heading', { name: 'createDialogTitle' }).textContent).toBe('createDialogTitle')+ expect(view.getByRole('region', { name: 'recommended' })).not.toBeNull()+ expect(observed.form).not.toHaveBeenCalled()+ expect(observed.history).not.toHaveBeenCalled()+ expect(bindings.read('session-a', tab)).toBeUndefined()+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ })++ it('keeps task history readable after options failure without losing its binding', async () => {+ vi.mocked(getOptions).mockRejectedValueOnce(new Error('Options read failed'))+ const view = await renderTab()+ expect(view.getByRole('alert').textContent).toBe('Options read failed')+ expect((await lastHistory(view)).taskId).toBe('task-a')+ expect(observed.form).not.toHaveBeenCalled()+ expect(view.taskBindings.read('session-a', view.tab)).toEqual({ id: 'task-a', sessionId: undefined })+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ })++ it('opens a real recommendation as a draft instead of creating or binding a task', async () => {+ const view = await renderTab(tabFixture({ params: { draft: true }, revision: 1 }))+ await act(async () => {+ fireEvent.click(within(view.getByRole('region', { name: 'recommended' })).getByRole('button', { name: /recReviewName/ }))+ })+ expect(view.tab.actions.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', {+ params: { draft: true, sessionId: 'session-a', initial: { delivery: 'new-session', sessionId: '', enabled: false, name: 'recReviewName', schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00' }, prompt: 'recReviewPrompt', workspaceId: '', permission: 'read-only', provider: '', model: '', reasoningEffort: '', recommendationId: 'weekly-review' } },+ })+ expect(postTasks).not.toHaveBeenCalled()+ expect(view.taskBindings.read('session-a', view.tab)).toBeUndefined()+ })++ it('forwards a saved task and close action through the public tab navigation boundary', async () => {+ const view = await renderTab()+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'save projection' }))+ })+ expect(view.tab.actions.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'saved-task', sessionId: 'session-b' } })+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'close projection' }))+ })+ expect(view.tab.actions.close).toHaveBeenCalledTimes(1)+ })+})++describe('taskTab deletion feedback and live session feeds', () => {+ it('requests deletion without closing before confirmation and ignores historical or unrelated feedback', async () => {+ const task = taskFixture()+ await finishDeletion(task, { ok: true })+ const view = await renderTab()+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ await act(async () => {+ fireEvent.click(view.getByRole('button', { name: 'detail.more' }))+ })+ await act(async () => {+ fireEvent.click(view.getByRole('menuitem', { name: 'delete' }))+ })+ expect(store.deletion.pendingTask).toEqual(task)+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ await finishDeletion(taskFixture({ id: 'task-b', name: 'Task B' }), { ok: true })+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ await finishDeletion(task, { ok: false, error: 'Delete failed' })+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ await finishDeletion(task, { ok: true })+ expect(view.tab.actions.close).toHaveBeenCalledTimes(1)+ expect(deleteTasks).not.toHaveBeenCalled()+ })++ it('matches deletion feedback to the new target after the tab navigation revision changes', async () => {+ const first = taskFixture()+ const second = taskFixture({ id: 'task-b', name: 'Task B' })+ vi.mocked(getTasks).mockResolvedValue(tasksReply([first, second]))+ store.scheduler.$patch({ tasks: [first, second] })+ const view = await renderTab()+ const next = { ...view.tab, navigation: { params: { id: 'task-b' }, revision: 2 } }+ await act(async () => {+ view.tabs.publish({ tab: next })+ })+ await finishDeletion(first, { ok: true })+ expect(view.tab.actions.close).not.toHaveBeenCalled()+ await finishDeletion(second, { ok: true })+ expect(view.tab.actions.close).toHaveBeenCalledTimes(1)+ })++ it('updates inherited session availability from real subscription feeds without a catalog reload', async () => {+ const task = taskFixture({ delivery: 'this-session', sessionId: 'session-b', workspaceId: undefined, permission: undefined, provider: undefined, model: undefined, reasoningEffort: undefined })+ vi.mocked(getTasks).mockResolvedValue(tasksReply([task]))+ const view = await renderTab(tabFixture({ params: { id: 'task-a', sessionId: 'session-b' }, revision: 1 }))+ await act(async () => {+ view.sessions.publish(sessionsFixture({ ids: ['session-b' as SessionId], byId: { ['session-b' as SessionId]: { ...sessionsFixture().byId['session-a' as SessionId], id: 'session-b' as SessionId } } }))+ })+ const link = view.getByRole('button', { name: 'session.link: Session A' }) as HTMLButtonElement+ expect(link.disabled).toBe(false)+ vi.mocked(view.props.openHistorySession).mockResolvedValueOnce({ ok: false, error: 'Session open failed' })+ await act(async () => {+ fireEvent.click(link)+ })+ expect(view.props.openHistorySession).toHaveBeenCalledExactlyOnceWith('session-b')+ expect(view.getByRole('alert').textContent).toBe('Session open failed')+ await act(async () => {+ view.workspaces.publish(workspacesFixture({ archivedSessionIds: ['session-b' as SessionId] }))+ })+ expect((view.getByRole('button', { name: 'session.link: Session A' }) as HTMLButtonElement).disabled).toBe(true)+ expect(lastForm().workspaces.archivedSessionIds).toEqual(['session-b'])+ expect((await lastHistory(view)).workspaces.archivedSessionIds).toEqual(['session-b'])+ expect(getTasks).toHaveBeenCalledTimes(1)+ expect(getHistory).toHaveBeenCalledExactlyOnceWith({ limit: 100 })+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/components/task-tab.tsx b/packages/dsh-tauri-scheduler/src/client/components/task-tab.tsxnew file mode 100644index 00000000..79e2a919--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/components/task-tab.tsx@@ -0,0 +1,18 @@+import type { PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'+import type { ReactElement } from 'react'+import type { Translate } from '../locales/index.types'+import type { TaskTabBindings } from '../service/task-tab-bindings'+import { TaskTabContent } from './task-tab-content'++export interface TaskTabInjected {+ t: Translate+ taskBindings: TaskTabBindings+ openHistorySession: (id: string) => Promise<{ ok: boolean, error?: string }>+}++export type TaskTabProps = PropsRuntime<'sidebar.right.pane.tab'> & TaskTabInjected++export function TaskTab(props: TaskTabProps): ReactElement {+ const { tab } = props.useTabInfo()+ return <TaskTabContent key={`${props.sessionId}/${tab.id}/${tab.navigation.revision}`} {...props} tab={tab} />+}diff --git a/packages/dsh-tauri-scheduler/src/client/constants/index.ts b/packages/dsh-tauri-scheduler/src/client/constants/index.tsindex eaeec9a0..11931fe9 100644--- a/packages/dsh-tauri-scheduler/src/client/constants/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/constants/index.ts@@ -11,10 +11,8 @@ export const INPUT_PREFILL_ORDER = 40export const INPUT_PREFILL_PRIORITY = 0export const STYLE_ID = `${PLUGIN_ID}-styles`-export const SESSION_ICON_STYLE_ID = `${PLUGIN_ID}-session-clock-icon`--export const SESSION_ICON_ATTRIBUTE = 'data-dsh-scheduler-icon'-export const SIDEBAR_SELECTOR = '[data-slot="sidebar"]'+export const SCHEDULE_TASK_ID = `${PLUGIN_ID}/task`+export const SCHEDULE_TASK_KIND = 'scheduleTask'export const REFRESH_INTERVAL_MS = 5_000@@ -23,4 +21,5 @@ export const STYLES_EFFECT = `${PLUGIN_ID}: styles`export const HYDRATE_EFFECT = `${PLUGIN_ID}: hydrate`export const PANEL_EFFECT = `${PLUGIN_ID}: panel`export const PREFILL_EFFECT = `${PLUGIN_ID}: prefill`-export const SESSION_ICONS_EFFECT = `${PLUGIN_ID}: session clock icons`+export const AMBIENT_EFFECT = `${PLUGIN_ID}: session schedules`+export const TASK_TAB_EFFECT = `${PLUGIN_ID}: task tabs`diff --git a/packages/dsh-tauri-scheduler/src/client/hooks/use-task-tab-target.ts b/packages/dsh-tauri-scheduler/src/client/hooks/use-task-tab-target.tsnew file mode 100644index 00000000..6860d229--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/hooks/use-task-tab-target.ts@@ -0,0 +1,19 @@+import type { TaskTabBindings } from '../service/task-tab-bindings'+import type { TaskTabInfo } from '../types/task-tab'+import { useWatchImmediate } from 'dsh-tauri/client'+import { useMemo } from 'react'+import { taskTabParams } from '../service/task-tab-bindings'++export function useTaskTabTarget(sessionId: string, tab: TaskTabInfo['tab'], taskBindings: TaskTabBindings) {+ const navigated = tab.navigation.params !== undefined+ const navigation = taskTabParams(tab.navigation.params)+ const recovered = useMemo(+ () => navigated ? undefined : taskBindings.read(sessionId, { id: tab.id, kind: tab.kind, contentId: tab.contentId }),+ [taskBindings, sessionId, tab.id, tab.kind, tab.contentId, navigated],+ )+ useWatchImmediate([sessionId, tab.id, tab.kind, tab.contentId, navigated, tab.navigation.revision], () => {+ if (!navigated)+ taskBindings.dropMismatched(sessionId, tab)+ })+ return { navigated, navigation, recovered, params: navigated ? navigation : recovered }+}diff --git a/packages/dsh-tauri-scheduler/src/client/index.ts b/packages/dsh-tauri-scheduler/src/client/index.tsindex a589a1ec..78795db8 100644--- a/packages/dsh-tauri-scheduler/src/client/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/index.ts@@ -1,22 +1,14 @@import type { ClientContext } from 'dsh-tauri/client'-import {- HYDRATE_EFFECT,- LOCALE_EFFECT,- PANEL_EFFECT,- PLUGIN_ID,- PREFILL_EFFECT,- SESSION_ICONS_EFFECT,- STYLES_EFFECT,-} from './constants'+import { AMBIENT_EFFECT, HYDRATE_EFFECT, LOCALE_EFFECT, PANEL_EFFECT, PLUGIN_ID, PREFILL_EFFECT, STYLES_EFFECT, TASK_TAB_EFFECT } from './constants'import { locale } from './locales'+import { ambientFeature } from './register/ambient'import { hydrateFeature } from './register/hydrate'import { panelFeature } from './register/panel'import { prefillFeature } from './register/prefill'-import { sessionIconsFeature } from './register/session-icons'import { stylesFeature } from './register/styles'+import { taskTabFeature } from './register/task-tab'export const name = PLUGIN_ID-export const inject = ['slots', 'layout', 'locale', 'sessions', 'workspaces']export function apply(ctx: ClientContext): void {@@ -25,5 +17,6 @@ export function apply(ctx: ClientContext): void {ctx.effect(hydrateFeature, HYDRATE_EFFECT)ctx.effect(panelFeature, PANEL_EFFECT)ctx.effect(prefillFeature, PREFILL_EFFECT)- ctx.effect(sessionIconsFeature, SESSION_ICONS_EFFECT)+ ctx.effect(taskTabFeature, TASK_TAB_EFFECT)+ ctx.effect(ambientFeature, AMBIENT_EFFECT)}diff --git a/packages/dsh-tauri-scheduler/src/client/locales/index.ts b/packages/dsh-tauri-scheduler/src/client/locales/index.tsindex 9d0fa5c9..b5a54ab2 100644--- a/packages/dsh-tauri-scheduler/src/client/locales/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/locales/index.ts@@ -4,8 +4,6 @@ import { PLUGIN_ID } from '../constants'const zh = {'scheduler': '定时任务','subtitle': '按计划自动执行任务,也可随时手动触发。在任意对话中描述你想定期做的事,即可快速创建。',- 'tasksTab': '定时任务',- 'runsTab': '执行记录','wakeHint': '定时任务仅在电脑保持唤醒时运行','searchPlaceholder': '搜索定时任务...','sort': '排序',@@ -48,7 +46,7 @@ const zh = {'scheduleMonthly': '每月','scheduleCustom': '自定义','dayShort': '天',- 'scheduleTime': '时间段',+ 'scheduleTime': '时间','scheduleEveryMinutes': '间隔时长','scheduleMonthDay': '每月第几天','scheduleEveryDays': '每隔几天',@@ -122,6 +120,63 @@ const zh = {'perDay': '每天','perWorkday': '工作日','perWeek': '每周',+ 'delivery': '投递方式',+ 'task.session': '会话',+ 'delivery.this-session': '当前会话提醒',+ 'delivery.new-session': '新会话执行',+ 'delivery.inherited': '提醒沿用关联会话的工作区、权限和模型。',+ 'session.link': '关联会话',+ 'session.select': '请选择会话',+ 'session.available': '可用',+ 'session.loading': '会话列表载入中',+ 'session.archived': '会话已归档',+ 'session.unavailable': '会话不可用',+ 'task.inactive': '已终止',+ 'task.missing': '任务不存在或已删除',+ 'task.unbound': '无法恢复任务绑定,请从任务列表重新打开',+ 'task.conflictHint': '如任务已被修改,请重新打开后编辑。当前草稿不会覆盖新数据。',+ 'navigation.unavailable': '当前内核未提供任务右栏,请更新内核。',+ 'navigation.failed': '无法打开任务右栏',+ 'timeZone': '时区',+ 'detail.tabs': '任务详情',+ 'detail.rule': '规则',+ 'detail.records': '任务运行记录',+ 'detail.more': '更多操作',+ 'detail.unsaved': '有未保存的修改',+ 'detail.runtime': '运行时间',+ 'detail.repeat': '重复',+ 'detail.options': '投递与执行设置',+ 'detail.onceHint': '单次任务只保存触发时刻;日期和时间按所选时区换算',+ 'picker.locale': 'zh-CN',+ 'picker.date': '日期',+ 'picker.prevMonth': '上个月',+ 'picker.nextMonth': '下个月',+ 'picker.hour': '时',+ 'picker.minute': '分',+ 'picker.second': '秒',+ 'picker.zoneSearch': '搜索时区',+ 'picker.system': '(系统)',+ 'history.expand': '展开',+ 'history.collapse': '收起',+ 'ambient.mark.origin.aria': '定时任务创建的会话',+ 'history.title': '运行记录',+ 'history.empty': '还没有运行记录',+ 'history.more': '加载更早记录',+ 'history.open': '打开会话',+ 'history.unavailable': '旧记录未完整保留',+ 'history.pruned': '更早记录已裁剪,仅保留最近 {days} 天、最多 {records} 条',+ 'ambient.trigger.one': '查看定时任务',+ 'ambient.trigger.other': '查看 {count} 个定时任务',+ 'ambient.list.aria': '本会话定时任务',+ 'ambient.open': '打开 {name}',+ 'ambient.mark.aria': '本会话有 {count} 个定时任务',+ 'ambient.hover.more': '还有 {count} 个定时任务',+ 'ambient.overdue': '已逾期',+ 'ambient.card.open': '查看任务',+ 'ambient.card.deleted': '任务已删除',+ 'deletion.deleted': '已删除定时任务 {name}',+ 'deletion.failed': '无法删除定时任务 {name}',+ 'deletion.pending': '正在删除定时任务 {name}…',}type LocaleKey = keyof typeof zh@@ -129,8 +184,6 @@ type LocaleKey = keyof typeof zhconst en: Record<LocaleKey, string> = {'scheduler': 'Scheduled Tasks','subtitle': 'Run tasks automatically on a schedule, or trigger them anytime. Describe what you want to run regularly in any chat to create one quickly.',- 'tasksTab': 'Scheduled Tasks',- 'runsTab': 'Run History','wakeHint': 'Scheduled tasks only run while your computer stays awake','searchPlaceholder': 'Search scheduled tasks...','sort': 'Sort',@@ -173,7 +226,7 @@ const en: Record<LocaleKey, string> = {'scheduleMonthly': 'Monthly','scheduleCustom': 'Custom','dayShort': 'd',- 'scheduleTime': 'Time of day',+ 'scheduleTime': 'Time','scheduleEveryMinutes': 'Interval length','scheduleMonthDay': 'Day of month','scheduleEveryDays': 'Every N days',@@ -247,6 +300,63 @@ const en: Record<LocaleKey, string> = {'perDay': 'Daily','perWorkday': 'Workdays','perWeek': 'Weekly',+ 'delivery': 'Delivery',+ 'task.session': 'Session',+ 'delivery.this-session': 'Remind in this session',+ 'delivery.new-session': 'Run in a new session',+ 'delivery.inherited': 'Reminders use the linked session’s workspace, permission and model.',+ 'session.link': 'Linked session',+ 'session.select': 'Select a session',+ 'session.available': 'Available',+ 'session.loading': 'Loading sessions',+ 'session.archived': 'Session archived',+ 'session.unavailable': 'Session unavailable',+ 'task.inactive': 'Inactive',+ 'task.missing': 'Task is missing or deleted',+ 'task.unbound': 'Cannot restore the task binding. Reopen it from the task list.',+ 'task.conflictHint': 'If the task changed, reopen it before editing. Your draft will not overwrite newer data.',+ 'navigation.unavailable': 'This core has no task sidebar. Update the core to enable it.',+ 'navigation.failed': 'Cannot open the task sidebar',+ 'timeZone': 'Time zone',+ 'detail.tabs': 'Task details',+ 'detail.rule': 'Rule',+ 'detail.records': 'Task run history',+ 'detail.more': 'More actions',+ 'detail.unsaved': 'Unsaved changes',+ 'detail.runtime': 'Run time',+ 'detail.repeat': 'Repeat',+ 'detail.options': 'Delivery and execution settings',+ 'detail.onceHint': 'One-time tasks store the instant; date and time use the selected time zone.',+ 'picker.locale': 'en-US',+ 'picker.date': 'Date',+ 'picker.prevMonth': 'Previous month',+ 'picker.nextMonth': 'Next month',+ 'picker.hour': 'Hour',+ 'picker.minute': 'Minute',+ 'picker.second': 'Second',+ 'picker.zoneSearch': 'Search time zones',+ 'picker.system': ' (system)',+ 'history.expand': 'Expand',+ 'history.collapse': 'Collapse',+ 'ambient.mark.origin.aria': 'Session created by a scheduled task',+ 'history.title': 'Run history',+ 'history.empty': 'No run history yet',+ 'history.more': 'Load earlier records',+ 'history.open': 'Open session',+ 'history.unavailable': 'Earlier records were not fully retained',+ 'history.pruned': 'Earlier records pruned. Retaining the latest {days} days and at most {records} records.',+ 'ambient.trigger.one': 'View scheduled task',+ 'ambient.trigger.other': 'View {count} scheduled tasks',+ 'ambient.list.aria': 'Scheduled tasks for this session',+ 'ambient.open': 'Open {name}',+ 'ambient.mark.aria': 'This session has {count} scheduled tasks',+ 'ambient.hover.more': '{count} more scheduled tasks',+ 'ambient.overdue': 'Overdue',+ 'ambient.card.open': 'View task',+ 'ambient.card.deleted': 'Task deleted',+ 'deletion.deleted': 'Deleted scheduled task {name}',+ 'deletion.failed': 'Could not delete scheduled task {name}',+ 'deletion.pending': 'Deleting scheduled task {name}…',}export const locale = defineLocale(PLUGIN_ID, { zh, en })diff --git a/packages/dsh-tauri-scheduler/src/client/register/ambient.test.ts b/packages/dsh-tauri-scheduler/src/client/register/ambient.test.tsnew file mode 100644index 00000000..7a39434c--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/ambient.test.ts@@ -0,0 +1,261 @@+import type { PropsRenderSlots } from '@deepseek-ai/dsh-client-ui-slots'+import type { RegisterEffect } from 'dsh-tauri/client'+import { SlotCore } from '@deepseek-ai/dsh-client-ui-slots'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { ScheduleCatalogAction } from '../components/schedule-catalog-action'+import { ScheduleDeletionOverlay } from '../components/schedule-deletion-overlay'+import { ScheduleTurnCard } from '../components/schedule-turn-card'+import { SessionScheduleHover } from '../components/session-schedule-hover'+import { SessionScheduleMark } from '../components/session-schedule-mark'+import { scheduleTurnDefinition } from '../service/schedule-turn'+import { store } from '../store'+import { ambientFeature } from './ambient'++vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/register'),+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define'),+ ...await import('../../../../dsh-tauri/src/client/locale'),+ noop: () => {},+}))+vi.mock('../components/schedule-catalog-action', () => ({ ScheduleCatalogAction: () => null }))+vi.mock('../components/schedule-deletion-overlay', () => ({ ScheduleDeletionOverlay: () => null }))+vi.mock('../components/schedule-turn-card', () => ({ ScheduleTurnCard: () => null }))+vi.mock('../components/session-schedule-mark', () => ({ SessionScheduleMark: () => null }))+vi.mock('../components/session-schedule-hover', () => ({ SessionScheduleHover: () => null }))++interface Entry {+ name: string+ id: string+ locale: string+ order?: number+ inject?: (sessionId: string) => { sessionId?: string, openTaskDetail?: (id: string) => void }+}++const seats = {+ 'conversation.chat.turnTail': { kind: 'list', scope: 'session' },+ 'conversation.session.header.utilities': { kind: 'list', scope: 'session' },+ 'sidebar.session.row.leading': { kind: 'list', scope: 'root' },+ 'sidebar.session.row.hover': { kind: 'list', scope: 'root' },+ 'shell.overlay': { kind: 'list', scope: 'root' },+}++function runtime(initial: Record<string, { kind: string, scope: string }> = seats) {+ const specs = new Map(Object.entries(initial))+ const pending = new Map<string, { setup: () => () => void, active?: () => void }>()+ const active = new Map<string, { entry: Entry, component: unknown }>()+ const entryDisposals = vi.fn()+ const injectDisposals = vi.fn()+ const slots = {+ spec: vi.fn((name: string) => specs.get(name)),+ inject: vi.fn((name: string, setup: () => () => void) => {+ const record = { setup, active: specs.has(name) ? setup() : undefined }+ pending.set(name, record)+ return () => {+ if (pending.get(name) !== record)+ return+ record.active?.()+ record.active = undefined+ pending.delete(name)+ injectDisposals(name)+ }+ }),+ register: vi.fn((entry: Entry, component: unknown) => {+ active.set(entry.id, { entry, component })+ let disposed = false+ return () => {+ if (disposed)+ return+ disposed = true+ active.delete(entry.id)+ entryDisposals(entry.id)+ }+ }),+ }+ const eventDisposal = vi.fn()+ const events = { register: vi.fn(() => eventDisposal) }+ return {+ slots,+ events,+ active,+ pending,+ entryDisposals,+ injectDisposals,+ eventDisposal,+ context: { slots, uiConversation: { events } },+ declare(name: string, spec = { kind: 'list', scope: 'root' }) {+ pending.get(name)?.active?.()+ specs.set(name, spec)+ const waiting = pending.get(name)+ if (waiting)+ waiting.active = waiting.setup()+ },+ collapse(name: string) {+ const waiting = pending.get(name)+ waiting?.active?.()+ if (waiting)+ waiting.active = undefined+ specs.delete(name)+ },+ }+}++const cleanups: (() => void)[] = []++function mount(context: object) {+ const dispose = ambientFeature.call(context)+ cleanups.push(dispose)+ return dispose+}++beforeEach(() => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ store.navigation.$patch({ target: null, seq: 0, error: '' })+})++afterEach(() => {+ for (const dispose of cleanups.splice(0))+ dispose()+ vi.restoreAllMocks()+})++describe('ambient public registration lifecycle', () => {+ it('keeps its deletion overlay alongside the official native schedule entry without stealing its id', () => {+ const core = new SlotCore()+ const root = core.register({ name: 'root', children: { 'shell.overlay': { kind: 'list', scope: 'root' } } }, (props: PropsRenderSlots<'shell.overlay'>) => props.renderSlot('shell.overlay', {}))+ cleanups.push(root)+ const native = core.register({ name: 'shell.overlay', id: 'schedule.delete-toast' }, () => null)+ cleanups.push(native)+ const slots = {+ spec: core.specDynamic.bind(core),+ inject: (name: string, setup: () => () => void) => core.specDynamic(name) ? setup() : () => {},+ register: core.register.bind(core),+ }+ const dispose = mount({ slots })+ expect(core.entriesOfSlot('shell.overlay').map(entry => entry.options.id)).toEqual(['schedule.delete-toast', 'dsh-tauri-scheduler.delete-toast'])+ dispose()+ expect(core.entriesOfSlot('shell.overlay').map(entry => entry.options.id)).toEqual(['schedule.delete-toast'])+ })++ it('registers exact public entries and the state-only turn definition', () => {+ const host = runtime()+ mount(host.context)+ expect(host.events.register).toHaveBeenCalledExactlyOnceWith(scheduleTurnDefinition)+ expect(host.slots.register.mock.calls.map(([entry, component]) => [entry.name, entry.id, entry.order, entry.locale, component])).toEqual([+ ['conversation.chat.turnTail', 'schedule-created', 20, 'dsh-tauri-scheduler', ScheduleTurnCard],+ ['conversation.session.header.utilities', 'schedule-catalog', -5, 'dsh-tauri-scheduler', ScheduleCatalogAction],+ ['sidebar.session.row.leading', 'schedule-mark', 10, 'dsh-tauri-scheduler', SessionScheduleMark],+ ['sidebar.session.row.hover', 'schedule-tasks', 10, 'dsh-tauri-scheduler', SessionScheduleHover],+ ['shell.overlay', 'dsh-tauri-scheduler.delete-toast', undefined, 'dsh-tauri-scheduler', ScheduleDeletionOverlay],+ ])+ expect(console.warn).not.toHaveBeenCalled()+ host.active.get('schedule-created')!.entry.inject!('owner').openTaskDetail!('created-task')+ expect(store.navigation.target).toEqual({ id: 'created-task', sessionId: 'owner' })+ const header = host.active.get('schedule-catalog')!.entry.inject!('other-owner')+ expect(header.sessionId).toBe('other-owner')+ header.openTaskDetail!('existing-task')+ expect(store.navigation.target).toEqual({ id: 'existing-task', sessionId: 'other-owner' })+ })++ it('owns all slot/event disposers, is idempotent, and leaves no duplicate entries after HMR', () => {+ const host = runtime()+ const dispose = mount(host.context)+ expect(host.active.size).toBe(5)+ dispose()+ dispose()+ expect(host.active.size).toBe(0)+ expect(host.pending.size).toBe(0)+ expect(host.entryDisposals).toHaveBeenCalledTimes(5)+ expect(host.injectDisposals).toHaveBeenCalledTimes(5)+ expect(host.eventDisposal).toHaveBeenCalledTimes(1)+ mount(host.context)+ expect(host.active.size).toBe(5)+ expect(host.pending.size).toBe(5)+ expect(host.events.register).toHaveBeenCalledTimes(2)+ })++ it('waits for late seat declaration and tears down a collapsed seat without DOM fallback', () => {+ const { 'sidebar.session.row.leading': _leading, ...initial } = seats+ const host = runtime(initial)+ mount(host.context)+ expect(host.active.has('schedule-mark')).toBe(false)+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] Public seat sidebar.session.row.leading unavailable; disabled until declared.')+ host.declare('sidebar.session.row.leading')+ expect(host.active.has('schedule-mark')).toBe(true)+ host.collapse('sidebar.session.row.leading')+ expect(host.active.has('schedule-mark')).toBe(false)+ host.declare('sidebar.session.row.leading')+ expect(host.active.has('schedule-mark')).toBe(true)+ expect(host.entryDisposals).toHaveBeenCalledWith('schedule-mark')+ })++ it('warns and disables optional missing services or incompatible seats instead of guessing internals', () => {+ mount({})+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] Public slot spec/inject/register capability unavailable; ambient surfaces disabled.')+ const host = runtime({ ...seats, 'sidebar.session.row.hover': { kind: 'slot', scope: 'session' } })+ mount({ slots: host.slots })+ expect(host.active.has('schedule-created')).toBe(false)+ expect(host.active.has('schedule-tasks')).toBe(false)+ expect(host.active.has('schedule-catalog')).toBe(true)+ expect(host.active.has('dsh-tauri-scheduler.delete-toast')).toBe(true)+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] uiConversation.events.register unavailable; created turn cards disabled.')+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] Public seat sidebar.session.row.hover incompatible; expected list/root.')+ })++ it('isolates a failed seat registration while keeping other optional surfaces usable', () => {+ const host = runtime()+ const register = host.slots.register.getMockImplementation()!+ host.slots.register.mockImplementation((entry, component) => {+ if (entry.id === 'schedule-mark')+ throw new Error('unsupported owner')+ return register(entry, component)+ })+ expect(() => mount(host.context)).not.toThrow()+ expect(host.active.has('schedule-mark')).toBe(false)+ expect(host.active.has('schedule-tasks')).toBe(true)+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] Public seat sidebar.session.row.leading registration failed; surface disabled.', expect.objectContaining({ message: 'unsupported owner' }))+ })++ it('defers turn definition until uiConversation arrives and disposes it on service replacement/unload', () => {+ const host = runtime()+ let available = false+ let dependency: ((scope: object) => unknown) | undefined+ let effectCleanup: (() => void) | undefined+ const fiberDisposal = vi.fn(() => {+ effectCleanup?.()+ effectCleanup = undefined+ })+ const context = {+ slots: host.slots,+ get: (name: string) => name === 'slots' ? host.slots : name === 'uiConversation' && available ? { events: host.events } : undefined,+ effect: (effect: RegisterEffect) => {+ effectCleanup = effect.call(context)+ return effectCleanup+ },+ inject: vi.fn((services: string[], callback: (scope: object) => unknown) => {+ expect(services).toEqual(['uiConversation'])+ dependency = callback+ return { dispose: fiberDisposal }+ }),+ }+ const dispose = mount(context)+ expect(host.events.register).not.toHaveBeenCalled()+ expect(host.active.has('schedule-created')).toBe(false)+ expect(console.warn).toHaveBeenCalledWith('[scheduler ambient] uiConversation unavailable; created turn cards disabled until declared.')+ available = true+ dependency!(context)+ expect(host.events.register).toHaveBeenCalledTimes(1)+ expect(host.active.has('schedule-created')).toBe(true)+ effectCleanup!()+ expect(host.active.has('schedule-created')).toBe(false)+ expect(host.eventDisposal).toHaveBeenCalledTimes(1)+ dependency!(context)+ expect(host.active.has('schedule-created')).toBe(true)+ dispose()+ expect(fiberDisposal).toHaveBeenCalledTimes(1)+ expect(host.eventDisposal).toHaveBeenCalledTimes(2)+ expect(host.active.size).toBe(0)+ dependency!(context)+ expect(host.events.register).toHaveBeenCalledTimes(2)+ expect(host.active.size).toBe(0)+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/register/ambient.tsx b/packages/dsh-tauri-scheduler/src/client/register/ambient.tsxnew file mode 100644index 00000000..87b17116--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/ambient.tsx@@ -0,0 +1,121 @@+import type { ClientContext, RegisterController } from 'dsh-tauri/client'+import type { ComponentType } from 'react'+import { defineRegister, noop } from 'dsh-tauri/client'+import { ScheduleCatalogAction } from '../components/schedule-catalog-action'+import { ScheduleDeletionOverlay } from '../components/schedule-deletion-overlay'+import { ScheduleTurnCard } from '../components/schedule-turn-card'+import { SessionScheduleHover } from '../components/session-schedule-hover'+import { SessionScheduleMark } from '../components/session-schedule-mark'+import { PLUGIN_ID } from '../constants'+import { locale } from '../locales'+import { scheduleTurnDefinition } from '../service/schedule-turn'+import { store } from '../store'++const DELETION_OVERLAY_ID = `${PLUGIN_ID}.delete-toast`++interface AmbientSlotSpec {+ readonly kind: string+ readonly scope: string+}++interface AmbientSlotEntry {+ readonly name: string+ readonly id: string+ readonly order?: number+ readonly locale: string+ readonly inject?: (sessionId: string) => object+}++interface AmbientSlots {+ spec: (name: string) => AmbientSlotSpec | undefined+ inject: (name: string, setup: () => () => void) => () => void+ register: <Props extends object>(entry: AmbientSlotEntry, component: ComponentType<Props>) => () => void+}++interface AmbientConversation {+ readonly events?: {+ register: (definition: typeof scheduleTurnDefinition) => () => void+ }+}++export const ambientFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {+ const slots = adapter.service<AmbientSlots>('slots')+ if (!slots || typeof slots.spec !== 'function' || typeof slots.inject !== 'function' || typeof slots.register !== 'function') {+ console.warn('[scheduler ambient] Public slot spec/inject/register capability unavailable; ambient surfaces disabled.')+ return+ }+ const registerSeat = <Props extends object>(entry: AmbientSlotEntry, scope: 'root' | 'session', component: ComponentType<Props>, owner: RegisterController = controller) => {+ try {+ if (slots.spec(entry.name) === undefined)+ console.warn(`[scheduler ambient] Public seat ${entry.name} unavailable; disabled until declared.`)+ owner.add(slots.inject(entry.name, () => {+ if (controller.isDisposed() || owner.isDisposed())+ return noop+ const spec = slots.spec(entry.name)+ if (spec?.kind !== 'list' || spec.scope !== scope) {+ console.warn(`[scheduler ambient] Public seat ${entry.name} incompatible; expected list/${scope}.`)+ return noop+ }+ try {+ return slots.register(entry, component)+ }+ catch (error) {+ console.warn(`[scheduler ambient] Public seat ${entry.name} registration failed; surface disabled.`, error)+ return noop+ }+ }))+ }+ catch (error) {+ console.warn(`[scheduler ambient] Public seat ${entry.name} capability failed; surface disabled.`, error)+ }+ }+ const taskNavigation = (sessionId: string) => ({+ openTaskDetail: (id: string) => store.navigation.request({ id, sessionId }),+ })+ const turnFeature = defineRegister<ClientContext>((turnController, _turnCtx, turnAdapter) => {+ if (controller.isDisposed())+ return+ const conversation = turnAdapter.service<AmbientConversation>('uiConversation')+ if (typeof conversation?.events?.register !== 'function') {+ console.warn('[scheduler ambient] uiConversation.events.register unavailable; created turn cards disabled.')+ return+ }+ try {+ turnController.add(conversation.events.register(scheduleTurnDefinition))+ registerSeat({+ name: 'conversation.chat.turnTail',+ id: 'schedule-created',+ order: 20,+ locale: locale.NS,+ inject: taskNavigation,+ }, 'session', ScheduleTurnCard, turnController)+ }+ catch (error) {+ console.warn('[scheduler ambient] Conversation definition registration failed; created turn cards disabled.', error)+ }+ })+ if (typeof ctx.inject === 'function') {+ if (adapter.service('uiConversation') === undefined)+ console.warn('[scheduler ambient] uiConversation unavailable; created turn cards disabled until declared.')+ try {+ const fiber = ctx.inject(['uiConversation'], scoped => scoped.effect(turnFeature, 'scheduler: ambient turn'))+ controller.add(() => void fiber.dispose())+ }+ catch (error) {+ console.warn('[scheduler ambient] Conversation dependency injection failed; created turn cards disabled.', error)+ }+ }+ else {+ controller.add(turnFeature.call(ctx))+ }+ registerSeat({+ name: 'conversation.session.header.utilities',+ id: 'schedule-catalog',+ order: -5,+ locale: locale.NS,+ inject: sessionId => ({ ...taskNavigation(sessionId), sessionId }),+ }, 'session', ScheduleCatalogAction)+ registerSeat({ name: 'sidebar.session.row.leading', id: 'schedule-mark', order: 10, locale: locale.NS }, 'root', SessionScheduleMark)+ registerSeat({ name: 'sidebar.session.row.hover', id: 'schedule-tasks', order: 10, locale: locale.NS }, 'root', SessionScheduleHover)+ registerSeat({ name: 'shell.overlay', id: DELETION_OVERLAY_ID, locale: locale.NS }, 'root', ScheduleDeletionOverlay)+})diff --git a/packages/dsh-tauri-scheduler/src/client/register/panel.tsx b/packages/dsh-tauri-scheduler/src/client/register/panel.tsxindex df1d864d..f4e8e8bb 100644--- a/packages/dsh-tauri-scheduler/src/client/register/panel.tsx+++ b/packages/dsh-tauri-scheduler/src/client/register/panel.tsx@@ -1,36 +1,30 @@import type { ClientContext, PanelHandle } from 'dsh-tauri/client'-import type { Translate } from '../locales/index.types'-import { Panel } from 'dsh-tauri-ui/client'import { definePanel, defineRegister } from 'dsh-tauri/client'import { SchedulerNavIcon } from '../components/scheduler-nav-icon'import { SchedulerPanel } from '../components/scheduler-panel'+import { sessionLinkState } from '../components/session-link'import { PANEL_ACTION_ORDER, PANEL_ID, REFRESH_INTERVAL_MS } from '../constants'import { locale } from '../locales'import { loadScheduler } from '../service/scheduler'import { store } from '../store'export const panelFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {- const t: Translate = locale.textconst holder: { current?: PanelHandle } = {}-- // 侧边栏未读角标在面板关闭时也要跟上新运行,所以拉取轮询放在注册层;- // 面板自己只负责首屏(含对话框选项)与回焦刷新。- void loadScheduler(false)- const timer = setInterval(() => {- void loadScheduler(false)- }, REFRESH_INTERVAL_MS)- controller.add(() => clearInterval(timer))-- // 在会话区点开某条运行记录的会话时,同步消掉这条记录的未读。+ void loadScheduler(true)+ controller.interval(() => void loadScheduler(false), REFRESH_INTERVAL_MS)+ controller.listen('visibilitychange', () => {+ if (document.visibilityState === 'visible')+ void loadScheduler(false)+ })+ controller.listenWindow('focus', () => void loadScheduler(false))const sessionList = adapter.sessionList()- if (sessionList !== undefined) {+ if (sessionList) {controller.add(sessionList.subscribe(() => {const current = adapter.sessionList()?.current- if (current !== undefined)+ if (current)store.scheduler.markSessionRead(current)}))}-holder.current = definePanel(ctx, {id: PANEL_ID,order: PANEL_ACTION_ORDER,@@ -38,25 +32,31 @@ export const panelFeature = defineRegister<ClientContext>((controller, ctx, adaplabel: () => locale.text('scheduler'),icon: props => <SchedulerNavIcon size={props.size} />,render: () => (- <Panel>- <SchedulerPanel- t={t}- onViaChat={() => {- store.prefill.set(locale.text('chatPrompt'))- holder.current?.close()- }}- onOpenSession={(sessionId) => {- // 归档的会话会从官方活动列表里消失,放行只会落到空白初始页,所以先拦下。- const listed = adapter.sessionList()?.ids- if (listed !== undefined && !listed.includes(sessionId))- return 'archived'- if (adapter.openSession(sessionId).status === 'unavailable')- return 'unavailable'+ <SchedulerPanel+ t={locale.text}+ sessionsRuntime={ctx.sessions}+ workspacesRuntime={ctx.workspaces}+ openHistorySession={async (id) => {+ const state = sessionLinkState(id, ctx.sessions.list.getSnapshot(), ctx.workspaces.list.getSnapshot())+ if (state !== 'available')+ return { ok: false, error: locale.text(`session.${state}`) }+ try {+ const result = adapter.openSession(id)+ if (result.status !== 'opened')+ return { ok: false, error: locale.text('openRunFailed') }+ await result.valueholder.current?.close()- return 'opened'- }}- />- </Panel>+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) }+ }+ }}+ onViaChat={() => {+ store.prefill.set(locale.text('chatPrompt'))+ holder.current?.close()+ }}+ />),})controller.add(holder.current.dispose)diff --git a/packages/dsh-tauri-scheduler/src/client/register/prefill.ts b/packages/dsh-tauri-scheduler/src/client/register/prefill.tsindex 2017ea21..9c037166 100644--- a/packages/dsh-tauri-scheduler/src/client/register/prefill.ts+++ b/packages/dsh-tauri-scheduler/src/client/register/prefill.ts@@ -11,13 +11,12 @@ import {import { store } from '../store'export const prefillFeature = defineRegister<ClientContext>((controller, ctx) => {- controller.add(ctx.slots.inject(CONVERSATION_INPUT_LEFT_SLOT as never, () => ctx.slots.register({+ controller.add(ctx.slots.inject(CONVERSATION_INPUT_LEFT_SLOT, () => ctx.slots.register({name: CONVERSATION_INPUT_LEFT_SLOT,id: INPUT_PREFILL_ID,registrant: PLUGIN_ID,order: INPUT_PREFILL_ORDER,priority: INPUT_PREFILL_PRIORITY,- inject: (sessionId: string) => ({ sessionId }),- } as never, PrefillBridge)))+ }, PrefillBridge)))controller.add(() => store.prefill.clear())})diff --git a/packages/dsh-tauri-scheduler/src/client/register/session-icons.ts b/packages/dsh-tauri-scheduler/src/client/register/session-icons.tsdeleted file mode 100644index 9ccd53ec..00000000--- a/packages/dsh-tauri-scheduler/src/client/register/session-icons.ts+++ /dev/null@@ -1,90 +0,0 @@-import type { ClientContext } from 'dsh-tauri/client'-import type { Root } from 'react-dom/client'-import { Clock, Icon, mountStyle } from 'dsh-tauri-ui/client'-import { compact, defineRegister, map } from 'dsh-tauri/client'-import { createElement } from 'react'-import { createRoot } from 'react-dom/client'-import { PLUGIN_ID } from '../../shared/constants'-import { SESSION_ICON_ATTRIBUTE, SESSION_ICON_STYLE_ID, SIDEBAR_SELECTOR } from '../constants'-import { store } from '../store'-import sessionIconStyle from '../styles/index.cssr'--const ICON_ROOTS = new WeakMap<Element, Root>()--function removeIcon(icon: Element): void {- ICON_ROOTS.get(icon)?.unmount()- ICON_ROOTS.delete(icon)- icon.remove()-}--interface FiberLike {- key?: unknown- return?: FiberLike | null-}--// HARDCODE: DSH 0.1.1-rc.2 不暴露 per-row 槽位或 data id,只能读私有 React Fiber key。-function rowSessionId(element: Element): string | undefined {- const fiberName = Object.keys(element).find(key => key.startsWith('__reactFiber$'))- if (fiberName === undefined)- return undefined- let fiber = (element as Element & Record<string, FiberLike | undefined>)[fiberName]- for (let depth = 0; fiber && depth < 10; depth++, fiber = fiber.return ?? undefined) {- if (typeof fiber.key === 'string')- return fiber.key- }- return undefined-}--function sessionRows(): Map<string, Element> {- const rows = new Map<string, Element>()- for (const row of document.querySelectorAll<Element>('[role="treeitem"][aria-selected]')) {- const id = rowSessionId(row)- if (id)- rows.set(id, row)- }- return rows-}--// HARDCODE: 锚定 rowActions 而非依赖文案的时间列;空行没有时间列,绝不回退插到标题之前。-function applyIcon(row: Element): void {- if (row.querySelector(`[${SESSION_ICON_ATTRIBUTE}]`))- return- const actions = row.lastElementChild- const time = actions?.previousElementSibling- if (!actions?.querySelector('button') || !time || time.querySelector('button'))- return-- const icon = document.createElement('span')- icon.setAttribute(SESSION_ICON_ATTRIBUTE, '1')- const root = createRoot(icon)- root.render(createElement(Icon, { as: Clock, size: 12 }))- ICON_ROOTS.set(icon, root)- row.insertBefore(icon, time)-}--function scan(): void {- const scheduled = new Set(compact(map(store.scheduler.runs, 'sessionId')))- for (const [sessionId, row] of sessionRows()) {- const icon = row.querySelector<HTMLElement>(`[${SESSION_ICON_ATTRIBUTE}]`)- if (scheduled.has(sessionId)) {- if (!icon)- applyIcon(row)- }- else if (icon) {- removeIcon(icon)- }- }-}--export const sessionIconsFeature = defineRegister<ClientContext>((controller) => {- if (typeof document === 'undefined')- return- controller.add(mountStyle(sessionIconStyle, SESSION_ICON_STYLE_ID, PLUGIN_ID))- controller.observe(document.body, scan)- controller.add(store.scheduler.$subscribe(scan))-- const stopPolling = controller.interval(() => {- if (document.querySelector(SIDEBAR_SELECTOR))- stopPolling()- }, 400)-})diff --git a/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.test.ts b/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.test.tsnew file mode 100644index 00000000..66f47a28--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.test.ts@@ -0,0 +1,759 @@+import type { ILayout, MainPanelId, SessionId, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { Translate } from '../locales/index.types'+import type { TaskTabNavigation } from '../types/task-tab'+import { getEventListeners } from 'node:events'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { createLifecycleController } from '../../../../dsh-tauri/src/client/controller'+import { defineAdapter } from '../../../../dsh-tauri/src/client/register/index.adapter'+import { liveTaskTabIds, openTaskTab } from './task-tab.navigation'++function observable<T>(initial: T) {+ let snapshot = initial+ const listeners = new Set<() => void>()+ return {+ listeners,+ getSnapshot: () => snapshot,+ subscribe(listener: () => void) {+ listeners.add(listener)+ return () => listeners.delete(listener)+ },+ publish(value: T) {+ snapshot = value+ for (const listener of [...listeners])+ listener()+ },+ }+}++function deferred() {+ let resolve = () => {}+ let reject = (_error: unknown) => {}+ const promise = new Promise<void>((done, fail) => {+ resolve = done+ reject = fail+ })+ return { promise, resolve, reject }+}++const cleanups: Array<() => void> = []+const sessionId = (value: string) => value as SessionId+const translate = ((key: string) => key) as Translate++function runtime(options: { ids?: string[], current?: string, original?: string, mounted?: string, archived?: string[] } = {}) {+ const ids = (options.ids ?? ['original', 'current', 'first']).map(sessionId)+ const list = observable<SessionListState & { current?: string }>({+ ids,+ byId: Object.fromEntries(ids.map(id => [id, {+ id,+ displayTitle: id,+ running: false,+ retainedBy: {},+ blank: false,+ updatedAt: 0,+ }])),+ phase: 'ready',+ projectionsBySession: {},+ current: options.current ?? 'current',+ })+ const workspaces = observable<WorkspaceSnapshot>({+ items: [],+ archivedSessionIds: (options.archived ?? []).map(sessionId),+ pinnedSessionIds: [],+ state: 'idle',+ phase: 'ready',+ error: null,+ })+ const mounted = observable<SessionId | undefined>(options.mounted ? sessionId(options.mounted) : undefined)+ const panelInfo = observable<{ activePanelId: MainPanelId | null }>({ activePanelId: 'scheduler' as MainPanelId })+ const calls: string[] = []+ const openSession = vi.fn((id: string): unknown => {+ calls.push(`session:${id}`)+ return undefined+ })+ const startSession = vi.fn((): unknown => {+ calls.push('start')+ return undefined+ })+ const openTab = vi.fn((_kind: string, _options: { params: TaskTabNavigation }) => {+ calls.push('tab')+ })+ const layout: ILayout = {+ panelInfo,+ selectPanel: vi.fn((id: MainPanelId | null) => {+ calls.push(`panel:${id}`)+ panelInfo.publish({ activePanelId: id })+ }),+ beginNavigation: () => new AbortController().signal,+ toggleSidebar: vi.fn(),+ openRightbar: vi.fn(),+ closeRightbar: vi.fn(),+ }+ const uiWorkspace: { openSession?: typeof openSession, startSession?: typeof startSession } = { openSession, startSession }+ const sessions: { list: typeof list, create?: () => Promise<SessionId> } = { list }+ const adapter = defineAdapter({ sessions, workspaces: { list: workspaces }, uiWorkspace }, { onWarn: vi.fn() })+ const controller = createLifecycleController()+ const abort = new AbortController()+ const target: TaskTabNavigation = { id: 'task-1', sessionId: options.original ?? 'original' }+ const input = {+ controller,+ adapter,+ layout,+ sidebar: { mounted, openTab },+ target,+ signal: abort.signal,+ t: translate,+ sessions: list.getSnapshot,+ workspaces: workspaces.getSnapshot,+ }+ cleanups.push(() => {+ abort.abort()+ controller.dispose()+ })+ return { input, controller, abort, list, sessions, workspaces, mounted, panelInfo, calls, openSession, startSession, openTab, layout, uiWorkspace }+}++function observe(promise: Promise<void>) {+ let result: { status: 'opened' } | { status: 'failed', error: unknown } | undefined+ const settled = promise.then(+ () => { result = { status: 'opened' } as const },+ (error) => { result = { status: 'failed', error } as const },+ )+ return { settled, result: () => result }+}++function expectClean(fixture: ReturnType<typeof runtime>) {+ expect(fixture.mounted.listeners.size).toBe(0)+ expect(fixture.panelInfo.listeners.size).toBe(0)+ expect(fixture.list.listeners.size).toBe(0)+ expect(fixture.workspaces.listeners.size).toBe(0)+ expect(getEventListeners(fixture.abort.signal, 'abort')).toHaveLength(0)+ expect(vi.getTimerCount()).toBe(0)+}++beforeEach(() => {+ vi.useFakeTimers()+})++afterEach(() => {+ cleanups.splice(0).reverse().forEach(cleanup => cleanup())+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+})++describe('openTaskTab pending public navigation', () => {+ it('bounds an unresolved openSession promise by the five-second navigation deadline', async () => {+ const fixture = runtime()+ const opening = deferred()+ fixture.openSession.mockReturnValue(opening.promise)+ const request = observe(openTaskTab(fixture.input))++ await vi.advanceTimersByTimeAsync(4_999)+ expect(request.result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)+ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('aborts without waiting for an unresolved openSession promise', async () => {+ const fixture = runtime()+ fixture.openSession.mockReturnValue(deferred().promise)+ const request = observe(openTaskTab(fixture.input))+ const reason = new Error('replaced navigation')++ fixture.abort.abort(reason)+ await vi.advanceTimersByTimeAsync(0)+ expect(request.result()).toEqual({ status: 'failed', error: reason })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('disposes a request whose openSession promise never resolves', async () => {+ const fixture = runtime()+ fixture.openSession.mockReturnValue(deferred().promise)+ const request = observe(openTaskTab(fixture.input))++ fixture.controller.dispose()+ await vi.advanceTimersByTimeAsync(0)+ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('keeps the deadline measured from request creation even when catalog arrival starts navigation late', async () => {+ const fixture = runtime()+ fixture.list.publish({ ...fixture.list.getSnapshot(), phase: 'pending' })+ fixture.openSession.mockReturnValue(deferred().promise)+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(4_970)+ expect(fixture.openSession).not.toHaveBeenCalled()+ fixture.list.publish({ ...fixture.list.getSnapshot(), phase: 'ready' })+ await vi.advanceTimersByTimeAsync(5)+ expect(fixture.openSession).toHaveBeenCalledExactlyOnceWith('original')+ await vi.advanceTimersByTimeAsync(24)+ expect(request.result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('ignores a late successful public navigation after its deadline expires', async () => {+ const fixture = runtime({ mounted: 'original' })+ const opening = deferred()+ fixture.openSession.mockReturnValue(opening.promise)+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(5_000)+ opening.resolve()+ await vi.advanceTimersByTimeAsync(0)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('bounds an unresolved startSession promise by the same navigation deadline', async () => {+ const fixture = runtime({ ids: [] })+ fixture.startSession.mockReturnValue(deferred().promise)+ const request = observe(openTaskTab(fixture.input))++ await vi.advanceTimersByTimeAsync(5_000)+ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.startSession).toHaveBeenCalledTimes(1)+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })+})++describe('openTaskTab public session selection', () => {+ it.each([+ { name: 'available original', options: { mounted: 'original' }, owner: 'original' },+ { name: 'current when original is missing', options: { original: 'missing', mounted: 'current' }, owner: 'current' },+ { name: 'current when original is archived', options: { archived: ['original'], mounted: 'current' }, owner: 'current' },+ { name: 'first when current and original are missing', options: { original: 'missing', current: 'missing', mounted: 'original' }, owner: 'original' },+ { name: 'first non-archived when earlier ids are archived', options: { original: 'missing', archived: ['original', 'current'], mounted: 'first' }, owner: 'first' },+ { name: 'first when no current is selected', options: { original: 'missing', current: '', mounted: 'original' }, owner: 'original' },+ ])('closes the main panel before opening the $name', async ({ options, owner }) => {+ const fixture = runtime(options)+ fixture.sessions.create = vi.fn(async () => sessionId('unneeded'))+ await openTaskTab(fixture.input)++ expect(fixture.sessions.create).not.toHaveBeenCalled()+ expect(fixture.calls).toEqual(['panel:null', `session:${owner}`, 'tab'])+ expect(fixture.openSession).toHaveBeenCalledExactlyOnceWith(owner)+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'task-1', sessionId: options.original ?? 'original' } })+ expectClean(fixture)+ })++ it('starts a new session only when the ready catalog contains no available session', async () => {+ const fixture = runtime({ ids: [], mounted: undefined })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ expect(fixture.calls).toEqual(['panel:null', 'start'])+ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(request.result()).toBeUndefined()++ fixture.list.publish({ ...fixture.list.getSnapshot(), ids: [sessionId('created')] })+ fixture.mounted.publish(sessionId('created'))+ await request.settled+ expect(request.result()).toEqual({ status: 'opened' })+ expect(fixture.calls).toEqual(['panel:null', 'start', 'tab'])+ expectClean(fixture)+ })++ it('creates and opens a real session when workspace navigation would only show the empty hero', async () => {+ const fixture = runtime({ ids: [] })+ fixture.sessions.create = vi.fn(async () => {+ fixture.calls.push('create')+ fixture.list.publish({ ...fixture.list.getSnapshot(), ids: [sessionId('created')] })+ return sessionId('created')+ })+ fixture.openSession.mockImplementation((id) => {+ fixture.calls.push(`session:${id}`)+ fixture.mounted.publish(sessionId(id))+ })++ await openTaskTab(fixture.input)++ expect(fixture.calls).toEqual(['panel:null', 'create', 'session:created', 'tab'])+ expect(fixture.sessions.create).toHaveBeenCalledExactlyOnceWith()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: fixture.input.target })+ expectClean(fixture)+ })++ it.each(['abort', 'dispose', 'deadline'] as const)('does not navigate after session creation completes past %s', async (cancel) => {+ const fixture = runtime({ ids: [] })+ let complete = (_id: SessionId) => {}+ fixture.sessions.create = vi.fn(() => new Promise<SessionId>((resolve) => {+ complete = resolve+ }))+ const request = observe(openTaskTab(fixture.input))+ if (cancel === 'abort')+ fixture.abort.abort(new Error('cancelled'))+ else if (cancel === 'dispose')+ fixture.controller.dispose()+ else+ await vi.advanceTimersByTimeAsync(5_000)+ complete(sessionId('created'))+ await request.settled+ await vi.advanceTimersByTimeAsync(0)++ expect(request.result()?.status).toBe('failed')+ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('does not create an orphan session when the public opening capability is unavailable', async () => {+ const fixture = runtime({ ids: [] })+ fixture.sessions.create = vi.fn(async () => sessionId('created'))+ const adapter = defineAdapter({ sessions: fixture.sessions, workspaces: { list: fixture.workspaces } }, { onWarn: vi.fn() })++ await expect(openTaskTab({ ...fixture.input, adapter })).rejects.toThrow('navigation.unavailable')++ expect(fixture.sessions.create).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('propagates public session creation failure without opening a hero or a task tab', async () => {+ const fixture = runtime({ ids: [] })+ const error = new Error('session creation failed')+ fixture.sessions.create = vi.fn(async () => {+ throw error+ })++ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('does not treat archived rows or a missing current id as live sessions', async () => {+ const fixture = runtime({ ids: ['archived'], archived: ['archived'], original: 'archived', current: 'missing' })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).toHaveBeenCalledTimes(1)++ fixture.list.publish({ ...fixture.list.getSnapshot(), ids: [sessionId('created')] })+ fixture.mounted.publish(sessionId('created'))+ await request.settled+ expect(request.result()).toEqual({ status: 'opened' })+ expectClean(fixture)+ })++ it.each(['sessions', 'workspaces'] as const)('waits for pending %s resources instead of starting another session', async (pending) => {+ const fixture = runtime({ mounted: 'original' })+ if (pending === 'sessions')+ fixture.list.publish({ ...fixture.list.getSnapshot(), phase: 'pending' })+ else+ fixture.workspaces.publish({ ...fixture.workspaces.getSnapshot(), phase: 'pending' })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(24)+ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()++ fixture.list.publish({ ...fixture.list.getSnapshot(), phase: 'ready' })+ fixture.workspaces.publish({ ...fixture.workspaces.getSnapshot(), phase: 'ready' })+ await vi.advanceTimersByTimeAsync(25)+ await request.settled+ expect(request.result()).toEqual({ status: 'opened' })+ expect(fixture.calls).toEqual(['panel:null', 'session:original', 'tab'])+ expectClean(fixture)+ })++ it('reports a visible failure if starting a session shows only a hero with no mounted surface', async () => {+ const fixture = runtime({ ids: [] })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(5_000)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.startSession).toHaveBeenCalledTimes(1)+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })+})++describe('openTaskTab mounted session and public surface readiness', () => {+ it('waits for the selected session to replace the previous mounted session', async () => {+ const fixture = runtime({ mounted: 'current' })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ expect(fixture.openTab).not.toHaveBeenCalled()+ expect(fixture.mounted.listeners.size).toBe(1)++ fixture.mounted.publish(sessionId('original'))+ await request.settled+ expect(request.result()).toEqual({ status: 'opened' })+ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ expectClean(fixture)+ })++ it('rejects a different new mounted session rather than opening on the wrong owner', async () => {+ const fixture = runtime({ mounted: 'current' })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ fixture.mounted.publish(sessionId('first'))+ await request.settled++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('bounds a permanently missing mounted session and removes all readiness subscriptions', async () => {+ const fixture = runtime()+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(4_999)+ expect(request.result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('retries the documented no-session-surface race after 25ms and cleans the deadline', async () => {+ const fixture = runtime({ mounted: 'original' })+ fixture.openTab.mockImplementationOnce(() => {+ throw new Error('sidebarRight: no session surface is mounted')+ })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ expect(request.result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(24)+ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ await vi.advanceTimersByTimeAsync(1)++ expect(request.result()).toEqual({ status: 'opened' })+ expect(fixture.openTab).toHaveBeenCalledTimes(2)+ expectClean(fixture)+ })++ it('bounds a no-session-surface race that never becomes ready', async () => {+ const fixture = runtime({ mounted: 'original' })+ fixture.openTab.mockImplementation(() => {+ throw new Error('sidebarRight: no session surface is mounted')+ })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(5_000)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab.mock.calls.length).toBeGreaterThan(1)+ expectClean(fixture)+ })++ it('does not retry an unrelated public openTab failure', async () => {+ const fixture = runtime({ mounted: 'original' })+ const error = new Error('registration missing')+ fixture.openTab.mockImplementation(() => {+ throw error+ })+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ expectClean(fixture)+ })++ it('rechecks archive status after opening instead of committing on a newly archived surface', async () => {+ const fixture = runtime({ mounted: 'original' })+ const opening = deferred()+ fixture.openSession.mockReturnValue(opening.promise)+ const request = observe(openTaskTab(fixture.input))+ fixture.workspaces.publish({ ...fixture.workspaces.getSnapshot(), archivedSessionIds: [sessionId('original')] })+ opening.resolve()+ await vi.advanceTimersByTimeAsync(5_000)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('waits for a started session to appear in the ready catalog before opening its mounted tab', async () => {+ const fixture = runtime({ ids: [] })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ fixture.mounted.publish(sessionId('created'))+ expect(fixture.openTab).not.toHaveBeenCalled()+ fixture.list.publish({ ...fixture.list.getSnapshot(), ids: [sessionId('created')] })+ await vi.advanceTimersByTimeAsync(25)++ expect(request.result()).toEqual({ status: 'opened' })+ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ expectClean(fixture)+ })+})++describe('openTaskTab cancellation and cleanup', () => {+ it('rejects an already-aborted request without changing panel or session', async () => {+ const fixture = runtime({ mounted: 'original' })+ const reason = new Error('already replaced')+ fixture.abort.abort(reason)+ await expect(openTaskTab(fixture.input)).rejects.toBe(reason)++ expect(fixture.calls).toEqual([])+ expectClean(fixture)+ })++ it('rejects a disposed controller before acquiring any public navigation resources', async () => {+ const fixture = runtime({ mounted: 'original' })+ fixture.controller.dispose()+ await expect(openTaskTab(fixture.input)).rejects.toThrow('navigation.failed')++ expect(fixture.calls).toEqual([])+ expectClean(fixture)+ })++ it('aborts while waiting for a mounted session and ignores its later mount', async () => {+ const fixture = runtime()+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ const reason = new Error('cancelled request')+ fixture.abort.abort(reason)+ await request.settled+ fixture.mounted.publish(sessionId('original'))+ await vi.advanceTimersByTimeAsync(25)++ expect(request.result()).toEqual({ status: 'failed', error: reason })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('cancels a scheduled surface retry immediately when the request aborts', async () => {+ const fixture = runtime({ mounted: 'original' })+ fixture.openTab.mockImplementation(() => {+ throw new Error('sidebarRight: no session surface is mounted')+ })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ fixture.abort.abort(new Error('replaced'))+ await request.settled+ await vi.advanceTimersByTimeAsync(100)++ expect(fixture.openTab).toHaveBeenCalledTimes(1)+ expectClean(fixture)+ })++ it('settles and unsubscribes immediately when its real lifecycle controller is disposed', async () => {+ const fixture = runtime()+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ fixture.controller.dispose()+ await request.settled+ fixture.mounted.publish(sessionId('original'))++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('rejects when a main panel replaces the navigation while waiting for a surface', async () => {+ const fixture = runtime()+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)+ fixture.panelInfo.publish({ activePanelId: 'other-panel' as MainPanelId })+ await request.settled+ fixture.mounted.publish(sessionId('original'))++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.failed') })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it.each(['resolve', 'reject'] as const)('ignores a late public promise %s after abort without leaking listeners or retry timers', async (settle) => {+ const fixture = runtime({ mounted: 'original' })+ const opening = deferred()+ fixture.openSession.mockReturnValue(opening.promise)+ const request = observe(openTaskTab(fixture.input))+ const reason = new Error('superseded')+ fixture.abort.abort(reason)+ await vi.advanceTimersByTimeAsync(0)+ if (settle === 'resolve')+ opening.resolve()+ else+ opening.reject(new Error('late service failure'))+ await vi.advanceTimersByTimeAsync(0)++ expect(request.result()).toEqual({ status: 'failed', error: reason })+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('lets a replacement request open exactly its new target while the old public promise is still pending', async () => {+ const fixture = runtime({ mounted: 'original' })+ const opening = deferred()+ fixture.openSession.mockReturnValueOnce(opening.promise)+ const first = observe(openTaskTab(fixture.input))+ fixture.abort.abort(new Error('new request'))+ const replacement = new AbortController()+ await openTaskTab({ ...fixture.input, signal: replacement.signal, target: { id: 'task-2', sessionId: 'original' } })+ opening.resolve()+ await vi.advanceTimersByTimeAsync(0)++ expect(first.result()?.status).toBe('failed')+ expect(fixture.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'task-2', sessionId: 'original' } })+ expect(getEventListeners(replacement.signal, 'abort')).toHaveLength(0)+ expectClean(fixture)+ })++ it('does not let disposing a completed controller affect a later independent navigation', async () => {+ const first = runtime({ mounted: 'original' })+ await openTaskTab(first.input)+ const second = runtime()+ const request = observe(openTaskTab(second.input))+ await vi.advanceTimersByTimeAsync(0)+ first.controller.dispose()+ expect(request.result()).toBeUndefined()+ second.mounted.publish(sessionId('original'))+ await request.settled++ expect(request.result()).toEqual({ status: 'opened' })+ expect(first.openTab).toHaveBeenCalledTimes(1)+ expect(second.openTab).toHaveBeenCalledTimes(1)+ expectClean(first)+ expectClean(second)+ })+})++describe('openTaskTab public service failures', () => {+ it('fails closed on an unavailable workspace snapshot instead of starting a new session', async () => {+ const fixture = runtime()+ fixture.workspaces.publish({ ...fixture.workspaces.getSnapshot(), state: 'error' })+ const request = observe(openTaskTab(fixture.input))+ await vi.advanceTimersByTimeAsync(0)++ expect(request.result()).toEqual({ status: 'failed', error: new Error('navigation.unavailable') })+ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it.each(['open', 'start'] as const)('cleans all resources when the public %s service throws', async (service) => {+ const fixture = runtime(service === 'start' ? { ids: [] } : {})+ const error = new Error(`${service} failed`)+ const ability = service === 'start' ? fixture.startSession : fixture.openSession+ ability.mockImplementation(() => {+ throw error+ })+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it.each(['open', 'start'] as const)('cleans all resources when the public %s service promise rejects', async (service) => {+ const fixture = runtime(service === 'start' ? { ids: [] } : {})+ const error = new Error(`${service} rejected`)+ const ability = service === 'start' ? fixture.startSession : fixture.openSession+ ability.mockImplementation(() => Promise.reject(error))+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('cleans resources if selecting the registered main panel throws', async () => {+ const fixture = runtime()+ const error = new Error('layout unavailable')+ vi.mocked(fixture.layout.selectPanel).mockImplementation(() => {+ throw error+ })+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('does not report success for a public navigation promise rejected without a reason', async () => {+ const fixture = runtime({ mounted: 'original' })+ const opening = deferred()+ fixture.openSession.mockReturnValue(opening.promise)+ const request = observe(openTaskTab(fixture.input))+ opening.reject(undefined)+ await vi.advanceTimersByTimeAsync(0)++ expect(request.result()?.status).toBe('failed')+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('removes already-acquired lifecycle resources if the public mounted subscription throws', async () => {+ const fixture = runtime()+ const error = new Error('mounted service disposed')+ vi.spyOn(fixture.mounted, 'subscribe').mockImplementation(() => {+ throw error+ })+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('removes an acquired mounted subscription if the public panel subscription throws', async () => {+ const fixture = runtime()+ const error = new Error('layout service disposed')+ vi.spyOn(fixture.panelInfo, 'subscribe').mockImplementation(() => {+ throw error+ })+ await expect(openTaskTab(fixture.input)).rejects.toBe(error)++ expect(fixture.openSession).not.toHaveBeenCalled()+ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('reports unavailable instead of trying to start when the selected session cannot be opened', async () => {+ const fixture = runtime()+ delete fixture.uiWorkspace.openSession+ const adapter = defineAdapter({ sessions: { list: fixture.list }, workspaces: { list: fixture.workspaces } }, { onWarn: vi.fn() })+ await expect(openTaskTab({ ...fixture.input, adapter })).rejects.toThrow('navigation.unavailable')++ expect(fixture.openTab).not.toHaveBeenCalled()+ expect(fixture.startSession).not.toHaveBeenCalled()+ expectClean(fixture)+ })++ it('reports unavailable when a ready empty catalog has no public startSession capability', async () => {+ const fixture = runtime({ ids: [] })+ const adapter = defineAdapter({ sessions: { list: fixture.list }, workspaces: { list: fixture.workspaces } }, { onWarn: vi.fn() })+ await expect(openTaskTab({ ...fixture.input, adapter })).rejects.toThrow('navigation.unavailable')++ expect(fixture.openTab).not.toHaveBeenCalled()+ expectClean(fixture)+ })+})++describe('liveTaskTabIds', () => {+ it('reads only public tab page ids from the requested session', () => {+ const tabsIn = vi.fn(() => [+ { id: 'page-1', kind: 'scheduleTask', contentId: 'content-1' },+ { id: 'page-2', kind: 'files', contentId: 'content-2' },+ ])+ const fixture = runtime()+ expect(liveTaskTabIds({ ...fixture.input.sidebar, tabsIn }, 'owner')).toEqual(['page-1', 'page-2'])+ expect(tabsIn).toHaveBeenCalledExactlyOnceWith('owner')+ })++ it('preserves unknown vs empty capability results for conservative pruning', () => {+ const fixture = runtime()+ expect(liveTaskTabIds(undefined, 'owner')).toBeUndefined()+ expect(liveTaskTabIds(fixture.input.sidebar, 'owner')).toBeUndefined()+ expect(liveTaskTabIds({ ...fixture.input.sidebar, tabsIn: () => [] }, 'owner')).toEqual([])+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.ts b/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.tsnew file mode 100644index 00000000..4c68003e--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/task-tab.navigation.ts@@ -0,0 +1,174 @@+import type { ClientAdapter, ILayout, ISessions, LifecycleController, SessionId, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { Translate } from '../locales/index.types'+import type { SidebarRight, TaskTabNavigation } from '../types/task-tab'+import { sessionLinkState } from '../components/session-link'+import { SCHEDULE_TASK_KIND } from '../constants'++interface NavigationRuntime {+ controller: LifecycleController+ adapter: ClientAdapter+ layout: ILayout+ sidebar: SidebarRight+ target: TaskTabNavigation+ signal: AbortSignal+ t: Translate+ sessions: () => SessionListState+ workspaces: () => WorkspaceSnapshot+}++export async function openTaskTab({ controller, adapter, layout, sidebar, target, signal, t, sessions, workspaces }: NavigationRuntime): Promise<void> {+ signal.throwIfAborted()+ if (controller.isDisposed())+ throw new Error(t('navigation.failed'))+ await new Promise<void>((resolve, reject) => {+ let settled = false+ let started = false+ let navigated = false+ let owner: string | undefined+ const previouslyMounted = sidebar.mounted.getSnapshot()+ let cancelRetry = () => {}+ let unsubscribe = () => {}+ let unsubscribePanel = () => {}+ let cancelDeadline = () => {}+ let unhookDisposal = () => {}+ const finish = (error?: unknown) => {+ if (settled)+ return+ settled = true+ cancelRetry()+ cancelDeadline()+ unsubscribe()+ unsubscribePanel()+ unhookDisposal()+ signal.removeEventListener('abort', abort)+ error === undefined ? resolve() : reject(error)+ }+ const fail = (error: unknown) => finish(error ?? new Error(t('navigation.failed')))+ function abort(): void {+ fail(signal.reason)+ }+ const retry = () => {+ cancelRetry()+ cancelRetry = controller.timeout(attempt, 25)+ }+ function attempt(): void {+ if (settled)+ return+ if (signal.aborted || controller.isDisposed()) {+ abort()+ return+ }+ if (!started) {+ const list = sessions()+ const workspace = workspaces()+ if (list.phase === 'pending' || workspace.phase === 'pending') {+ retry()+ return+ }+ if (workspace.state === 'error' || workspace.error) {+ finish(new Error(t('navigation.unavailable')))+ return+ }+ const linked = target.sessionId && sessionLinkState(target.sessionId, list, workspace) === 'available' ? target.sessionId : undefined+ const current = adapter.sessionList()?.current+ owner = linked ?? (current && sessionLinkState(current, list, workspace) === 'available' ? current : undefined)+ ?? list.ids.find(id => sessionLinkState(id, list, workspace) === 'available')+ started = true+ try {+ layout.selectPanel(null)+ let opening: unknown+ if (owner) {+ const result = adapter.openSession(owner)+ if (result.status !== 'opened') {+ finish(new Error(t('navigation.unavailable')))+ return+ }+ opening = result.value+ }+ else {+ const sessions = adapter.service<Partial<ISessions>>('sessions')+ if (typeof sessions?.create === 'function') {+ if (!adapter.resolveOpenSession()) {+ finish(new Error(t('navigation.unavailable')))+ return+ }+ opening = sessions.create().then((id) => {+ if (settled || signal.aborted || controller.isDisposed())+ return+ owner = id+ const result = adapter.openSession(id)+ if (result.status !== 'opened')+ throw new Error(t('navigation.unavailable'))+ return result.value+ })+ }+ else {+ const start = adapter.resolveStartSession()+ if (!start) {+ finish(new Error(t('navigation.unavailable')))+ return+ }+ opening = start()+ }+ }+ void Promise.resolve(opening).then(() => {+ if (settled)+ return+ navigated = true+ attempt()+ }, fail)+ }+ catch (error) {+ fail(error)+ }+ return+ }+ if (!navigated)+ return+ const mounted = sidebar.mounted.getSnapshot()+ if (!mounted || (owner && mounted !== owner)) {+ if (mounted && mounted !== previouslyMounted)+ finish(new Error(t('navigation.failed')))+ return+ }+ if (sessionLinkState(mounted, sessions(), workspaces()) !== 'available') {+ retry()+ return+ }+ try {+ sidebar.openTab(SCHEDULE_TASK_KIND, { params: target })+ finish()+ }+ catch (error) {+ if (error instanceof Error && error.message === 'sidebarRight: no session surface is mounted')+ retry()+ else+ fail(error)+ }+ }+ try {+ signal.addEventListener('abort', abort, { once: true })+ unhookDisposal = controller.add(() => fail(undefined))+ cancelDeadline = controller.timeout(() => fail(undefined), 5_000)+ unsubscribe = sidebar.mounted.subscribe(attempt)+ unsubscribePanel = layout.panelInfo.subscribe(() => {+ if (layout.panelInfo.getSnapshot().activePanelId !== null)+ fail(undefined)+ })+ if (settled) {+ unsubscribe()+ unsubscribePanel()+ }+ else {+ attempt()+ }+ }+ catch (error) {+ fail(error)+ }+ })+}++export function liveTaskTabIds(sidebar: SidebarRight | undefined, sessionId: string): readonly string[] | undefined {+ return sidebar?.tabsIn?.(sessionId as SessionId).map(tab => tab.id)+}diff --git a/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.harness.ts b/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.harness.tsnew file mode 100644index 00000000..26482396--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.harness.ts@@ -0,0 +1,275 @@+import type { ILayout, MainPanelId, SessionId, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { TaskTabInjected } from '../components/task-tab'+import type { SidebarRightTabs, TaskTabNavigation } from '../types/task-tab'+import { vi } from 'vitest'++export interface TaskTabSeatSpec {+ kind: string+ scope: string+}++interface TaskTabSeatEntry {+ name: string+ key: string+ inject: () => TaskTabInjected+}++interface SeatInjection {+ name: string+ setup: () => () => void+ cleanup?: () => void+ stopped: boolean+}++interface ServiceInjection {+ names: readonly string[]+ setup: (scope: object) => unknown+ snapshot?: readonly unknown[]+ cleanup?: () => void+ loaded: boolean+ stopped: boolean+}++export const taskTabSeats: Readonly<Record<string, TaskTabSeatSpec>> = {+ 'sidebar.right.pane.tab': { kind: 'keyed', scope: 'session' },+ 'sidebar.right.pane.tab.title': { kind: 'keyed', scope: 'session' },+}++function observable<T>(initial: T) {+ let snapshot = initial+ const listeners = new Set<() => void>()+ return {+ listeners,+ getSnapshot: () => snapshot,+ subscribe(listener: () => void) {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+ },+ publish(value: T) {+ snapshot = value+ for (const listener of [...listeners])+ listener()+ },+ }+}++export function taskTabRuntime(initial: Readonly<Record<string, TaskTabSeatSpec>> = taskTabSeats) {+ const specs = new Map(Object.entries(initial))+ const seatInjections = new Set<SeatInjection>()+ const serviceInjections = new Set<ServiceInjection>()+ const activeSeats = new Map<string, { entry: TaskTabSeatEntry, component: unknown }>()+ const definitions = new Map<string, Parameters<SidebarRightTabs['register']>[0]>()+ const registrationFailures = new Map<string, Error>()+ const declarationFailures: unknown[] = []+ const seatDisposals = vi.fn((_name: string) => {})+ const injectionDisposals = vi.fn((_name: string) => {})+ const definitionDisposals = vi.fn((_id: string) => {})+ const fiberDisposals = vi.fn()++ function stopSeat(record: SeatInjection) {+ if (record.stopped)+ return+ record.stopped = true+ record.cleanup?.()+ record.cleanup = undefined+ seatInjections.delete(record)+ injectionDisposals(record.name)+ }++ const slots = {+ spec: vi.fn((name: string) => specs.get(name)),+ inject: vi.fn((name: string, setup: () => () => void) => {+ const record: SeatInjection = { name, setup, stopped: false }+ seatInjections.add(record)+ try {+ if (specs.has(name))+ record.cleanup = setup()+ }+ catch (error) {+ stopSeat(record)+ throw error+ }+ return () => stopSeat(record)+ }),+ register: vi.fn((entry: TaskTabSeatEntry, component: unknown) => {+ const failure = registrationFailures.get(entry.name)+ if (failure)+ throw failure+ const key = `${entry.name}:${entry.key}`+ if (activeSeats.has(key))+ throw new Error('Duplicate task tab seat contribution')+ activeSeats.set(key, { entry, component })+ let disposed = false+ return () => {+ if (disposed)+ return+ disposed = true+ activeSeats.delete(key)+ seatDisposals(entry.name)+ }+ }),+ }+ const registry = {+ register: vi.fn((definition: Parameters<SidebarRightTabs['register']>[0]) => {+ if (definitions.has(definition.id))+ throw new Error('Duplicate task tab definition')+ definitions.set(definition.id, definition)+ let disposed = false+ return () => {+ if (disposed)+ return+ disposed = true+ definitions.delete(definition.id)+ definitionDisposals(definition.id)+ }+ }),+ }+ const owner = 'owner' as SessionId+ const sessionList = observable<SessionListState & { current: SessionId }>({+ ids: [owner],+ byId: {+ [owner]: { id: owner, displayTitle: 'Owner', running: false, retainedBy: {}, blank: false, updatedAt: 0 },+ },+ projectionsBySession: {},+ current: owner,+ phase: 'ready',+ })+ const workspaceList = observable<WorkspaceSnapshot>({+ items: [],+ archivedSessionIds: [],+ pinnedSessionIds: [],+ state: 'idle',+ phase: 'ready',+ error: null,+ })+ const mounted = observable<SessionId | undefined>(owner)+ const panelInfo = observable<{ activePanelId: MainPanelId | null }>({ activePanelId: 'scheduler' as MainPanelId })+ const openTab = vi.fn((_kind: string, _options: { params: TaskTabNavigation }) => {})+ const openSession = vi.fn((_id: string): unknown => undefined)+ const startSession = vi.fn((): unknown => undefined)+ const sidebar = { mounted, openTab, tabsIn: vi.fn((_id: SessionId) => []) }+ const layout: ILayout = {+ panelInfo,+ selectPanel: vi.fn((id: MainPanelId | null) => panelInfo.publish({ activePanelId: id })),+ beginNavigation: () => new AbortController().signal,+ toggleSidebar: vi.fn(),+ openRightbar: vi.fn(),+ closeRightbar: vi.fn(),+ }+ const sessions = { list: sessionList }+ const workspaces = { list: workspaceList }+ const services = new Map<string, unknown>([+ ['sidebarRight', sidebar],+ ['sidebarRightTabs', registry],+ ['slots', slots],+ ['layout', layout],+ ['sessions', sessions],+ ['workspaces', workspaces],+ ['uiWorkspace', { openSession, startSession }],+ ])++ function reconcile(record: ServiceInjection, scope: object) {+ if (record.stopped)+ return+ const snapshot = record.names.map(name => services.get(name))+ const ready = snapshot.every(value => value !== undefined)+ if (record.loaded && ready && snapshot.every((value, index) => value === record.snapshot?.[index]))+ return+ record.cleanup?.()+ record.cleanup = undefined+ record.loaded = false+ record.snapshot = undefined+ if (!ready)+ return+ record.loaded = true+ record.snapshot = snapshot+ const cleanup = record.setup(scope)+ if (typeof cleanup === 'function')+ record.cleanup = () => { cleanup() }+ }++ const context = {+ sessions,+ workspaces,+ get: vi.fn((name: string) => services.get(name)),+ inject: vi.fn((names: string[], setup: (scope: object) => unknown) => {+ const record: ServiceInjection = { names, setup, loaded: false, stopped: false }+ serviceInjections.add(record)+ reconcile(record, context)+ return {+ dispose: vi.fn(() => {+ if (!record.stopped) {+ record.stopped = true+ record.cleanup?.()+ record.cleanup = undefined+ serviceInjections.delete(record)+ fiberDisposals()+ }+ return Promise.resolve()+ }),+ }+ }),+ }++ return {+ context,+ slots,+ registry,+ sidebar,+ layout,+ mounted,+ panelInfo,+ sessionList,+ workspaceList,+ openTab,+ openSession,+ startSession,+ activeSeats,+ definitions,+ seatInjections,+ serviceInjections,+ declarationFailures,+ seatDisposals,+ injectionDisposals,+ definitionDisposals,+ fiberDisposals,+ provide(name: string, service: unknown) {+ if (service === undefined)+ services.delete(name)+ else+ services.set(name, service)+ for (const record of [...serviceInjections])+ reconcile(record, context)+ },+ failRegistration(name: string, error: Error) {+ registrationFailures.set(name, error)+ },+ declare(name: string, spec: TaskTabSeatSpec = { kind: 'keyed', scope: 'session' }) {+ specs.set(name, spec)+ for (const record of [...seatInjections]) {+ if (record.name !== name || record.stopped)+ continue+ record.cleanup?.()+ record.cleanup = undefined+ try {+ record.cleanup = record.setup()+ }+ catch (error) {+ stopSeat(record)+ declarationFailures.push(error)+ }+ }+ },+ collapse(name: string) {+ specs.delete(name)+ for (const record of [...seatInjections]) {+ if (record.name !== name)+ continue+ record.cleanup?.()+ record.cleanup = undefined+ }+ },+ }+}diff --git a/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.ts b/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.tsnew file mode 100644index 00000000..c0cee86c--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/task-tab.test.ts@@ -0,0 +1,503 @@+import type { TaskTabSeatSpec } from './task-tab.test.harness'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { TaskTab } from '../components/task-tab'+import { TaskTabTitle } from '../components/task-tab-title'+import { locale } from '../locales'+import { TaskTabBindings } from '../service/task-tab-bindings'+import { store } from '../store'+import { taskTabFeature } from './task-tab'+import { taskTabRuntime, taskTabSeats } from './task-tab.test.harness'++vi.mock('dsh-tauri/client', async () => ({+ ...await import('../../../../dsh-tauri/src/client/register'),+ ...await import('../../../../dsh-tauri/src/client/modules/valtio-define'),+ ...await import('../../../../dsh-tauri/src/client/locale'),+}))+vi.mock('../components/task-tab', () => ({ TaskTab: () => null }))+vi.mock('../components/task-tab-title', () => ({ TaskTabTitle: () => null }))++const cleanups: Array<() => void> = []++function mount(host: ReturnType<typeof taskTabRuntime>) {+ const dispose = taskTabFeature.call(host.context)+ cleanups.push(dispose)+ return dispose+}++async function request(id = 'task-1') {+ store.navigation.request({ id, sessionId: 'owner' })+ await vi.advanceTimersByTimeAsync(0)+}++function expectUnavailable(host: ReturnType<typeof taskTabRuntime>) {+ expect(host.openTab).not.toHaveBeenCalled()+ expect(store.navigation.target).toBeNull()+ expect(store.navigation.error).toBe('This core has no task sidebar. Update the core to enable it.')+}++function expectClean(host: ReturnType<typeof taskTabRuntime>) {+ expect(host.activeSeats.size).toBe(0)+ expect(host.definitions.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ expect(host.serviceInjections.size).toBe(0)+ expect(host.mounted.listeners.size).toBe(0)+ expect(host.panelInfo.listeners.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+}++beforeEach(() => {+ vi.useFakeTimers()+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ store.navigation.$patch({ target: null, seq: 0, error: '' })+})++afterEach(() => {+ cleanups.splice(0).reverse().forEach(dispose => dispose())+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+})++describe('taskTabFeature public definition and registration', () => {+ it('registers a keep-mounted scheduleTask definition and exact keyed body and title contributions', () => {+ const host = taskTabRuntime()+ const translate = vi.spyOn(locale, 'text')+ mount(host)++ expect(host.registry.register).toHaveBeenCalledTimes(1)+ const definition = host.registry.register.mock.calls[0]![0]+ expect(definition).toEqual({+ id: 'dsh-tauri-scheduler/task',+ kind: 'scheduleTask',+ priority: 'extension',+ keepMounted: true,+ title: expect.any(Function),+ })+ expect(definition.title()).toBe('Edit scheduled task')+ expect(translate).toHaveBeenCalledExactlyOnceWith('editDialogTitle')+ expect(host.slots.inject.mock.calls.map(([name]) => name)).toEqual([+ 'sidebar.right.pane.tab',+ 'sidebar.right.pane.tab.title',+ ])+ expect(host.slots.register.mock.calls.map(([entry, component]) => [entry.name, entry.key, component])).toEqual([+ ['sidebar.right.pane.tab', 'dsh-tauri-scheduler/task', TaskTab],+ ['sidebar.right.pane.tab.title', 'dsh-tauri-scheduler/task', TaskTabTitle],+ ])+ const body = host.activeSeats.get('sidebar.right.pane.tab:dsh-tauri-scheduler/task')!.entry.inject()+ const title = host.activeSeats.get('sidebar.right.pane.tab.title:dsh-tauri-scheduler/task')!.entry.inject()+ expect(body.t).toBe(locale.text)+ expect(title.t).toBe(locale.text)+ expect(body.taskBindings).toBeInstanceOf(TaskTabBindings)+ expect(title.taskBindings).toBe(body.taskBindings)+ expect(title.openHistorySession).toBe(body.openHistorySession)+ expect(console.warn).not.toHaveBeenCalled()+ })++ it('publishes the new target before the real synchronous sequence subscription handles a request', async () => {+ const host = taskTabRuntime()+ mount(host)+ store.navigation.request({ id: 'first-click', sessionId: 'owner' })+ await vi.advanceTimersByTimeAsync(0)++ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'first-click', sessionId: 'owner' } })+ expect(store.navigation.target).toBeNull()+ expect(store.navigation.error).toBe('')+ })++ it('supersedes a pending first action with exactly the second target rather than reopening the previous request', async () => {+ const host = taskTabRuntime()+ let resolveOpening = () => {}+ const opening = new Promise<void>((resolve) => {+ resolveOpening = resolve+ })+ host.openSession.mockReturnValueOnce(opening)+ mount(host)+ store.navigation.request({ id: 'first-pending', sessionId: 'owner' })+ await vi.advanceTimersByTimeAsync(0)+ expect(host.openTab).not.toHaveBeenCalled()+ store.navigation.request({ id: 'second-click', sessionId: 'owner' })+ await vi.advanceTimersByTimeAsync(0)+ resolveOpening()+ await vi.advanceTimersByTimeAsync(0)++ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'second-click', sessionId: 'owner' } })+ expect(store.navigation.target).toBeNull()+ expect(store.navigation.error).toBe('')+ expect(host.mounted.listeners.size).toBe(0)+ expect(host.panelInfo.listeners.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('opens queued requests only after both ready keyed session seats have registered', async () => {+ const host = taskTabRuntime()+ mount(host)+ await request()++ expect(host.activeSeats.size).toBe(2)+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'task-1', sessionId: 'owner' } })+ expect(store.navigation.target).toBeNull()+ expect(store.navigation.error).toBe('')+ })++ it('owns the definition, both declaration waits, shared bindings, and navigation subscription through idempotent HMR disposal', async () => {+ const host = taskTabRuntime()+ const clear = vi.spyOn(TaskTabBindings.prototype, 'clear')+ const dispose = mount(host)+ dispose()+ dispose()++ expectClean(host)+ expect(host.fiberDisposals).toHaveBeenCalledTimes(1)+ expect(host.definitionDisposals).toHaveBeenCalledExactlyOnceWith('dsh-tauri-scheduler/task')+ expect(host.seatDisposals.mock.calls).toEqual([+ ['sidebar.right.pane.tab.title'],+ ['sidebar.right.pane.tab'],+ ])+ expect(host.injectionDisposals.mock.calls).toEqual([+ ['sidebar.right.pane.tab.title'],+ ['sidebar.right.pane.tab'],+ ])+ expect(clear).toHaveBeenCalledTimes(1)+ await request('after-dispose')+ expect(host.openTab).not.toHaveBeenCalled()+ expect(store.navigation.target).toEqual({ id: 'after-dispose', sessionId: 'owner' })++ const remount = mount(host)+ await vi.advanceTimersByTimeAsync(0)+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'after-dispose', sessionId: 'owner' } })+ expect(host.activeSeats.size).toBe(2)+ expect(host.registry.register).toHaveBeenCalledTimes(2)+ remount()+ expectClean(host)+ })+})++describe('taskTabFeature late public services and capability probes', () => {+ it('waits for both public right-sidebar services and becomes usable when they arrive', async () => {+ const host = taskTabRuntime()+ host.provide('sidebarRight', undefined)+ host.provide('sidebarRightTabs', undefined)+ mount(host)+ expect(host.registry.register).not.toHaveBeenCalled()+ await request('before-services')+ expectUnavailable(host)++ host.provide('sidebarRight', host.sidebar)+ expect(host.registry.register).not.toHaveBeenCalled()+ host.provide('sidebarRightTabs', host.registry)+ expect(host.activeSeats.size).toBe(2)+ await request('after-services')+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'after-services', sessionId: 'owner' } })+ expect(store.navigation.error).toBe('')+ })++ it('unloads and reinstalls contributions when a required service disappears and returns', async () => {+ const host = taskTabRuntime()+ mount(host)+ host.provide('sidebarRightTabs', undefined)+ expect(host.activeSeats.size).toBe(0)+ expect(host.definitions.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ await request('while-unloaded')+ expectUnavailable(host)++ host.provide('sidebarRightTabs', host.registry)+ await request('after-reload')+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'after-reload', sessionId: 'owner' } })+ expect(host.registry.register).toHaveBeenCalledTimes(2)+ })++ it('cancels a deferred service injection so arrival after plugin disposal cannot register or navigate', async () => {+ const host = taskTabRuntime()+ host.provide('sidebarRight', undefined)+ const dispose = mount(host)+ dispose()+ host.provide('sidebarRight', host.sidebar)+ await request('after-late-arrival')++ expectClean(host)+ expect(host.registry.register).not.toHaveBeenCalled()+ expect(host.slots.inject).not.toHaveBeenCalled()+ expect(host.openTab).not.toHaveBeenCalled()+ expect(store.navigation.target).toEqual({ id: 'after-late-arrival', sessionId: 'owner' })+ })++ it.each([+ 'sidebar openTab',+ 'mounted subscribe',+ 'mounted snapshot',+ 'tab definition register',+ 'slot spec',+ 'slot inject',+ 'slot register',+ 'layout',+ ] as const)('warns and fails closed when the public %s capability is missing', async (missing) => {+ const host = taskTabRuntime()+ switch (missing) {+ case 'sidebar openTab':+ host.provide('sidebarRight', { mounted: host.mounted })+ break+ case 'mounted subscribe':+ host.provide('sidebarRight', { openTab: host.openTab, mounted: { getSnapshot: host.mounted.getSnapshot } })+ break+ case 'mounted snapshot':+ host.provide('sidebarRight', { openTab: host.openTab, mounted: { subscribe: host.mounted.subscribe } })+ break+ case 'tab definition register':+ host.provide('sidebarRightTabs', {})+ break+ case 'slot spec':+ host.provide('slots', { inject: host.slots.inject, register: host.slots.register })+ break+ case 'slot inject':+ host.provide('slots', { spec: host.slots.spec, register: host.slots.register })+ break+ case 'slot register':+ host.provide('slots', { spec: host.slots.spec, inject: host.slots.inject })+ break+ case 'layout':+ host.provide('layout', undefined)+ break+ }+ expect(() => mount(host)).not.toThrow()+ await request()++ expect(host.registry.register).not.toHaveBeenCalled()+ expect(host.slots.register).not.toHaveBeenCalled()+ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar capability unavailable; task tabs disabled.')+ })++ it('fails closed and clears bindings when the public definition registry rejects installation', async () => {+ const host = taskTabRuntime()+ const error = new Error('definition rejected')+ const clear = vi.spyOn(TaskTabBindings.prototype, 'clear')+ host.registry.register.mockImplementationOnce(() => {+ throw error+ })+ expect(() => mount(host)).not.toThrow()+ await request()++ expect(host.definitions.size).toBe(0)+ expect(host.activeSeats.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ expect(host.slots.inject).not.toHaveBeenCalled()+ expect(host.definitionDisposals).not.toHaveBeenCalled()+ expect(clear).toHaveBeenCalledTimes(1)+ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar registration failed.', error)+ })++ it.each(['body', 'title'] as const)('rolls back the definition and prior contributions when the %s declaration wait itself throws', async (seat) => {+ const host = taskTabRuntime()+ const error = new Error(`${seat} declaration wait rejected`)+ const inject = host.slots.inject.getMockImplementation()!+ const clear = vi.spyOn(TaskTabBindings.prototype, 'clear')+ if (seat === 'title')+ host.slots.inject.mockImplementationOnce(inject)+ host.slots.inject.mockImplementationOnce(() => {+ throw error+ })+ expect(() => mount(host)).not.toThrow()+ await request()++ expect(host.definitions.size).toBe(0)+ expect(host.activeSeats.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ expect(host.definitionDisposals).toHaveBeenCalledExactlyOnceWith('dsh-tauri-scheduler/task')+ expect(host.seatDisposals.mock.calls).toEqual(seat === 'title' ? [['sidebar.right.pane.tab']] : [])+ expect(host.injectionDisposals.mock.calls).toEqual(seat === 'title' ? [['sidebar.right.pane.tab']] : [])+ expect(clear).toHaveBeenCalledTimes(1)+ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar registration failed.', error)+ })++ it('rolls back partial installation when the body registration throws synchronously', async () => {+ const host = taskTabRuntime()+ const error = new Error('body contribution rejected')+ host.failRegistration('sidebar.right.pane.tab', error)+ const clear = vi.spyOn(TaskTabBindings.prototype, 'clear')+ expect(() => mount(host)).not.toThrow()+ await request()++ expect(host.definitions.size).toBe(0)+ expect(host.activeSeats.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ expect(host.definitionDisposals).toHaveBeenCalledExactlyOnceWith('dsh-tauri-scheduler/task')+ expect(clear).toHaveBeenCalledTimes(1)+ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar registration failed.', error)+ })++ it('rolls back the already registered body and definition when the title contribution throws', async () => {+ const host = taskTabRuntime()+ const error = new Error('title contribution rejected')+ host.failRegistration('sidebar.right.pane.tab.title', error)+ mount(host)+ await request()++ expect(host.definitions.size).toBe(0)+ expect(host.activeSeats.size).toBe(0)+ expect(host.seatInjections.size).toBe(0)+ expect(host.seatDisposals).toHaveBeenCalledExactlyOnceWith('sidebar.right.pane.tab')+ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar registration failed.', error)+ })+})++describe('taskTabFeature requires both public seats before navigation', () => {+ it('does not open a blank task tab while both seats are undeclared', async () => {+ const host = taskTabRuntime({})+ const dispose = mount(host)+ expect(host.definitions.size).toBe(1)+ expect(host.slots.inject.mock.calls.map(([name]) => name)).toEqual([+ 'sidebar.right.pane.tab',+ 'sidebar.right.pane.tab.title',+ ])+ expect(host.activeSeats.size).toBe(0)+ await request()+ expectUnavailable(host)+ dispose()+ expectClean(host)+ })++ it.each(['sidebar.right.pane.tab', 'sidebar.right.pane.tab.title'])('does not open a blank task tab when only %s has been declared', async (readySeat) => {+ const host = taskTabRuntime({ [readySeat]: { kind: 'keyed', scope: 'session' } })+ mount(host)+ expect(host.activeSeats.size).toBe(1)+ await request()+ expectUnavailable(host)+ })++ it('becomes navigable only after the second late declaration and clears the previous unavailable feedback', async () => {+ const host = taskTabRuntime({})+ mount(host)+ await request('neither-ready')+ expectUnavailable(host)+ host.declare('sidebar.right.pane.tab')+ await request('only-body-ready')+ expectUnavailable(host)+ host.declare('sidebar.right.pane.tab.title')+ await request('both-ready')++ expect(host.activeSeats.size).toBe(2)+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'both-ready', sessionId: 'owner' } })+ expect(store.navigation.error).toBe('')+ })++ it.each([+ { name: 'sidebar.right.pane.tab', spec: { kind: 'list', scope: 'session' } },+ { name: 'sidebar.right.pane.tab', spec: { kind: 'keyed', scope: 'root' } },+ { name: 'sidebar.right.pane.tab.title', spec: { kind: 'list', scope: 'session' } },+ { name: 'sidebar.right.pane.tab.title', spec: { kind: 'keyed', scope: 'root' } },+ ] satisfies { name: string, spec: TaskTabSeatSpec }[])('warns without navigating for an incompatible $name $spec.kind/$spec.scope declaration', async ({ name, spec }) => {+ const host = taskTabRuntime({ ...taskTabSeats, [name]: spec })+ mount(host)+ expect(host.activeSeats.size).toBe(1)+ await request()++ expectUnavailable(host)+ expect(console.warn).toHaveBeenCalledWith('[scheduler task tab] Public right-sidebar capability unavailable; task tabs disabled.')+ })++ it.each(['sidebar.right.pane.tab', 'sidebar.right.pane.tab.title'])('loses readiness when %s collapses and recovers without duplicating contributions', async (name) => {+ const host = taskTabRuntime()+ mount(host)+ host.collapse(name)+ expect(host.activeSeats.size).toBe(1)+ await request('collapsed')+ expectUnavailable(host)+ host.declare(name)+ await request('redeclared')++ expect(host.activeSeats.size).toBe(2)+ expect(host.openTab).toHaveBeenCalledExactlyOnceWith('scheduleTask', { params: { id: 'redeclared', sessionId: 'owner' } })+ expect(host.seatDisposals).toHaveBeenCalledWith(name)+ })++ it.each([+ { failed: 'sidebar.right.pane.tab', ready: 'sidebar.right.pane.tab.title' },+ { failed: 'sidebar.right.pane.tab.title', ready: 'sidebar.right.pane.tab' },+ ])('keeps navigation disabled when the late compatible $failed contribution fails to register', async ({ failed, ready }) => {+ const host = taskTabRuntime({ [ready]: { kind: 'keyed', scope: 'session' } })+ const error = new Error('late contribution rejected')+ host.failRegistration(failed, error)+ const dispose = mount(host)+ host.declare(failed)+ expect(host.activeSeats.size).toBe(1)+ expect(host.declarationFailures).toEqual([error])+ await request()++ expectUnavailable(host)+ dispose()+ expectClean(host)+ })++ it('does not register late seats after the feature and its waits have been disposed', async () => {+ const host = taskTabRuntime({})+ const dispose = mount(host)+ dispose()+ host.declare('sidebar.right.pane.tab')+ host.declare('sidebar.right.pane.tab.title')+ await request('disposed')++ expectClean(host)+ expect(host.slots.register).not.toHaveBeenCalled()+ expect(host.openTab).not.toHaveBeenCalled()+ })+})++describe('taskTabFeature aborts lifecycle-owned navigation when its rendering capabilities unload', () => {+ it.each(['sidebar.right.pane.tab', 'sidebar.right.pane.tab.title'])('aborts pending navigation when %s collapses and cannot open after mounted publishes', async (name) => {+ const host = taskTabRuntime()+ host.mounted.publish(undefined)+ const dispose = mount(host)+ await request()+ expect(host.mounted.listeners.size).toBe(1)+ host.collapse(name)+ await vi.advanceTimersByTimeAsync(0)++ expect(host.activeSeats.size).toBe(1)+ expect(host.openTab).not.toHaveBeenCalled()+ expect(host.mounted.listeners.size).toBe(0)+ expect(host.panelInfo.listeners.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ host.mounted.publish('owner' as NonNullable<ReturnType<typeof host.mounted.getSnapshot>>)+ await vi.advanceTimersByTimeAsync(0)+ expect(host.openTab).not.toHaveBeenCalled()+ dispose()+ expectClean(host)+ })++ it('aborts an already pending navigation before unloading its body and title contributions', async () => {+ const host = taskTabRuntime()+ host.mounted.publish(undefined)+ mount(host)+ await request()+ expect(host.mounted.listeners.size).toBe(1)+ host.provide('sidebarRight', undefined)+ await vi.advanceTimersByTimeAsync(0)++ expect(host.openTab).not.toHaveBeenCalled()+ expect(host.activeSeats.size).toBe(0)+ expect(host.mounted.listeners.size).toBe(0)+ expect(host.panelInfo.listeners.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('does not leave a request alive after full plugin disposal', async () => {+ const host = taskTabRuntime()+ host.mounted.publish(undefined)+ const dispose = mount(host)+ await request()+ dispose()+ await vi.advanceTimersByTimeAsync(0)++ expectClean(host)+ host.mounted.publish('owner' as NonNullable<ReturnType<typeof host.mounted.getSnapshot>>)+ await vi.advanceTimersByTimeAsync(0)+ expect(host.openTab).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/register/task-tab.tsx b/packages/dsh-tauri-scheduler/src/client/register/task-tab.tsxnew file mode 100644index 00000000..34c95e08--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/register/task-tab.tsx@@ -0,0 +1,147 @@+import type { ClientContext, ILayout, SessionListState, WorkspaceSnapshot } from 'dsh-tauri/client'+import type { SidebarRight, SidebarRightTabs } from '../types/task-tab'+import { defineAdapter, defineRegister } from 'dsh-tauri/client'+import { sessionLinkState } from '../components/session-link'+import { TaskTab } from '../components/task-tab'+import { TaskTabTitle } from '../components/task-tab-title'+import { SCHEDULE_TASK_ID, SCHEDULE_TASK_KIND } from '../constants'+import { locale } from '../locales'+import { TaskTabBindings } from '../service/task-tab-bindings'+import { store } from '../store'+import { liveTaskTabIds, openTaskTab } from './task-tab.navigation'++export const taskTabFeature = defineRegister<ClientContext>((controller, ctx, adapter) => {+ let installed = false+ let pending: AbortController | undefined+ const warn = () => console.warn('[scheduler task tab] Public right-sidebar capability unavailable; task tabs disabled.')+ const fiber = ctx.inject(['sidebarRight', 'sidebarRightTabs'], (scoped) => {+ const current = defineAdapter(scoped)+ const sidebar = current.service<SidebarRight>('sidebarRight')+ const registry = current.service<SidebarRightTabs>('sidebarRightTabs')+ const slots = current.service<ClientContext['slots']>('slots')+ const layout = current.service<ILayout>('layout')+ if (!sidebar || typeof sidebar.openTab !== 'function' || typeof sidebar.mounted?.subscribe !== 'function' || typeof sidebar.mounted.getSnapshot !== 'function'+ || typeof registry?.register !== 'function' || typeof slots?.spec !== 'function' || typeof slots.inject !== 'function' || typeof slots.register !== 'function' || !layout) {+ warn()+ return+ }+ const taskBindings = new TaskTabBindings(id => liveTaskTabIds(sidebar, id))+ const openHistorySession = async (id: string): Promise<{ ok: boolean, error?: string }> => {+ const state = sessionLinkState(id, ctx.sessions.list.getSnapshot(), ctx.workspaces.list.getSnapshot())+ if (state !== 'available')+ return { ok: false, error: locale.text(`session.${state}`) }+ try {+ const result = current.openSession(id)+ if (result.status !== 'opened')+ return { ok: false, error: locale.text('openRunFailed') }+ await result.value+ store.scheduler.markSessionRead(id)+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: error instanceof Error ? error.message : String(error) }+ }+ }+ const injected = () => ({ t: locale.text, taskBindings, openHistorySession })+ const disposers: Array<() => void> = []+ let complete = false+ let bodyReady = false+ let titleReady = false+ function updateReadiness(): void {+ installed = complete && bodyReady && titleReady+ if (!installed)+ pending?.abort()+ }+ try {+ disposers.push(registry.register({ id: SCHEDULE_TASK_ID, kind: SCHEDULE_TASK_KIND, priority: 'extension', keepMounted: true, title: () => locale.text('editDialogTitle') }))+ disposers.push(slots.inject('sidebar.right.pane.tab', () => {+ const spec = slots.spec('sidebar.right.pane.tab')+ if (spec?.kind !== 'keyed' || spec.scope !== 'session') {+ warn()+ return () => {}+ }+ const dispose = slots.register({ name: 'sidebar.right.pane.tab', key: SCHEDULE_TASK_ID, inject: injected }, TaskTab)+ bodyReady = true+ updateReadiness()+ return () => {+ bodyReady = false+ updateReadiness()+ dispose()+ }+ }))+ disposers.push(slots.inject('sidebar.right.pane.tab.title', () => {+ const spec = slots.spec('sidebar.right.pane.tab.title')+ if (spec?.kind !== 'keyed' || spec.scope !== 'session') {+ warn()+ return () => {}+ }+ const dispose = slots.register({ name: 'sidebar.right.pane.tab.title', key: SCHEDULE_TASK_ID, inject: injected }, TaskTabTitle)+ titleReady = true+ updateReadiness()+ return () => {+ titleReady = false+ updateReadiness()+ dispose()+ }+ }))+ complete = true+ updateReadiness()+ }+ catch (error) {+ complete = false+ updateReadiness()+ disposers.reverse().forEach(dispose => dispose())+ taskBindings.clear()+ console.warn('[scheduler task tab] Public right-sidebar registration failed.', error)+ return+ }+ return () => {+ complete = false+ updateReadiness()+ disposers.reverse().forEach(dispose => dispose())+ taskBindings.clear()+ }+ })+ controller.add(() => {+ pending?.abort()+ void fiber.dispose()+ })+ const navigate = () => {+ const { target, seq } = store.navigation+ if (!target)+ return+ pending?.abort()+ if (!installed) {+ warn()+ store.navigation.finish(seq, locale.text('navigation.unavailable'))+ return+ }+ const sidebar = adapter.service<SidebarRight>('sidebarRight')+ const layout = adapter.service<ILayout>('layout')+ if (!sidebar || !layout) {+ store.navigation.finish(seq, locale.text('navigation.unavailable'))+ return+ }+ pending = new AbortController()+ const request = pending+ void openTaskTab({+ controller,+ adapter,+ sidebar,+ layout,+ target,+ signal: request.signal,+ t: locale.text,+ sessions: () => ctx.sessions.list.getSnapshot() as SessionListState,+ workspaces: () => ctx.workspaces.list.getSnapshot() as WorkspaceSnapshot,+ }).then(() => {+ if (!controller.isDisposed() && !request.signal.aborted)+ store.navigation.finish(seq)+ }).catch((error: unknown) => {+ if (!controller.isDisposed() && !request.signal.aborted)+ store.navigation.finish(seq, error instanceof Error ? error.message : String(error))+ })+ }+ controller.add(store.navigation.$subscribeKey('seq', navigate))+ navigate()+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/deletion.test.ts b/packages/dsh-tauri-scheduler/src/client/service/deletion.test.tsnew file mode 100644index 00000000..2a58656a--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/deletion.test.ts@@ -0,0 +1,103 @@+import type { TaskView } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { store } from '../store'+import { cancelTaskDeletion, confirmTaskDeletion, dismissDeletionFeedback, requestTaskDeletion } from './deletion'+import { deleteTask } from './scheduler'++vi.mock('dsh-tauri/client', async () => await import('../../../../dsh-tauri/src/client/modules/valtio-define'))+vi.mock('./scheduler', () => ({ deleteTask: vi.fn() }))++function task(id: string): TaskView {+ return {+ id,+ name: `Task ${id}`,+ prompt: 'Report',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'owner',+ enabled: true,+ schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' },+ createdAt: '2026-10-10T00:00:00Z',+ updatedAt: '2026-10-10T00:00:00Z',+ }+}++beforeEach(() => {+ store.deletion.$patch({ pendingTask: null, deletingTaskId: null, feedback: null, feedbackSeq: 0 })+ vi.mocked(deleteTask).mockReset()+})++afterEach(() => {+ vi.restoreAllMocks()+})++describe('global deletion lifecycle', () => {+ it('does not delete until confirmed and cancellation clears only the pending task', async () => {+ requestTaskDeletion(task('a'))+ expect(store.deletion.pendingTask?.id).toBe('a')+ expect(deleteTask).not.toHaveBeenCalled()+ cancelTaskDeletion()+ expect(store.deletion.pendingTask).toBeNull()+ await confirmTaskDeletion()+ expect(deleteTask).not.toHaveBeenCalled()+ })++ it('serializes confirmation, prevents replacement while busy, and preserves final feedback globally', async () => {+ let resolve!: (value: { ok: boolean }) => void+ vi.mocked(deleteTask).mockReturnValueOnce(new Promise(done => resolve = done))+ requestTaskDeletion(task('a'))+ const confirmation = confirmTaskDeletion()+ expect(store.deletion.deletingTaskId).toBe('a')+ cancelTaskDeletion()+ requestTaskDeletion(task('b'))+ await confirmTaskDeletion()+ expect(store.deletion.pendingTask?.id).toBe('a')+ expect(deleteTask).toHaveBeenCalledExactlyOnceWith('a')+ resolve({ ok: true })+ await confirmation+ expect(store.deletion.pendingTask).toBeNull()+ expect(store.deletion.deletingTaskId).toBeNull()+ expect(store.deletion.feedback).toEqual({ seq: 1, kind: 'deleted', taskId: 'a', name: 'Task a' })+ requestTaskDeletion(task('b'))+ cancelTaskDeletion()+ expect(store.deletion.feedback?.taskId).toBe('a')+ })++ it.each([+ { outcome: { ok: false, error: 'server refused' }, expected: 'server refused' },+ { outcome: new Error('network broke'), expected: 'network broke' },+ { outcome: 'transport failure', expected: 'transport failure' },+ ])('settles API failures and thrown values as global feedback %#', async ({ outcome, expected }) => {+ if (typeof outcome === 'object' && !(outcome instanceof Error))+ vi.mocked(deleteTask).mockResolvedValueOnce(outcome)+ else+ vi.mocked(deleteTask).mockRejectedValueOnce(outcome)+ requestTaskDeletion(task('a'))+ await expect(confirmTaskDeletion()).resolves.toBeUndefined()+ expect(store.deletion.deletingTaskId).toBeNull()+ expect(store.deletion.pendingTask).toBeNull()+ expect(store.deletion.feedback).toEqual({ seq: 1, kind: 'deleteFailed', taskId: 'a', name: 'Task a', error: expected })+ })++ it('does not let an old banner dismissal clear a newer deletion result', async () => {+ vi.mocked(deleteTask).mockResolvedValue({ ok: true })+ requestTaskDeletion(task('a'))+ await confirmTaskDeletion()+ requestTaskDeletion(task('b'))+ await confirmTaskDeletion()+ dismissDeletionFeedback(1)+ expect(store.deletion.feedback).toEqual({ seq: 2, kind: 'deleted', taskId: 'b', name: 'Task b' })+ dismissDeletionFeedback(2)+ expect(store.deletion.feedback).toBeNull()+ })++ it('ignores an out-of-order store completion not owned by the in-flight request', () => {+ requestTaskDeletion(task('a'))+ store.deletion.begin()+ store.deletion.finish(task('b'), { ok: true })+ expect(store.deletion.deletingTaskId).toBe('a')+ expect(store.deletion.feedback).toBeNull()+ store.deletion.finish(task('a'), { ok: false })+ expect(store.deletion.feedback).toEqual({ seq: 1, kind: 'deleteFailed', taskId: 'a', name: 'Task a' })+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/deletion.ts b/packages/dsh-tauri-scheduler/src/client/service/deletion.tsnew file mode 100644index 00000000..10977ec9--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/deletion.ts@@ -0,0 +1,28 @@+import type { TaskView } from '../types'+import { store } from '../store'+import { deleteTask } from './scheduler'++export function requestTaskDeletion(task: TaskView): void {+ store.deletion.request(task)+}++export function cancelTaskDeletion(): void {+ store.deletion.cancel()+}++export function dismissDeletionFeedback(seq?: number): void {+ store.deletion.dismiss(seq)+}++export async function confirmTaskDeletion(): Promise<void> {+ const task = store.deletion.begin()+ if (task === null)+ return+ try {+ const outcome = await deleteTask(task.id)+ store.deletion.finish(task, outcome)+ }+ catch (error) {+ store.deletion.finish(task, { ok: false, error: error instanceof Error ? error.message : String(error) })+ }+}diff --git a/packages/dsh-tauri-scheduler/src/client/service/schedule-created.test.ts b/packages/dsh-tauri-scheduler/src/client/service/schedule-created.test.tsnew file mode 100644index 00000000..4ad8392f--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/schedule-created.test.ts@@ -0,0 +1,100 @@+import type { TaskView } from '../types'+import { describe, expect, it } from 'vitest'+import { decodeCreatedTask } from './schedule-created'++function task(schedule: TaskView['schedule'] = { kind: 'daily', time: '09:00', timeZone: 'UTC' }): TaskView {+ return {+ id: 'created-task',+ name: 'Morning report',+ prompt: 'Summarize the overnight changes',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'owner',+ enabled: true,+ schedule,+ createdAt: '2026-10-10T00:00:00Z',+ updatedAt: '2026-10-10T00:00:00Z',+ nextRunAt: '2026-10-11T09:00:00Z',+ }+}++function content(value: unknown) {+ return [{ type: 'text', text: JSON.stringify(value) }]+}++describe('durable scheduler_create payload', () => {+ it.each<TaskView['schedule']>([+ { kind: 'once', at: '2026-10-11T09:00:00Z', timeZone: 'UTC' },+ { kind: 'hourly', minute: 15, timeZone: 'UTC' },+ { kind: 'daily', time: '09:00', timeZone: 'UTC' },+ { kind: 'workdays', time: '09:00', timeZone: 'UTC' },+ { kind: 'weekly', time: '09:00', weekdays: ['MO', 'FR'], timeZone: 'UTC' },+ { kind: 'monthly', time: '09:00', day: 31, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 30, anchor: '2026-10-10T00:00:00Z', timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: 2, anchor: '2026-10-10T00:00:00Z', timeZone: 'Asia/Shanghai' },+ { kind: 'daily', time: ' 8:30 ', timeZone: 'Asia/Shanghai' },+ { kind: 'interval', everyMinutes: 1.5, anchor: '2026-10-10T00:00:00.123Z', timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 525_600, timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: 366, anchor: '2026-10-10T00:00:00Z', timeZone: 'UTC' },+ ])('decodes a complete $kind snapshot without depending on live catalog %#', (schedule) => {+ const snapshot = task(schedule)+ expect(decodeCreatedTask(content({ ok: true, taskId: snapshot.id, nextRunAt: snapshot.nextRunAt, task: snapshot }))).toEqual(snapshot)+ })++ it.each([+ [],+ [{ type: 'text', text: '' }],+ [{ type: 'text', text: '{' }],+ [{ type: 'text', text: '已创建任务' }],+ [{ type: 'image', text: '{}' }],+ [{ type: 'text', text: '{}' }, { type: 'text', text: '{}' }],+ content({ ok: false, task: task() }),+ content({ ok: true, taskId: 'wrong', task: task() }),+ content({ ok: true, taskId: 'legacy-id', nextRunAt: '2026-10-11T09:00:00Z' }),+ ].map(result => ({ result })))('ignores incomplete or failed output %#', ({ result }) => {+ expect(decodeCreatedTask(result)).toBeUndefined()+ })++ it.each([+ { id: '' },+ { name: ' ' },+ { prompt: '' },+ { enabled: 'true' },+ { delivery: 'unknown' },+ { status: 'unknown' },+ { sessionId: 7 },+ { createdAt: 'invalid' },+ { updatedAt: 'invalid' },+ { nextRunAt: 'invalid' },+ { workspaceId: 1 },+ { agentPreset: 1 },+ ])('rejects malformed canonical task fields %#', (changes) => {+ expect(decodeCreatedTask(content({ ok: true, task: { ...task(), ...changes } }))).toBeUndefined()+ })++ it.each([+ { kind: 'daily', time: '09:00' },+ { kind: 'daily', time: '09:00', timeZone: '' },+ { kind: 'daily', time: '09:00', timeZone: ' UTC ' },+ { kind: 'daily', time: '09:00', timeZone: 'Unknown/Zone' },+ { kind: 'daily', time: '24:00', timeZone: 'UTC' },+ { kind: 'daily', time: '09:60', timeZone: 'UTC' },+ { kind: 'hourly', minute: 60, timeZone: 'UTC' },+ { kind: 'hourly', minute: 0.5, timeZone: 'UTC' },+ { kind: 'weekly', time: '09:00', weekdays: [], timeZone: 'UTC' },+ { kind: 'weekly', time: '09:00', weekdays: ['BAD'], timeZone: 'UTC' },+ { kind: 'monthly', time: '09:00', day: 32, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 0, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 0.5, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 525_601, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: '1.5', timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 1.5, anchor: 'invalid', timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: 2, timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: -1, anchor: '2026-10-10T00:00:00Z', timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: 367, anchor: '2026-10-10T00:00:00Z', timeZone: 'UTC' },+ { kind: 'custom', time: '09:00', everyDays: 1.5, anchor: '2026-10-10T00:00:00Z', timeZone: 'UTC' },+ { kind: 'once', at: 'invalid', timeZone: 'UTC' },+ ])('rejects malformed canonical schedule fields %#', (schedule) => {+ expect(decodeCreatedTask(content({ ok: true, task: { ...task(), schedule } }))).toBeUndefined()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/schedule-created.ts b/packages/dsh-tauri-scheduler/src/client/service/schedule-created.tsnew file mode 100644index 00000000..3b8f72e6--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/schedule-created.ts@@ -0,0 +1,88 @@+import type { TaskView } from '../types'++function isRecord(value: unknown): value is Record<string, unknown> {+ return value !== null && typeof value === 'object' && !Array.isArray(value)+}++function isTime(value: unknown): value is string {+ return typeof value === 'string' && /^(?:[01]?\d|2[0-3]):[0-5]\d$/.test(value.trim())+}++function isTimeZone(value: unknown): value is string {+ if (typeof value !== 'string' || value === '' || value.trim() !== value)+ return false+ try {+ return new Intl.DateTimeFormat('en-US', { timeZone: value }).resolvedOptions().timeZone !== ''+ }+ catch {+ return false+ }+}++function isPositiveInteger(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0+}++function isTimestamp(value: unknown): value is string {+ return typeof value === 'string' && Number.isFinite(Date.parse(value))+}++function isSchedule(value: unknown): value is TaskView['schedule'] {+ if (!isRecord(value) || !isTimeZone(value.timeZone))+ return false+ switch (value.kind) {+ case 'once':+ return isTimestamp(value.at)+ case 'hourly':+ return typeof value.minute === 'number' && Number.isInteger(value.minute) && value.minute >= 0 && value.minute <= 59+ case 'daily':+ case 'workdays':+ return isTime(value.time)+ case 'weekly':+ return isTime(value.time) && Array.isArray(value.weekdays) && value.weekdays.length > 0+ && value.weekdays.every(day => ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'].includes(day))+ case 'monthly':+ return isTime(value.time) && isPositiveInteger(value.day) && value.day <= 31+ case 'interval':+ return typeof value.everyMinutes === 'number' && Number.isFinite(value.everyMinutes)+ && value.everyMinutes >= 1 && value.everyMinutes < 525_601 && (value.anchor === undefined || isTimestamp(value.anchor))+ case 'custom':+ return isTime(value.time) && isPositiveInteger(value.everyDays) && value.everyDays <= 366 && isTimestamp(value.anchor)+ default:+ return false+ }+}++function isTask(value: unknown): value is TaskView {+ if (!isRecord(value))+ return false+ return typeof value.id === 'string' && value.id.trim() !== ''+ && typeof value.name === 'string' && value.name.trim() !== ''+ && typeof value.prompt === 'string' && value.prompt.trim() !== ''+ && typeof value.enabled === 'boolean'+ && (value.delivery === 'this-session' || value.delivery === 'new-session')+ && (value.status === 'active' || value.status === 'inactive')+ && (value.sessionId === undefined || typeof value.sessionId === 'string')+ && isTimestamp(value.createdAt) && isTimestamp(value.updatedAt)+ && isSchedule(value.schedule)+ && ['recommendationId', 'workspaceId', 'permission', 'provider', 'model', 'reasoningEffort', 'module', 'agentPreset']+ .every(key => value[key] === undefined || typeof value[key] === 'string')+ && ['lastRunAt', 'nextRunAt'].every(key => value[key] === undefined || isTimestamp(value[key]))+ && (value.waiting === undefined || typeof value.waiting === 'boolean')+}++export function decodeCreatedTask(content: readonly { type: string, text?: string }[]): TaskView | undefined {+ if (content.length !== 1 || content[0]?.type !== 'text' || !content[0].text?.trim())+ return undefined+ try {+ const value: unknown = JSON.parse(content[0].text)+ if (!isRecord(value) || value.ok !== true || !isTask(value.task))+ return undefined+ if (value.taskId !== undefined && value.taskId !== value.task.id)+ return undefined+ return value.task+ }+ catch {+ return undefined+ }+}diff --git a/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.test.ts b/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.test.tsnew file mode 100644index 00000000..d7241ed1--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.test.ts@@ -0,0 +1,161 @@+import type { ConversationMatch, ConversationNodeContext, ConversationTurnDataMap, TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client'+import type { SessionEvent } from '@deepseek-ai/dsh-session/types'+import type { TaskView } from '../types'+import type { ScheduleTurnData, ScheduleTurnState } from './schedule-turn'+import { describe, expect, it } from 'vitest'+import { scheduleTasksForClosing, scheduleTurnDefinition, selectScheduleTasks } from './schedule-turn'++function seq(value: number): SessionEvent['seq'] {+ return value as SessionEvent['seq']+}++function task(id = 'task-created'): TaskView {+ return {+ id,+ name: 'Scheduled report',+ prompt: 'Write a report',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'owner',+ enabled: true,+ schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' },+ createdAt: '2026-10-10T00:00:00Z',+ updatedAt: '2026-10-10T00:00:00Z',+ }+}++function start(turn = 3): SessionEvent<'turn/start'> {+ return { type: 'turn/start', seq: seq(1), time: 100, data: { turn } }+}++function call(callId = 'create', name = 'scheduler_create', turn = 3): SessionEvent<'tool/call'> {+ return {+ type: 'tool/call',+ seq: seq(2),+ time: 200,+ data: { turn, step: 1, callId: callId as SessionEvent<'tool/call'>['data']['callId'], name, arguments: '{}' },+ }+}++function result(callId = 'create', at = 4, changes: Partial<SessionEvent<'tool/result'>['data']['message']> = {}, turn = 3): SessionEvent<'tool/result'> {+ return {+ type: 'tool/result',+ seq: seq(at),+ time: 1700000000123 + at,+ surfaceOp: 'append',+ data: {+ turn,+ step: 1,+ message: {+ id: `message-${callId}` as SessionEvent<'tool/result'>['data']['message']['id'],+ role: 'tool',+ source: { kind: 'tool', callId: callId as SessionEvent<'tool/call'>['data']['callId'] },+ toolCallId: callId as SessionEvent<'tool/call'>['data']['callId'],+ content: [{ type: 'text', text: JSON.stringify({ ok: true, taskId: 'task-created', task: task() }) }],+ ...changes,+ },+ },+ }+}++function context(state: ScheduleTurnState): ConversationNodeContext<ScheduleTurnState> & { state: ScheduleTurnState } {+ return { key: 'schedule-created:3', kind: 'schedule-created', id: '3', matches: [], start: undefined, state, current: new Map() }+}++function initialize(): ScheduleTurnState {+ return scheduleTurnDefinition.start(+ { ...context({ turn: 3, calls: new Map(), created: [] }), state: undefined },+ { event: start(), role: 'start', location: { kind: 'unresolved' } },+ { previous: () => undefined },+ )+}++function update(state: ScheduleTurnState, event: SessionEvent): ScheduleTurnState {+ const accepted = scheduleTurnDefinition.match(event)+ if (accepted === null)+ return state+ const match: ConversationMatch = { event, role: accepted.role, location: { kind: 'unresolved' } }+ return scheduleTurnDefinition.update(context(state), match)+}++function owner(data: ScheduleTurnData | undefined, cursor = 5, end?: number) {+ const values: Partial<ConversationTurnDataMap> = { 'schedule-created': data }+ const turn: TurnLocation = {+ turn: 3,+ start: start(),+ end: end === undefined ? undefined : { type: 'turn/end', seq: seq(end), time: 999, data: { turn: 3, reason: { kind: 'completed' } } },+ status: end === undefined ? 'open' : 'closed',+ steps: [],+ data: { get: key => values[key], source: key => ({ getSnapshot: () => values[key], subscribe: () => () => {} }) },+ }+ return { turn, seq: cursor, openFile: () => {} }+}++describe('scheduler_create turn-tail definition', () => {+ it('publishes no tool-call view and accepts only start, call, and appended settled result events', () => {+ expect(scheduleTurnDefinition.kind).toBe('schedule-created')+ expect(scheduleTurnDefinition.target).toBeUndefined()+ expect(scheduleTurnDefinition.match(start())).toEqual({ id: '3', role: 'start' })+ expect(scheduleTurnDefinition.match(call())).toEqual({ id: '3', role: 'update' })+ expect(scheduleTurnDefinition.match(result())).toEqual({ id: '3', role: 'update' })+ expect(scheduleTurnDefinition.match({ ...result(), surfaceOp: { op: 'replace', startSeq: seq(1), endSeq: seq(2) } })).toBeNull()+ expect(scheduleTurnDefinition.match({ type: 'turn/end', seq: seq(5), time: 500, data: { turn: 3, reason: { kind: 'completed' } } })).toBeNull()+ })++ it('pairs calls by source callId and publishes immutable complete creation facts with event time', () => {+ const initial = initialize()+ const called = update(initial, call())+ expect(initial.calls.size).toBe(0)+ expect(initial.created).toEqual([])+ expect(called.calls.get('create')).toEqual({ name: 'scheduler_create' })+ const settled = update(called, result())+ expect(called.created).toEqual([])+ expect(settled.created).toEqual([{ seq: 4, time: 1700000000127, callId: 'create', task: task() }])+ expect(update(settled, result('create', 5))).toBe(settled)+ const secondCalled = update(settled, call('second'))+ const second = update(secondCalled, result('second', 6))+ expect(second.created.map(created => created.callId)).toEqual(['create', 'second'])+ expect(settled.created).toHaveLength(1)+ })++ it('ignores unmatched, different tools, failed, malformed, and wrong-turn results', () => {+ const initial = initialize()+ expect(update(initial, result())).toBe(initial)+ const wrongTool = update(initial, call('create', 'scheduler_update'))+ expect(update(wrongTool, result())).toBe(wrongTool)+ const called = update(initial, call())+ expect(update(called, result('create', 4, { isError: true }))).toBe(called)+ expect(update(called, result('create', 4, { content: [{ type: 'text', text: '{' }] }))).toBe(called)+ expect(update(called, result('create', 4, {}, 4))).toBe(called)+ expect(update(called, call('other', 'scheduler_create', 4))).toBe(called)+ expect(update(called, result('missing-source'))).toBe(called)+ })++ it('publishes only turn data, preserves unchanged identity, and does not require chat tool expansion', () => {+ const settled = update(update(initialize(), call()), result())+ const publish = scheduleTurnDefinition.buildLocationData!+ expect(publish(context(settled), 'step', null)).toBeNull()+ expect(publish({ ...context(settled), state: undefined }, 'turn', null)).toBeNull()+ const data = publish(context(settled), 'turn', null)+ expect(data).toEqual({ kind: 'turn', turn: 3, key: 'schedule-created', value: { created: settled.created } })+ expect(publish(context(settled), 'turn', data)).toBe(data)+ const next = update(update(settled, call('second')), result('second', 8))+ expect(publish(context(next), 'turn', data)).not.toBe(data)+ })++ it('bounds created cards to an open cursor or closed turn end without leaking later creations', () => {+ const data: ScheduleTurnData = {+ created: [+ { seq: 4, time: 1004, callId: 'first', task: task('first-task') },+ { seq: 8, time: 1008, callId: 'second', task: task('second-task') },+ ],+ }+ expect(selectScheduleTasks(owner(undefined))).toBeNull()+ expect(selectScheduleTasks(owner(data, 3))).toBeNull()+ expect(selectScheduleTasks(owner(data, 5))?.created.map(created => created.callId)).toEqual(['first'])+ expect(selectScheduleTasks(owner(data, 100, 5))?.created.map(created => created.callId)).toEqual(['first'])+ expect(selectScheduleTasks(owner(data, 2, 10))?.created.map(created => created.callId)).toEqual(['first', 'second'])+ expect(scheduleTasksForClosing(data).map(created => created.callId)).toEqual(['first', 'second'])+ expect(scheduleTasksForClosing(undefined)).toEqual([])+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.ts b/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.tsnew file mode 100644index 00000000..21c6bf09--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/schedule-turn.ts@@ -0,0 +1,96 @@+import type { ConversationNodeDefinition, TurnLocation } from '@deepseek-ai/dsh-client-ui-conversation/client'+import type { TaskView } from '../types'+import { decodeCreatedTask } from './schedule-created'++export interface ScheduleCreatedTask {+ readonly seq: number+ readonly time: number+ readonly callId: string+ readonly task: TaskView+}++export interface ScheduleTurnData {+ readonly created: readonly ScheduleCreatedTask[]+}++declare module '@deepseek-ai/dsh-client-ui-conversation/client' {+ interface ConversationTurnDataMap {+ 'schedule-created': ScheduleTurnData+ }+}++export interface ScheduleTurnOwner {+ readonly turn: TurnLocation+ readonly seq: number+ readonly openFile: (path: string) => void+}++interface ScheduleCall {+ readonly name: string+}++export interface ScheduleTurnState {+ readonly turn: number+ readonly calls: ReadonlyMap<string, ScheduleCall>+ readonly created: readonly ScheduleCreatedTask[]+}++export function scheduleTasksForClosing(+ data: Readonly<ScheduleTurnData> | undefined,+ seq = Number.POSITIVE_INFINITY,+): readonly ScheduleCreatedTask[] {+ return data === undefined ? [] : data.created.filter(created => created.seq <= seq)+}++export function selectScheduleTasks(owner: ScheduleTurnOwner): ScheduleTurnData | null {+ const created = scheduleTasksForClosing(owner.turn.data.get('schedule-created'), owner.turn.end?.seq ?? owner.seq)+ return created.length === 0 ? null : { created }+}++export const scheduleTurnDefinition: ConversationNodeDefinition<ScheduleTurnState> = {+ kind: 'schedule-created',+ match: (event) => {+ if (event.type === 'turn/start')+ return { id: String(event.data.turn), role: 'start' }+ if (event.type === 'tool/call')+ return { id: String(event.data.turn), role: 'update' }+ if (event.type === 'tool/result' && event.surfaceOp === 'append')+ return { id: String(event.data.turn), role: 'update' }+ return null+ },+ start: (_context, match) => {+ if (match.event.type !== 'turn/start')+ throw new Error('schedule-created start requires turn/start')+ return { turn: match.event.data.turn, calls: new Map(), created: [] }+ },+ update: (context, match) => {+ if (match.event.type === 'tool/call') {+ if (match.event.data.turn !== context.state.turn)+ return context.state+ const calls = new Map(context.state.calls)+ calls.set(String(match.event.data.callId), { name: match.event.data.name })+ return { ...context.state, calls }+ }+ if (match.event.type !== 'tool/result' || match.event.data.turn !== context.state.turn)+ return context.state+ const message = match.event.data.message+ const callId = String(message.source.callId)+ if (context.state.calls.get(callId)?.name !== 'scheduler_create' || message.isError === true)+ return context.state+ if (context.state.created.some(created => created.callId === callId))+ return context.state+ const task = decodeCreatedTask(message.content)+ return task === undefined+ ? context.state+ : { ...context.state, created: [...context.state.created, { seq: match.event.seq, time: match.event.time, callId, task }] }+ },+ buildLocationData: (context, scope, previous) => {+ if (scope !== 'turn' || context.state === undefined)+ return null+ if (previous?.kind === 'turn' && previous.turn === context.state.turn+ && previous.key === 'schedule-created' && previous.value.created === context.state.created) {+ return previous+ }+ return { kind: 'turn', turn: context.state.turn, key: 'schedule-created', value: { created: context.state.created } }+ },+}diff --git a/packages/dsh-tauri-scheduler/src/client/service/scheduler.history-http.test.ts b/packages/dsh-tauri-scheduler/src/client/service/scheduler.history-http.test.tsnew file mode 100644index 00000000..0bcf9298--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/scheduler.history-http.test.ts@@ -0,0 +1,165 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const fetchMock = vi.fn<typeof globalThis.fetch>()+let service: typeof import('./scheduler')+let apis: typeof import('../apis')++function jsonResponse(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })+}++function expectHistoryRequest(index: number, query: Record<string, string>): void {+ const call = fetchMock.mock.calls[index]+ if (!call)+ throw new Error('Expected a scheduler history HTTP request')+ const [input, options] = call+ expect(typeof input).toBe('string')+ if (typeof input !== 'string')+ throw new Error('Expected the generated history API to issue a URL string')+ const request = new URL(input, 'https://scheduler.invalid')+ expect(request.pathname).toBe('/api/tauri/scheduler/history')+ expect(Object.fromEntries(request.searchParams)).toEqual(query)+ expect(options?.method).toBe('GET')+}++beforeEach(async () => {+ vi.resetModules()+ fetchMock.mockReset()+ fetchMock.mockImplementation(async () => {+ throw new Error('Unexpected scheduler HTTP request')+ })+ vi.stubGlobal('fetch', fetchMock)+ service = await import('./scheduler')+ apis = await import('../apis')+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('scheduler history through generated API and the real HTTP client', () => {+ it('decodes a successful empty first page while sending the task identity and explicit limit', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ ok: true,+ records: [],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ }))++ expect(await service.loadTaskHistory('task with /?#', 20)).toEqual({+ ok: true,+ records: [],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task with /?#', limit: '20' })+ })++ it('preserves a successful page receipt, exclusive next cursor and retention flags after JSON decoding', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ ok: true,+ records: [{+ id: 'receipt-older',+ taskId: 'task-http',+ taskName: 'Original reminder',+ delivery: 'this-session',+ occurrence: '2030-01-01T12:00:00.000Z',+ trigger: 'schedule',+ sessionId: 'session-owner',+ scheduledAt: '2030-01-01T12:00:00.000Z',+ deliveredAt: '2030-01-01T12:00:01.000Z',+ messageId: 'message-delivered',+ prompt: 'Immutable reminder instruction',+ }],+ runs: [],+ nextBefore: 'receipt-older',+ earlierRecordsUnavailable: true,+ earlierRecordsPruned: true,+ retention: { days: 30, records: 200 },+ }))++ expect(await service.loadTaskHistory('task-http', 20, 'receipt-newer')).toEqual({+ ok: true,+ records: [{+ id: 'receipt-older',+ taskId: 'task-http',+ taskName: 'Original reminder',+ delivery: 'this-session',+ occurrence: '2030-01-01T12:00:00.000Z',+ trigger: 'schedule',+ sessionId: 'session-owner',+ scheduledAt: '2030-01-01T12:00:00.000Z',+ deliveredAt: '2030-01-01T12:00:01.000Z',+ messageId: 'message-delivered',+ prompt: 'Immutable reminder instruction',+ }],+ runs: [],+ nextBefore: 'receipt-older',+ earlierRecordsUnavailable: true,+ earlierRecordsPruned: true,+ retention: { days: 30, records: 200 },+ })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task-http', limit: '20', before: 'receipt-newer' })+ })++ it('preserves the official cursor code and domain message from an actual HTTP 400 response', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ ok: false,+ error: '历史游标不存在或已被清理',+ code: 'delivery_cursor_not_found',+ }, 400))++ const pending = service.loadTaskHistory('task-http', 20, 'receipt-pruned')+ await expect(pending).rejects.toBeInstanceOf(Error)+ await expect(pending).rejects.toMatchObject({+ message: '历史游标不存在或已被清理',+ code: 'delivery_cursor_not_found',+ })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task-http', limit: '20', before: 'receipt-pruned' })+ })++ it.each([+ { limit: 0, before: undefined, message: 'limit 必须是 1 到 100 的整数', code: 'history_invalid_limit' },+ { limit: 20, before: '', message: '历史查询参数无效', code: 'history_invalid_query' },+ ])('preserves the non-cursor HTTP 400 domain failure $code without inventing a cursor recovery', async ({ limit, before, message, code }) => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ ok: false, error: message, code }, 400))++ const pending = service.loadTaskHistory('task-http', limit, before)+ await expect(pending).rejects.toBeInstanceOf(Error)+ await expect(pending).rejects.toMatchObject({ message, code })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task-http', limit: String(limit), ...(before === undefined ? {} : { before }) })+ })++ it('does not change the shared HTTP client default error normalization for a direct generated request', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({+ ok: false,+ error: '历史游标不存在或已被清理',+ code: 'delivery_cursor_not_found',+ }, 400))++ const pending = apis.getHistory({ taskId: 'task-http', limit: 20, before: 'receipt-pruned' })+ await expect(pending).rejects.toMatchObject({ message: '请求失败 (400): 历史游标不存在或已被清理' })+ await expect(pending).rejects.not.toHaveProperty('code')+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task-http', limit: '20', before: 'receipt-pruned' })+ })++ it('keeps a transport rejection as an error without fabricating a cursor code or retrying', async () => {+ fetchMock.mockRejectedValueOnce(new Error('socket closed'))++ const pending = service.loadTaskHistory('task-http', 20, 'receipt-newer')+ await expect(pending).rejects.toThrowError('socket closed')+ await expect(pending).rejects.not.toHaveProperty('code')+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expectHistoryRequest(0, { taskId: 'task-http', limit: '20', before: 'receipt-newer' })+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/scheduler.test.ts b/packages/dsh-tauri-scheduler/src/client/service/scheduler.test.tsindex 5bb5421f..55b8a293 100644--- a/packages/dsh-tauri-scheduler/src/client/service/scheduler.test.ts+++ b/packages/dsh-tauri-scheduler/src/client/service/scheduler.test.ts@@ -1,32 +1,207 @@-import type { TaskInput } from '../types'-import { afterEach, expect, it, vi } from 'vitest'-import { postTasks, putTasks } from '../apis'-import { createTask, updateTask } from './scheduler'+import type { HistoryPage, TaskInput, TaskView } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { deleteHistory, deleteTasks, getHistory, getOptions, getTasks, postRunsRecover, postTasks, postTasksRun, postTasksToggle, putTasks } from '../apis'+import { store } from '../store'+import { createTask, deleteRun, deleteTask, loadOptions, loadScheduler, loadTaskHistory, recoverScheduler, runTask, toggleTask, updateTask } from './scheduler'+vi.mock('dsh-tauri/client', async () => await import('../../../../dsh-tauri/src/client/modules/valtio-define'))vi.mock('../apis', () => ({+ deleteHistory: vi.fn(),+ deleteTasks: vi.fn(),+ getHistory: vi.fn(),+ getOptions: vi.fn(),+ getTasks: vi.fn(),+ postRunsRecover: vi.fn(),postTasks: vi.fn(),+ postTasksRun: vi.fn(),+ postTasksToggle: vi.fn(),putTasks: vi.fn(),- getTasks: vi.fn(async () => ({ tasks: [] })),- getHistory: vi.fn(async () => ({ runs: [] })),-}))-vi.mock('../store', () => ({- store: { scheduler: { loadToken: 0, $patch: vi.fn(), seedReadAt: vi.fn() } },}))+const task = {+ id: 'task-a',+ name: 'Weekly',+ prompt: 'Original instruction',+ delivery: 'new-session',+ status: 'active',+ schedule: { kind: 'weekly', weekdays: ['MO', 'FR'], time: '09:00', timeZone: 'Asia/Shanghai' },+ enabled: true,+ createdAt: '2030-01-01T00:00:00.000Z',+ updatedAt: '2030-01-01T00:00:00.000Z',+} satisfies TaskView+const page: HistoryPage = {+ records: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+}+const options: Awaited<ReturnType<typeof getOptions>> = {+ workspaces: [],+ permissions: [],+ models: [],+ failures: [],+ defaultPermission: 'read-only',+ defaultModel: null,+}++function deferred<T>(): { promise: Promise<T>, resolve: (value: T) => void } {+ let resolve!: (value: T) => void+ const promise = new Promise<T>(done => resolve = done)+ return { promise, resolve }+}++beforeEach(() => {+ vi.resetAllMocks()+ store.scheduler.$patch({ tasks: [], runs: [], loading: false, error: '', refreshedAt: 0, loadToken: 0, successfulReadToken: 0, readAt: 0, readIds: [], options })+ vi.mocked(getTasks).mockResolvedValue({ tasks: [task] })+ vi.mocked(getHistory).mockResolvedValue({ ok: true, ...page, runs: [] })+ vi.mocked(getOptions).mockResolvedValue(options)+})+afterEach(() => {- vi.clearAllMocks()+ vi.restoreAllMocks()})-it('serializes readonly weekly weekdays for create and update without mutating the form', async () => {- const weekdays = Object.freeze(['MO', 'FR'] as const)- const input: TaskInput = { name: 'Weekly', prompt: 'run', schedule: { kind: 'weekly', weekdays, time: '09:00' } }- vi.mocked(postTasks).mockResolvedValue({ ok: true })- vi.mocked(putTasks).mockResolvedValue({ ok: true })- expect(await createTask(input)).toEqual({ ok: true })- expect(await updateTask('task', input)).toEqual({ ok: true })- expect(postTasks).toHaveBeenCalledExactlyOnceWith(input)- expect(putTasks).toHaveBeenCalledExactlyOnceWith({ id: 'task', ...input })- expect(vi.mocked(postTasks).mock.calls[0]![0].schedule).not.toBe(input.schedule)- expect(vi.mocked(putTasks).mock.calls[0]![0].schedule).not.toBe(input.schedule)- expect(input.schedule).toEqual({ kind: 'weekly', weekdays: ['MO', 'FR'], time: '09:00' })+describe('scheduler catalog reads', () => {+ it('requests an explicit history limit and commits the successful post-request read token', async () => {+ await loadScheduler(true)+ expect(getTasks).toHaveBeenCalledExactlyOnceWith()+ expect(getHistory).toHaveBeenCalledExactlyOnceWith({ limit: 100 })+ expect(getOptions).toHaveBeenCalledExactlyOnceWith()+ expect(store.scheduler.tasks).toEqual([task])+ expect(store.scheduler.$state).toMatchObject({ loading: false, error: '', loadToken: 1, successfulReadToken: 1 })+ expect(store.scheduler.readAt).toBeGreaterThan(0)+ })++ it('does not let an older task response overwrite a newer catalog or successful read token', async () => {+ const first = deferred<Awaited<ReturnType<typeof getTasks>>>()+ vi.mocked(getTasks).mockReturnValueOnce(first.promise)+ const pending = loadScheduler(true)+ await loadScheduler()+ first.resolve({ tasks: [{ ...task, name: 'Stale name' }] })+ await pending+ expect(store.scheduler.tasks).toEqual([task])+ expect(store.scheduler.$state).toMatchObject({ loadToken: 2, successfulReadToken: 2, loading: false })+ expect(getOptions).not.toHaveBeenCalled()+ })++ it('does not accept a failed or stale read as evidence that an existing task is deleted', async () => {+ await loadScheduler()+ vi.mocked(getHistory).mockResolvedValueOnce({ ok: false, error: 'History read failed', code: 'history_failed' })+ await loadScheduler()+ expect(store.scheduler.tasks).toEqual([task])+ expect(store.scheduler.$state).toMatchObject({ loadToken: 2, successfulReadToken: 1, loading: false, error: 'History read failed' })+ })++ it('ignores a failed older request after a newer request has succeeded', async () => {+ const first = deferred<Awaited<ReturnType<typeof getHistory>>>()+ vi.mocked(getHistory).mockReturnValueOnce(first.promise)+ const pending = loadScheduler()+ await loadScheduler()+ first.resolve({ ok: false, error: 'Stale failure' })+ await pending+ expect(store.scheduler.$state).toMatchObject({ tasks: [task], successfulReadToken: 2, loading: false, error: '' })+ })++ it('reports transport failure without clearing the last catalog', async () => {+ await loadScheduler()+ vi.mocked(getTasks).mockRejectedValueOnce(new Error('Connection lost'))+ await loadScheduler()+ expect(store.scheduler.$state).toMatchObject({ tasks: [task], successfulReadToken: 1, loading: false, error: 'Connection lost' })+ })++ it('loads resource options without requesting task or history data', async () => {+ await loadOptions()+ expect(getOptions).toHaveBeenCalledExactlyOnceWith()+ expect(getTasks).not.toHaveBeenCalled()+ expect(getHistory).not.toHaveBeenCalled()+ expect(store.scheduler.options).toEqual(options)+ })+})++describe('task-specific delivery history', () => {+ it('passes task identity, explicit page limit and exclusive cursor unchanged', async () => {+ const result = await loadTaskHistory('task-a', 20, 'message-z')+ expect(getHistory).toHaveBeenCalledExactlyOnceWith({ taskId: 'task-a', limit: 20, before: 'message-z' }, { ignoreResponseError: true })+ expect(result).toEqual({ ok: true, ...page, runs: [] })+ expect(store.scheduler.loadToken).toBe(0)+ })++ it('preserves the official cursor failure code for the history component to recover', async () => {+ vi.mocked(getHistory).mockResolvedValueOnce({ ok: false, error: 'Cursor expired', code: 'delivery_cursor_not_found' })+ await expect(loadTaskHistory('task-a', 20, 'expired')).rejects.toMatchObject({ message: 'Cursor expired', code: 'delivery_cursor_not_found' })+ })+})++describe('scheduler mutations', () => {+ it('serializes readonly weekly weekdays without changing the input or the expected record', async () => {+ const weekdays = Object.freeze(['MO', 'FR'] as const)+ const input: TaskInput = { delivery: 'new-session', name: 'Weekly', prompt: 'Updated instruction', schedule: { kind: 'weekly', weekdays, time: '09:00', timeZone: 'Asia/Shanghai' } }+ vi.mocked(postTasks).mockResolvedValueOnce({ ok: true, task })+ vi.mocked(putTasks).mockResolvedValueOnce({ ok: true, task })+ expect(await createTask(input)).toEqual({ ok: true, task })+ expect(await updateTask('task-a', input, task)).toEqual({ ok: true, task })+ expect(postTasks).toHaveBeenCalledExactlyOnceWith(input)+ expect(putTasks).toHaveBeenCalledExactlyOnceWith({ id: 'task-a', ...input, expected: task })+ expect(vi.mocked(postTasks).mock.calls[0]![0].schedule).not.toBe(input.schedule)+ expect(vi.mocked(putTasks).mock.calls[0]![0].schedule).not.toBe(input.schedule)+ expect(input.schedule).toEqual({ kind: 'weekly', weekdays: ['MO', 'FR'], time: '09:00', timeZone: 'Asia/Shanghai' })+ expect(task.prompt).toBe('Original instruction')+ })++ it('keeps an optimistic-concurrency rejection as a visible error and does not refresh away the draft', async () => {+ const input: TaskInput = { delivery: 'new-session', name: 'Weekly', prompt: 'My draft', schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' } }+ vi.mocked(putTasks).mockResolvedValueOnce({ ok: false, error: 'Task changed', code: 'task_conflict' })+ expect(await updateTask('task-a', input, task)).toEqual({ ok: false, error: 'Task changed' })+ expect(getTasks).not.toHaveBeenCalled()+ expect(input.prompt).toBe('My draft')+ expect(vi.mocked(putTasks).mock.calls[0]![0].expected).toEqual(task)+ })++ it('returns create transport failures instead of rejecting the form save', async () => {+ vi.mocked(postTasks).mockRejectedValueOnce(new Error('Offline'))+ const input: TaskInput = { delivery: 'this-session', sessionId: 'owner', name: 'Reminder', prompt: 'Report', schedule: { kind: 'hourly', minute: 15 } }+ expect(await createTask(input)).toEqual({ ok: false, error: 'Offline' })+ expect(getTasks).not.toHaveBeenCalled()+ })++ it.each([+ { api: postTasksToggle, action: () => toggleTask('task-a', false), body: { id: 'task-a', enabled: false } },+ { api: deleteTasks, action: () => deleteTask('task-a'), body: { id: 'task-a' } },+ { api: postTasksRun, action: () => runTask('task-a'), body: { id: 'task-a' } },+ { api: deleteHistory, action: () => deleteRun('run-a'), body: { id: 'run-a' } },+ ])('refreshes the shared catalog only after the mutation succeeds %#', async ({ api, action, body }) => {+ vi.mocked(api).mockResolvedValueOnce({ ok: true })+ expect(await action()).toEqual({ ok: true })+ expect(api).toHaveBeenCalledExactlyOnceWith(body)+ expect(getTasks).toHaveBeenCalledExactlyOnceWith()+ expect(getHistory).toHaveBeenCalledExactlyOnceWith({ limit: 100 })+ })++ it.each([+ { api: postTasksToggle, action: () => toggleTask('task-a', true) },+ { api: deleteTasks, action: () => deleteTask('task-a') },+ { api: postTasksRun, action: () => runTask('task-a') },+ { api: deleteHistory, action: () => deleteRun('run-a') },+ ])('does not refresh after a rejected or unreachable mutation %#', async ({ api, action }) => {+ vi.mocked(api).mockResolvedValueOnce({ ok: false, error: 'Rejected' })+ expect(await action()).toEqual({ ok: false, error: 'Rejected' })+ vi.mocked(api).mockRejectedValueOnce(new Error('Network error'))+ expect(await action()).toEqual({ ok: false, error: 'Network error' })+ expect(getTasks).not.toHaveBeenCalled()+ })++ it('refreshes task, history and resource options after crash recovery', async () => {+ vi.mocked(postRunsRecover).mockResolvedValueOnce({ ok: true })+ expect(await recoverScheduler()).toEqual({ ok: true })+ expect(postRunsRecover).toHaveBeenCalledExactlyOnceWith()+ expect(getTasks).toHaveBeenCalledExactlyOnceWith()+ expect(getOptions).toHaveBeenCalledExactlyOnceWith()+ })++ it('reports a rejected recovery without requesting task data', async () => {+ vi.mocked(postRunsRecover).mockResolvedValueOnce({ ok: false, error: 'Recovery refused' })+ expect(await recoverScheduler()).toEqual({ ok: false, error: 'Recovery refused' })+ expect(getTasks).not.toHaveBeenCalled()+ })})diff --git a/packages/dsh-tauri-scheduler/src/client/service/scheduler.ts b/packages/dsh-tauri-scheduler/src/client/service/scheduler.tsindex 0c06e426..5b7600c0 100644--- a/packages/dsh-tauri-scheduler/src/client/service/scheduler.ts+++ b/packages/dsh-tauri-scheduler/src/client/service/scheduler.ts@@ -1,104 +1,132 @@-import type { TaskInput } from '../types'-import {- deleteHistory,- deleteTasks,- getHistory,- getOptions,- getTasks,- postRunsRecover,- postTasks,- postTasksRun,- postTasksToggle,- putTasks,-} from '../apis'+import type { HistoryPage, TaskInput, TaskView } from '../types'+import { deleteHistory, deleteTasks, getHistory, getOptions, getTasks, postRunsRecover, postTasks, postTasksRun, postTasksToggle, putTasks } from '../apis'import { store } from '../store'export async function loadScheduler(withOptions = false): Promise<void> {const token = store.scheduler.loadToken + 1store.scheduler.$patch({ loadToken: token, loading: true, error: '' })try {- const [tasks, runs] = await Promise.all([getTasks(), getHistory()])+ const [tasks, history] = await Promise.all([getTasks(), getHistory({ limit: 100 })])if (token !== store.scheduler.loadToken)return- store.scheduler.$patch({ tasks: tasks.tasks, runs: runs.runs, loading: false, refreshedAt: Date.now() })+ if (!history.ok)+ throw new Error(history.error)+ store.scheduler.$patch({ tasks: tasks.tasks, runs: history.runs, loading: false, refreshedAt: Date.now(), successfulReadToken: token })store.scheduler.seedReadAt()- if (!withOptions)- return- const options = await getOptions()- if (token !== store.scheduler.loadToken)- return- store.scheduler.$patch({ options })+ if (withOptions)+ await loadOptions()}catch (error) {- if (token !== store.scheduler.loadToken)- return- store.scheduler.$patch({ loading: false, error: messageOf(error) })+ if (token === store.scheduler.loadToken)+ store.scheduler.$patch({ loading: false, error: messageOf(error) })}}+export async function loadOptions(): Promise<void> {+ store.scheduler.$patch({ options: await getOptions() })+}++export async function loadTaskHistory(taskId: string, limit: number, before?: string): Promise<HistoryPage> {+ const result = await getHistory({ taskId, limit, before }, { ignoreResponseError: true })+ if (!result.ok)+ throw Object.assign(new Error(result.error), { code: result.code })+ return result+}+export async function recoverScheduler(): Promise<{ ok: boolean, error?: string }> {try {- await postRunsRecover()+ const result = await postRunsRecover()+ if ('ok' in result && !result.ok)+ return { ok: false, error: 'error' in result ? String(result.error) : 'Recovery failed' }+ await loadScheduler(true)+ return { ok: true }}catch (error) {return { ok: false, error: messageOf(error) }}- await loadScheduler(true)- return { ok: true }}-export async function createTask(input: TaskInput): Promise<{ ok: boolean, error?: string }> {- const schedule = input.schedule.kind === 'weekly' ? { ...input.schedule, weekdays: [...input.schedule.weekdays] } : input.schedule- const result = await postTasks({ ...input, schedule })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+export async function createTask(input: TaskInput): Promise<{ ok: boolean, error?: string, task?: TaskView }> {+ try {+ const schedule = input.schedule.kind === 'weekly' ? { ...input.schedule, weekdays: [...input.schedule.weekdays] } : input.schedule+ const result = await postTasks({ ...input, schedule })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true, task: result.task }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}-export async function updateTask(id: string, input: TaskInput): Promise<{ ok: boolean, error?: string }> {- const schedule = input.schedule.kind === 'weekly' ? { ...input.schedule, weekdays: [...input.schedule.weekdays] } : input.schedule- const result = await putTasks({ id, ...input, schedule })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+export async function updateTask(id: string, input: TaskInput, expected: TaskView): Promise<{ ok: boolean, error?: string, task?: TaskView }> {+ try {+ const schedule = input.schedule.kind === 'weekly' ? { ...input.schedule, weekdays: [...input.schedule.weekdays] } : input.schedule+ const expectedSchedule = expected.schedule.kind === 'weekly' ? { ...expected.schedule, weekdays: [...expected.schedule.weekdays] } : expected.schedule+ const result = await putTasks({ id, ...input, schedule, expected: { ...expected, schedule: expectedSchedule } })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true, task: result.task }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}export async function toggleTask(id: string, enabled: boolean): Promise<{ ok: boolean, error?: string }> {- const result = await postTasksToggle({ id, enabled })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+ try {+ const result = await postTasksToggle({ id, enabled })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}export async function deleteTask(id: string): Promise<{ ok: boolean, error?: string }> {- const result = await deleteTasks({ id })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+ try {+ const result = await deleteTasks({ id })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}export async function runTask(id: string): Promise<{ ok: boolean, error?: string }> {- const result = await postTasksRun({ id })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+ try {+ const result = await postTasksRun({ id })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}export async function deleteRun(id: string): Promise<{ ok: boolean, error?: string }> {- const result = await deleteHistory({ id })- if (!result.ok)- return { ok: false, error: result.error }- await loadScheduler()- return { ok: true }+ try {+ const result = await deleteHistory({ id })+ if (!result.ok)+ return { ok: false, error: result.error }+ await loadScheduler()+ return { ok: true }+ }+ catch (error) {+ return { ok: false, error: messageOf(error) }+ }}-// --- internal ----function messageOf(error: unknown): string {return error instanceof Error ? error.message : String(error)}diff --git a/packages/dsh-tauri-scheduler/src/client/service/session-schedule.test.ts b/packages/dsh-tauri-scheduler/src/client/service/session-schedule.test.tsnew file mode 100644index 00000000..1d463d48--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/session-schedule.test.ts@@ -0,0 +1,62 @@+import type { TaskView } from '../types'+import { describe, expect, it } from 'vitest'+import { activeSessionTasks, isTaskOverdue, orderSessionTasks } from './session-schedule'++function task(id: string, changes: Partial<TaskView> = {}): TaskView {+ return {+ id,+ name: id,+ prompt: 'Reminder',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'owner',+ enabled: true,+ schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' },+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-01T00:00:00Z',+ ...changes,+ }+}++describe('shared session catalog projection', () => {+ it('keeps only enabled active this-session tasks bound to the seat owner', () => {+ const tasks = [+ task('match'),+ task('other-owner', { sessionId: 'elsewhere' }),+ task('unbound', { sessionId: undefined }),+ task('new-session', { delivery: 'new-session' }),+ task('inactive', { status: 'inactive' }),+ task('disabled', { enabled: false }),+ ]+ expect(activeSessionTasks(tasks, 'owner').map(value => value.id)).toEqual(['match'])+ expect(activeSessionTasks(tasks, 'elsewhere').map(value => value.id)).toEqual(['other-owner'])+ expect(activeSessionTasks(tasks, undefined)).toEqual([])+ expect(activeSessionTasks(tasks, '')).toEqual([])+ })++ it('orders overdue first, then nearest next run, with stable missing deadlines and no mutation', () => {+ const now = Date.parse('2026-10-10T09:00:00Z')+ const tasks = Object.freeze([+ task('later', { nextRunAt: '2026-10-10T10:00:00Z' }),+ task('missing'),+ task('overdue-near', { nextRunAt: '2026-10-10T08:59:00Z' }),+ task('overdue-old', { nextRunAt: '2026-10-09T09:00:00Z' }),+ task('due', { nextRunAt: '2026-10-10T09:00:00Z' }),+ task('invalid', { nextRunAt: 'invalid' }),+ task('soon', { nextRunAt: '2026-10-10T09:05:00Z' }),+ ])+ expect(orderSessionTasks(tasks, now).map(value => value.id)).toEqual([+ 'overdue-old',+ 'overdue-near',+ 'due',+ 'soon',+ 'later',+ 'missing',+ 'invalid',+ ])+ expect(tasks.map(value => value.id)).toEqual(['later', 'missing', 'overdue-near', 'overdue-old', 'due', 'invalid', 'soon'])+ expect(isTaskOverdue(task('due', { nextRunAt: '2026-10-10T09:00:00Z' }), now)).toBe(true)+ expect(isTaskOverdue(task('missing'), now)).toBe(false)+ expect(isTaskOverdue(task('invalid', { nextRunAt: 'invalid' }), now)).toBe(false)+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/session-schedule.ts b/packages/dsh-tauri-scheduler/src/client/service/session-schedule.tsnew file mode 100644index 00000000..2b92e69b--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/session-schedule.ts@@ -0,0 +1,27 @@+import type { TaskView } from '../types'++export function activeSessionTasks(tasks: readonly TaskView[], sessionId: string | undefined): readonly TaskView[] {+ if (!sessionId)+ return []+ return tasks.filter(task => task.delivery === 'this-session' && task.sessionId === sessionId+ && task.status === 'active' && task.enabled)+}++export function isTaskOverdue(task: TaskView, now: number): boolean {+ return task.nextRunAt !== undefined && Date.parse(task.nextRunAt) <= now+}++export function orderSessionTasks(tasks: readonly TaskView[], now: number): readonly TaskView[] {+ const deadline = (task: TaskView) => {+ const at = task.nextRunAt === undefined ? Number.NaN : Date.parse(task.nextRunAt)+ return Number.isFinite(at) ? at : Number.POSITIVE_INFINITY+ }+ return [...tasks].sort((left, right) => {+ const overdue = Number(isTaskOverdue(right, now)) - Number(isTaskOverdue(left, now))+ if (overdue !== 0)+ return overdue+ const leftAt = deadline(left)+ const rightAt = deadline(right)+ return leftAt === rightAt ? 0 : leftAt < rightAt ? -1 : 1+ })+}diff --git a/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.test.ts b/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.test.tsnew file mode 100644index 00000000..4f02ca85--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.test.ts@@ -0,0 +1,410 @@+import type { TaskFormState } from '../types'+import type { TaskTabPage } from '../types/task-tab'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { TaskTabBindings, taskTabParams } from './task-tab-bindings'++const PAGE: TaskTabPage = { id: 'page-1', kind: 'scheduleTask', contentId: 'task-content' }+const OTHER_PAGE: TaskTabPage = { id: 'page-2', kind: 'scheduleTask', contentId: 'other-content' }+const KEY = 'dsh.schedule.task-tab.v1.owner'++function storage() {+ const values = new Map<string, string>()+ return {+ values,+ getItem: vi.fn((key: string) => values.get(key) ?? null),+ setItem: vi.fn((key: string, value: string) => { values.set(key, value) }),+ removeItem: vi.fn((key: string) => { values.delete(key) }),+ }+}++function form(): TaskFormState {+ return {+ delivery: 'this-session',+ sessionId: 'linked',+ enabled: true,+ name: 'Private draft title',+ prompt: 'Private draft prompt',+ schedule: { kind: 'daily', time: '08:00', timeZone: 'UTC' },+ workspaceId: '',+ permission: '',+ provider: '',+ model: '',+ reasoningEffort: '',+ }+}++let persisted: ReturnType<typeof storage>++beforeEach(() => {+ persisted = storage()+ vi.stubGlobal('localStorage', persisted)+})++afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+})++describe('taskTabBindings identity persistence', () => {+ it('restores only identity after reload rather than a task snapshot', () => {+ const bindings = new TaskTabBindings()+ const target = { id: 'task-1', sessionId: 'linked', name: 'Private title', prompt: 'Private prompt', enabled: false }+ bindings.write('owner', PAGE, target)++ expect(JSON.parse(persisted.values.get(KEY)!)).toEqual({+ 'page-1': { kind: 'scheduleTask', contentId: 'task-content', id: 'task-1', sessionId: 'linked' },+ })+ expect(new TaskTabBindings().read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: 'linked' })+ expect(persisted.values.get(KEY)).not.toContain('Private')+ expect(persisted.values.get(KEY)).not.toContain('enabled')+ })++ it('isolates page identity by owning session and page id', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('other-owner', PAGE, { id: 'task-2', sessionId: 'other-link' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-3' })++ const reloaded = new TaskTabBindings()+ expect(reloaded.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(reloaded.read('other-owner', PAGE)).toEqual({ id: 'task-2', sessionId: 'other-link' })+ expect(reloaded.read('owner', OTHER_PAGE)).toEqual({ id: 'task-3', sessionId: undefined })+ expect(reloaded.read('missing-owner', PAGE)).toBeUndefined()+ expect(reloaded.read('owner', { ...PAGE, id: 'missing-page' })).toBeUndefined()+ })++ it('does not persist draft contents or their initial form', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { draft: true, sessionId: 'linked', initial: form() })++ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()+ expect(persisted.values.size).toBe(0)+ expect(persisted.setItem).not.toHaveBeenCalled()+ })++ it('ignores a draft write without replacing the existing durable identity', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ const original = persisted.values.get(KEY)+ bindings.write('owner', PAGE, { draft: true, initial: form() })++ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(persisted.values.get(KEY)).toBe(original)+ expect(persisted.setItem).toHaveBeenCalledTimes(1)+ })++ it('returns a fresh identity value so caller mutation cannot alter the cached binding', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1', sessionId: 'linked' })+ const returned = bindings.read('owner', PAGE)!+ if (!returned.draft)+ returned.id = 'mutated'+ returned.sessionId = 'mutated'++ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: 'linked' })+ })++ it('clears only in-memory cache, preserving stored identities for a new registration', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ persisted.values.set(KEY, JSON.stringify({+ 'page-1': { kind: 'scheduleTask', contentId: 'task-content', id: 'task-2' },+ }))+ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })++ bindings.clear()+ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-2', sessionId: undefined })+ expect(persisted.removeItem).not.toHaveBeenCalled()+ })++ it.each([+ { name: 'kind', replacement: { ...PAGE, kind: 'other-kind' } },+ { name: 'content id', replacement: { ...PAGE, contentId: 'other-content' } },+ ])('rejects and drops a reused page whose $name changed', ({ replacement }) => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })+ expect(bindings.read('owner', replacement)).toBeUndefined()++ bindings.dropMismatched('owner', replacement)+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()+ expect(bindings.read('owner', OTHER_PAGE)).toEqual({ id: 'task-2', sessionId: undefined })+ })++ it('keeps a matching page and does not write when dropping an absent page', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.dropMismatched('owner', PAGE)+ bindings.dropMismatched('owner', OTHER_PAGE)++ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(persisted.setItem).toHaveBeenCalledTimes(1)+ })++ it('forgets only the selected page and removes the storage document when empty', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })+ bindings.forget('owner', PAGE)+ expect(new TaskTabBindings().read('owner', OTHER_PAGE)).toEqual({ id: 'task-2', sessionId: undefined })+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()++ bindings.forget('owner', OTHER_PAGE)+ expect(persisted.values.has(KEY)).toBe(false)+ expect(persisted.removeItem).toHaveBeenCalledExactlyOnceWith(KEY)+ })+})++describe('taskTabBindings public live-tab pruning', () => {+ it('prunes stale pages only when a nonempty live-tab list is available', () => {+ let live: readonly string[] | undefined+ const liveTabIds = vi.fn((_sessionId: string) => live)+ const bindings = new TaskTabBindings(liveTabIds)+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })+ live = ['page-2']+ bindings.write('owner', OTHER_PAGE, { id: 'task-2-updated' })++ expect(liveTabIds).toHaveBeenLastCalledWith('owner')+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()+ expect(new TaskTabBindings().read('owner', OTHER_PAGE)).toEqual({ id: 'task-2-updated', sessionId: undefined })+ expect(Object.keys(JSON.parse(persisted.values.get(KEY)!))).toEqual(['page-2'])+ })++ it.each([undefined, []])('does not erase restored identities while live tabs are unknown or empty (%j)', (live) => {+ const bindings = new TaskTabBindings(() => live)+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })++ const reloaded = new TaskTabBindings()+ expect(reloaded.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(reloaded.read('owner', OTHER_PAGE)).toEqual({ id: 'task-2', sessionId: undefined })+ })++ it('also prunes stale siblings when forgetting an unrelated page', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })+ const reloaded = new TaskTabBindings(() => ['page-2'])+ reloaded.forget('owner', { ...PAGE, id: 'absent' })++ expect(reloaded.read('owner', PAGE)).toBeUndefined()+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()+ expect(reloaded.read('owner', OTHER_PAGE)).toEqual({ id: 'task-2', sessionId: undefined })+ })+})++describe('taskTabBindings unavailable or malformed storage', () => {+ it('works in memory without localStorage and clears that transient state on disposal', () => {+ vi.stubGlobal('localStorage', undefined)+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()++ bindings.clear()+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ bindings.write('owner', PAGE, { id: 'task-2' })+ bindings.forget('owner', PAGE)+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ })++ it('retains new bindings in memory when reading storage throws', () => {+ persisted.getItem.mockImplementation(() => {+ throw new Error('storage blocked')+ })+ const bindings = new TaskTabBindings()+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ bindings.write('owner', PAGE, { id: 'task-1' })++ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(persisted.values.has(KEY)).toBe(true)+ })++ it('retains memory state and reports a quota failure rather than throwing', () => {+ const error = new Error('quota exceeded')+ const report = vi.spyOn(console, 'error').mockImplementation(() => {})+ persisted.setItem.mockImplementation(() => {+ throw error+ })+ const bindings = new TaskTabBindings()+ expect(() => bindings.write('owner', PAGE, { id: 'task-1' })).not.toThrow()++ expect(bindings.read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ expect(report).toHaveBeenCalledExactlyOnceWith('Task tab binding persistence failed:', error)+ expect(new TaskTabBindings().read('owner', PAGE)).toBeUndefined()+ })++ it('forgets in memory even when removing the storage document throws', () => {+ const bindings = new TaskTabBindings()+ bindings.write('owner', PAGE, { id: 'task-1' })+ const error = new Error('storage remove blocked')+ const report = vi.spyOn(console, 'error').mockImplementation(() => {})+ persisted.removeItem.mockImplementation(() => {+ throw error+ })++ expect(() => bindings.forget('owner', PAGE)).not.toThrow()+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(report).toHaveBeenCalledExactlyOnceWith('Task tab binding persistence failed:', error)+ })++ it.each(['{', 'null', '[]', '1', '"text"', 'false'])('ignores a malformed storage document (%s)', (raw) => {+ persisted.values.set(KEY, raw)+ const bindings = new TaskTabBindings()+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(persisted.values.get(KEY)).toBe(raw)++ bindings.write('owner', PAGE, { id: 'task-1' })+ expect(new TaskTabBindings().read('owner', PAGE)).toEqual({ id: 'task-1', sessionId: undefined })+ })++ it.each([+ null,+ 'text',+ { kind: 1, contentId: 'task-content', id: 'task-1' },+ { kind: 'scheduleTask', contentId: 1, id: 'task-1' },+ { kind: 'scheduleTask', contentId: 'task-content', id: 1 },+ { kind: 'scheduleTask', contentId: 'task-content', id: 'task-1', sessionId: null },+ { kind: 'scheduleTask', contentId: 'task-content', id: '' },+ { kind: 'scheduleTask', contentId: 'task-content', id: ' ' },+ { kind: 'scheduleTask', contentId: 'task-content', id: 'task-1', sessionId: '' },+ { kind: 'scheduleTask', contentId: 'task-content', id: 'task-1', sessionId: ' ' },+ ])('drops a malformed stored entry but preserves its valid sibling (%j)', (bad) => {+ persisted.values.set(KEY, JSON.stringify({+ 'page-1': bad,+ 'page-2': { kind: 'scheduleTask', contentId: 'other-content', id: 'task-2', prompt: 'not identity' },+ }))+ const bindings = new TaskTabBindings()+ expect(bindings.read('owner', PAGE)).toBeUndefined()+ expect(bindings.read('owner', OTHER_PAGE)).toEqual({ id: 'task-2', sessionId: undefined })++ bindings.write('owner', OTHER_PAGE, { id: 'task-2' })+ expect(JSON.parse(persisted.values.get(KEY)!)).toEqual({+ 'page-2': { kind: 'scheduleTask', contentId: 'other-content', id: 'task-2' },+ })+ })+})++describe('taskTabParams', () => {+ it('projects an existing task navigation down to identity only', () => {+ expect(taskTabParams({ id: 'task-1', sessionId: 'linked', name: 'Private', prompt: 'Private', initial: form() }))+ .toEqual({ id: 'task-1', sessionId: 'linked' })+ expect(taskTabParams({ id: 'task-1', draft: false })).toEqual({ id: 'task-1', sessionId: undefined })+ })++ it('accepts a draft with no initial form or a structurally valid editable form', () => {+ expect(taskTabParams({ draft: true })).toEqual({ draft: true, sessionId: undefined, initial: undefined })+ const initial = form()+ expect(taskTabParams({ draft: true, sessionId: 'linked', initial })).toEqual({ draft: true, sessionId: 'linked', initial })+ })++ it('preserves optional recommendation identity and editable schedule options in a valid draft', () => {+ const initial: TaskFormState = {+ ...form(),+ recommendationId: 'recommendation-1',+ schedule: { kind: 'custom', everyDays: 2, time: '', anchor: '', timeZone: '' },+ }+ expect(taskTabParams({ draft: true, initial })).toEqual({ draft: true, sessionId: undefined, initial })+ })++ it('preserves nonblank identity exactly without trimming it into another identity', () => {+ expect(taskTabParams({ id: ' task-1 ', sessionId: ' linked ' })).toEqual({ id: ' task-1 ', sessionId: ' linked ' })+ })++ it('does not restore an existing id when the explicit navigation requests a draft', () => {+ expect(taskTabParams({ draft: true, id: 'old-task' })).toEqual({ draft: true, sessionId: undefined, initial: undefined })+ })++ it.each([+ undefined,+ null,+ false,+ 1,+ 'task-1',+ [],+ {},+ { id: 1 },+ { draft: 'true' },+ { id: 'task-1', sessionId: 1 },+ { draft: true, sessionId: null },+ ])('rejects invalid explicit navigation (%j)', (value) => {+ expect(taskTabParams(value)).toBeUndefined()+ })++ it.each([+ { id: '' },+ { id: ' ' },+ { id: 'task-1', sessionId: '' },+ { id: 'task-1', sessionId: ' ' },+ { id: 'task-1', draft: 'true' },+ { id: 'task-1', draft: null },+ { id: 'task-1', draft: 1 },+ { draft: true, sessionId: '' },+ { draft: true, sessionId: ' ' },+ ])('rejects empty identity or an invalid navigation discriminant (%j)', (value) => {+ expect(taskTabParams(value)).toBeUndefined()+ })++ it.each([+ undefined,+ null,+ 1,+ [],+ {},+ { ...form(), enabled: 'true' },+ { ...form(), delivery: 'other' },+ { ...form(), prompt: 1 },+ { ...form(), schedule: null },+ { ...form(), recommendationId: 1 },+ { ...form(), recommendationId: null },+ ])('opens an empty draft rather than accepting malformed initial form (%j)', (initial) => {+ expect(taskTabParams({ draft: true, sessionId: 'linked', initial })).toEqual({+ draft: true,+ sessionId: 'linked',+ initial: undefined,+ })+ })++ it.each([+ { kind: 'unknown' },+ { kind: 1 },+ { kind: 'once', at: 1 },+ { kind: 'hourly', minute: '0' },+ { kind: 'daily', time: 800 },+ { kind: 'interval', everyMinutes: '15' },+ { kind: 'interval', everyMinutes: 15, anchor: 1 },+ { kind: 'workdays', time: undefined },+ { kind: 'weekly', weekdays: 'MO', time: '08:00' },+ { kind: 'weekly', weekdays: [1], time: '08:00' },+ { kind: 'weekly', weekdays: ['XX'], time: '08:00' },+ { kind: 'monthly', day: '31', time: '08:00' },+ { kind: 'custom', everyDays: '2', time: '08:00' },+ { kind: 'custom', everyDays: 2, time: '08:00', anchor: 1 },+ { kind: 'daily', time: '08:00', timeZone: 1 },+ ])('rejects malformed schedule structure without discarding the draft entry (%j)', (schedule) => {+ expect(taskTabParams({ draft: true, initial: { ...form(), schedule } })).toEqual({+ draft: true,+ sessionId: undefined,+ initial: undefined,+ })+ })++ it.each([+ { kind: 'once', at: '' },+ { kind: 'hourly', minute: 0 },+ { kind: 'daily', time: '' },+ { kind: 'interval', everyMinutes: 15 },+ { kind: 'workdays', time: '08:00' },+ { kind: 'weekly', weekdays: [], time: '08:00' },+ { kind: 'monthly', day: 31, time: '08:00' },+ { kind: 'custom', everyDays: 2, time: '08:00' },+ ] satisfies TaskFormState['schedule'][])('keeps structurally editable $kind draft fields without validating business values', (schedule) => {+ const initial = { ...form(), schedule }+ expect(taskTabParams({ draft: true, initial })).toEqual({ draft: true, sessionId: undefined, initial })+ })+})diff --git a/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.ts b/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.tsnew file mode 100644index 00000000..7d0e7e03--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/service/task-tab-bindings.ts@@ -0,0 +1,142 @@+import type { ScheduleForm, TaskFormState } from '../types'+import type { TaskTabNavigation, TaskTabPage } from '../types/task-tab'+import { WEEKDAYS } from '../../shared/constants'++interface StoredEntry {+ kind: string+ contentId: string+ id: string+ sessionId?: string+}++const PREFIX = 'dsh.schedule.task-tab.v1.'++function entriesOf(raw: string | null): Map<string, StoredEntry> {+ try {+ const parsed: unknown = JSON.parse(raw ?? '{}')+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))+ return new Map()+ return new Map(Object.entries(parsed).flatMap(([key, value]) => {+ if (!value || typeof value !== 'object')+ return []+ const entry = value as Record<string, unknown>+ if (typeof entry.kind !== 'string' || typeof entry.contentId !== 'string' || typeof entry.id !== 'string' || !entry.id.trim())+ return []+ if (entry.sessionId !== undefined && (typeof entry.sessionId !== 'string' || !entry.sessionId.trim()))+ return []+ return [[key, { kind: entry.kind, contentId: entry.contentId, id: entry.id, sessionId: entry.sessionId } as StoredEntry]]+ }))+ }+ catch {+ return new Map()+ }+}++export class TaskTabBindings {+ private readonly memory = new Map<string, Map<string, StoredEntry>>()++ constructor(private readonly liveTabIds?: (sessionId: string) => readonly string[] | undefined) {}++ read(sessionId: string, page: TaskTabPage): TaskTabNavigation | undefined {+ const entry = this.document(sessionId).get(page.id)+ return entry?.kind === page.kind && entry.contentId === page.contentId+ ? { id: entry.id, sessionId: entry.sessionId }+ : undefined+ }++ write(sessionId: string, page: TaskTabPage, target: TaskTabNavigation): void {+ if (target.draft)+ return+ const entries = new Map(this.document(sessionId))+ entries.set(page.id, { kind: page.kind, contentId: page.contentId, id: target.id, sessionId: target.sessionId })+ this.store(sessionId, entries)+ }++ forget(sessionId: string, page: TaskTabPage): void {+ const entries = new Map(this.document(sessionId))+ entries.delete(page.id)+ this.store(sessionId, entries)+ }++ dropMismatched(sessionId: string, page: TaskTabPage): void {+ const entry = this.document(sessionId).get(page.id)+ if (entry && (entry.kind !== page.kind || entry.contentId !== page.contentId))+ this.forget(sessionId, page)+ }++ clear(): void {+ this.memory.clear()+ }++ private document(sessionId: string): Map<string, StoredEntry> {+ const cached = this.memory.get(sessionId)+ if (cached)+ return cached+ try {+ const entries = entriesOf(typeof localStorage === 'undefined' ? null : localStorage.getItem(PREFIX + sessionId))+ this.memory.set(sessionId, entries)+ return entries+ }+ catch {+ return new Map()+ }+ }++ private store(sessionId: string, entries: Map<string, StoredEntry>): void {+ const live = this.liveTabIds?.(sessionId)+ const kept = live?.length ? new Map([...entries].filter(([id]) => live.includes(id))) : entries+ this.memory.set(sessionId, kept)+ try {+ if (typeof localStorage === 'undefined')+ return+ if (kept.size)+ localStorage.setItem(PREFIX + sessionId, JSON.stringify(Object.fromEntries(kept)))+ else+ localStorage.removeItem(PREFIX + sessionId)+ }+ catch (error) {+ console.error('Task tab binding persistence failed:', error)+ }+ }+}++function isScheduleForm(value: unknown): value is ScheduleForm {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return false+ const schedule = value as Record<string, unknown>+ if (schedule.timeZone !== undefined && typeof schedule.timeZone !== 'string')+ return false+ switch (schedule.kind) {+ case 'once': return typeof schedule.at === 'string'+ case 'hourly': return typeof schedule.minute === 'number'+ case 'daily':+ case 'workdays': return typeof schedule.time === 'string'+ case 'interval': return typeof schedule.everyMinutes === 'number' && (schedule.anchor === undefined || typeof schedule.anchor === 'string')+ case 'weekly': return typeof schedule.time === 'string' && Array.isArray(schedule.weekdays)+ && schedule.weekdays.every(day => WEEKDAYS.includes(day))+ case 'monthly': return typeof schedule.day === 'number' && typeof schedule.time === 'string'+ case 'custom': return typeof schedule.everyDays === 'number' && typeof schedule.time === 'string' && (schedule.anchor === undefined || typeof schedule.anchor === 'string')+ default: return false+ }+}++export function taskTabParams(value: unknown): TaskTabNavigation | undefined {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return undefined+ const params = value as Record<string, unknown>+ if (params.sessionId !== undefined && (typeof params.sessionId !== 'string' || !params.sessionId.trim()))+ return undefined+ if (params.draft === true) {+ const initial = params.initial+ const valid = initial && typeof initial === 'object' && !Array.isArray(initial)+ && ['name', 'prompt', 'sessionId', 'workspaceId', 'permission', 'provider', 'model', 'reasoningEffort'].every(key => typeof (initial as Record<string, unknown>)[key] === 'string')+ && 'delivery' in initial && (initial.delivery === 'this-session' || initial.delivery === 'new-session')+ && 'enabled' in initial && typeof initial.enabled === 'boolean'+ && (!('recommendationId' in initial) || initial.recommendationId === undefined || typeof initial.recommendationId === 'string')+ && 'schedule' in initial && isScheduleForm(initial.schedule)+ return { draft: true, sessionId: params.sessionId, initial: valid ? initial as TaskFormState : undefined }+ }+ if (params.draft !== undefined && params.draft !== false)+ return undefined+ return typeof params.id === 'string' && params.id.trim() ? { id: params.id, sessionId: params.sessionId } : undefined+}diff --git a/packages/dsh-tauri-scheduler/src/client/store/index.ts b/packages/dsh-tauri-scheduler/src/client/store/index.tsindex fb869e70..e0b8dffb 100644--- a/packages/dsh-tauri-scheduler/src/client/store/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/store/index.ts@@ -1,7 +1,11 @@+import { deletion } from './modules/deletion'+import { navigation } from './modules/navigation'import { prefill } from './modules/prefill'import { scheduler } from './modules/scheduler'export const store = {+ deletion,+ navigation,prefill,scheduler,}diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/deletion.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/deletion.tsnew file mode 100644index 00000000..e222fbb4--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/deletion.ts@@ -0,0 +1,61 @@+import type { TaskView } from '../../types'+import { defineStore } from 'dsh-tauri/client'++export interface DeletionFeedback {+ seq: number+ kind: 'deleted' | 'deleteFailed'+ taskId: string+ name: string+ error?: string+}++interface DeletionState {+ pendingTask: TaskView | null+ deletingTaskId: string | null+ feedback: DeletionFeedback | null+ feedbackSeq: number+}++export const deletion = defineStore({+ state: (): DeletionState => ({+ pendingTask: null,+ deletingTaskId: null,+ feedback: null,+ feedbackSeq: 0,+ }),+ actions: {+ request(task: TaskView) {+ if (this.deletingTaskId !== null)+ return+ this.pendingTask = task+ },+ begin(): TaskView | null {+ if (this.pendingTask === null || this.deletingTaskId !== null)+ return null+ this.deletingTaskId = this.pendingTask.id+ return this.pendingTask+ },+ finish(task: TaskView, outcome: { ok: boolean, error?: string }) {+ if (this.deletingTaskId !== task.id)+ return+ this.pendingTask = null+ this.deletingTaskId = null+ this.feedbackSeq += 1+ this.feedback = {+ seq: this.feedbackSeq,+ kind: outcome.ok ? 'deleted' : 'deleteFailed',+ taskId: task.id,+ name: task.name,+ ...(outcome.error === undefined ? {} : { error: outcome.error }),+ }+ },+ cancel() {+ if (this.deletingTaskId === null)+ this.pendingTask = null+ },+ dismiss(seq?: number) {+ if (seq === undefined || this.feedback?.seq === seq)+ this.feedback = null+ },+ },+})diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/navigation.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/navigation.tsnew file mode 100644index 00000000..4941a35f--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/navigation.ts@@ -0,0 +1,26 @@+import type { TaskTabNavigation } from '../../types/task-tab'+import { defineStore } from 'dsh-tauri/client'++export const navigation = defineStore({+ state: () => ({+ target: null as TaskTabNavigation | null,+ seq: 0,+ error: '',+ }),+ actions: {+ request(target: TaskTabNavigation) {+ this.target = target+ this.error = ''+ this.seq += 1+ },+ finish(seq: number, error = '') {+ if (seq !== this.seq)+ return+ this.target = null+ this.error = error+ },+ dismiss() {+ this.error = ''+ },+ },+})diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.tsindex 0ace9d09..1ca07248 100644--- a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.ts@@ -11,6 +11,7 @@ export const scheduler = defineStore({error: '',refreshedAt: 0,loadToken: 0,+ successfulReadToken: 0,readAt: 0,readIds: [],}),diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.types.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.types.tsindex 1f5d4bf9..6a2e3935 100644--- a/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.types.ts+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/scheduler.types.ts@@ -8,6 +8,7 @@ export interface SchedulerUiState {error: stringrefreshedAt: numberloadToken: number+ successfulReadToken: number/** 上次「全部标记为已读」的时间戳;`0` 表示尚未播种(历史一律视为已读)。 */readAt: number/** 单条已读的运行 id(点击该记录、或在会话区打开它的会话时记入)。 */diff --git a/packages/dsh-tauri-scheduler/src/client/styles/index.cssr.ts b/packages/dsh-tauri-scheduler/src/client/styles/index.cssr.tsindex 05f4d029..9a49268b 100644--- a/packages/dsh-tauri-scheduler/src/client/styles/index.cssr.ts+++ b/packages/dsh-tauri-scheduler/src/client/styles/index.cssr.ts@@ -1,17 +1,5 @@-import { cssr, styles as sharedStyles } from 'dsh-tauri-ui/client'-import { SESSION_ICON_ATTRIBUTE } from '../constants'+import { cssr } from 'dsh-tauri-ui/client'-const { c } = cssr-const { secondary } = sharedStyles--/**- * 全局样式:只压官方会话树(`[role="treeitem"]`)——图标座位由 DOM 观察器注入,- * 侧栏导航按钮里那个未读点也要靠 `:has()` 反过来定位宿主按钮。组件自身样式一律写在- * 组件的 `className` 上(见 `components/scheduler.classes.ts` 与各组件)。- */-export default c([- c(`[${SESSION_ICON_ATTRIBUTE}]`, { width: '16px', height: '20px', flex: 'none', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginLeft: '2px', marginRight: '5px', color: secondary }),- c('[role="treeitem"]', { position: 'relative' }),- c(`[role="treeitem"]:hover [${SESSION_ICON_ATTRIBUTE}]`, { visibility: 'hidden' }),- c('button:has(.dshp-scheduler__nav-dot)', { position: 'relative' }),+export default cssr.c([+ cssr.c('button:has(.dshp-scheduler__nav-dot)', { position: 'relative' }),])diff --git a/packages/dsh-tauri-scheduler/src/client/types/index.ts b/packages/dsh-tauri-scheduler/src/client/types/index.tsindex 6ec2548b..4e97ee11 100644--- a/packages/dsh-tauri-scheduler/src/client/types/index.ts+++ b/packages/dsh-tauri-scheduler/src/client/types/index.ts@@ -1,16 +1,22 @@+import type { GetApiTauriSchedulerHistoryResponse, GetApiTauriSchedulerTasksResponse } from '../apis/index.type'+export type ScheduleKind = 'once' | 'hourly' | 'daily' | 'interval' | 'workdays' | 'weekly' | 'monthly' | 'custom'export type Weekday = 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA' | 'SU'-export type ScheduleForm- = | { kind: 'once', at: string }- | { kind: 'hourly', minute: number }- | { kind: 'daily', time: string }- | { kind: 'interval', everyMinutes: number, anchor?: string }- | { kind: 'workdays', time: string }- | { kind: 'weekly', weekdays: readonly Weekday[], time: string }- | { kind: 'monthly', day: number, time: string }- | { kind: 'custom', everyDays: number, anchor?: string, time: string }+export type TaskDelivery = 'this-session' | 'new-session'+export type TaskStatus = 'active' | 'inactive'++export type ScheduleForm = (+ | { kind: 'once', at: string }+ | { kind: 'hourly', minute: number }+ | { kind: 'daily', time: string }+ | { kind: 'interval', everyMinutes: number, anchor?: string }+ | { kind: 'workdays', time: string }+ | { kind: 'weekly', weekdays: readonly Weekday[], time: string }+ | { kind: 'monthly', day: number, time: string }+ | { kind: 'custom', everyDays: number, anchor?: string, time: string }+) & { timeZone?: string }export interface PermissionOption {value: string@@ -44,42 +50,22 @@ export interface ModelCatalogFailure {message: string}-export interface TaskView {- id: string- name: string- schedule: ScheduleForm & { timeZone?: string }- prompt: string- recommendationId?: string- workspaceId?: string- permission?: string- provider?: string- model?: string- reasoningEffort?: string- module?: string- enabled: boolean- createdAt: string- updatedAt: string- lastRunAt?: string- nextRunAt?: string- waiting?: boolean-}--export type RunStatus = 'queued' | 'running' | 'succeeded' | 'failed' | 'interrupted' | 'skipped' | 'cancelled'--export interface RunView {- id: string- taskId: string- taskName: string- trigger: 'schedule' | 'manual'- status: RunStatus- scheduledFor: string- startedAt: string- finishedAt?: string- sessionId?: string- error?: string+type TaskRecord = GetApiTauriSchedulerTasksResponse['tasks'][number]+export type TaskView = Omit<TaskRecord, 'schedule'> & {+ schedule: Exclude<TaskRecord['schedule'], { kind: 'weekly' }>+ | (Omit<Extract<TaskRecord['schedule'], { kind: 'weekly' }>, 'weekdays'> & { weekdays: readonly Weekday[] })}+type HistoryResponse = Extract<GetApiTauriSchedulerHistoryResponse, { ok: true }>+export type HistoryPage = Omit<HistoryResponse, 'ok' | 'runs'>+export type HistoryRecord = HistoryPage['records'][number]+export type RunView = HistoryResponse['runs'][number]+export type RunStatus = RunView['status']export interface TaskFormState {+ delivery: TaskDelivery+ sessionId: string+ enabled: boolean+ recommendationId?: stringname: stringschedule: ScheduleFormprompt: string@@ -100,6 +86,8 @@ export interface SchedulerOptions {}export interface TaskInput {+ delivery: TaskDelivery+ sessionId?: stringname: stringschedule: ScheduleFormprompt: stringdiff --git a/packages/dsh-tauri-scheduler/src/client/types/task-tab.ts b/packages/dsh-tauri-scheduler/src/client/types/task-tab.tsnew file mode 100644index 00000000..620a762f--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/client/types/task-tab.ts@@ -0,0 +1,70 @@+import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-store'+import type { SlotHookFactory } from '@deepseek-ai/dsh-client-ui-slots'+import type { SessionId, SessionListState } from 'dsh-tauri/client'+import type { TaskFormState } from './index'++export type TaskTabNavigation+ = | { id: string, sessionId?: string, draft?: false }+ | { draft: true, sessionId?: string, initial?: TaskFormState }++export interface TaskTabPage {+ readonly id: string+ readonly kind: string+ readonly contentId: string+}++export interface TaskTabInfo {+ readonly tab: TaskTabPage & {+ readonly title: string+ readonly visible: boolean+ readonly navigation: { readonly params?: unknown, readonly revision: number }+ readonly signal: AbortSignal+ readonly actions: {+ close: () => void+ openTab: (kind: string, options: { params: TaskTabNavigation }) => void+ bindCommands: (commands: { refresh: () => void }) => () => void+ }+ }+}++export interface SidebarRight {+ readonly mounted: {+ getSnapshot: () => SessionId | undefined+ subscribe: (listener: () => void) => () => void+ }+ openTab: (kind: string, options: { params: TaskTabNavigation }) => void+ tabsIn?: (sessionId: SessionId) => readonly TaskTabPage[]+}++export interface SidebarRightTabs {+ register: (definition: {+ id: string+ kind: string+ priority: 'extension'+ keepMounted: boolean+ title: () => string+ }) => () => void+}++declare module '@deepseek-ai/dsh-client-ui-slots' {+ interface SessionStandardProps {+ sessionId: SessionId+ }+ interface GlobalStandardProps {+ useSessions: SnapshotSelectorHook<SessionListState>+ }+ interface SlotMap {+ 'sidebar.right.pane.tab': {+ kind: 'keyed'+ scope: 'session'+ hookContext: unknown+ inject: { hooks: { tabInfo: SlotHookFactory<'sidebar.right.pane.tab', () => TaskTabInfo> } }+ }+ 'sidebar.right.pane.tab.title': {+ kind: 'keyed'+ scope: 'session'+ hookContext: unknown+ inject: { hooks: { tabInfo: SlotHookFactory<'sidebar.right.pane.tab.title', () => TaskTabInfo> } }+ }+ }+}diff --git a/packages/dsh-tauri-scheduler/src/host/apply.ts b/packages/dsh-tauri-scheduler/src/host/apply.tsindex 04ff37d3..a02d5292 100644--- a/packages/dsh-tauri-scheduler/src/host/apply.ts+++ b/packages/dsh-tauri-scheduler/src/host/apply.ts@@ -1,8 +1,8 @@import type { HostContext } from './types'import { PLUGIN_ID } from '../shared/constants'import { resetWriteQueue } from './config/runtime'+import { registerSessionOrigin } from './events/session-origin'import { server } from './server'-import { recovery } from './service/recovery'import { scheduler } from './service/scheduler'import { createTaskTool } from './tools/create-task'import { deleteTaskTool } from './tools/delete-task'@@ -11,36 +11,35 @@ import { updateTaskTool } from './tools/update-task'const SCHEDULER_TICK_MS = 1_000-const SCHEDULER_ROUTES_EFFECT = `${PLUGIN_ID}: routes`--const SCHEDULER_RECOVER_EFFECT = `${PLUGIN_ID}: recover interrupted runs`--const SCHEDULER_TICK_EFFECT = `${PLUGIN_ID}: tick`--const SCHEDULER_RUNTIME_EFFECT = `${PLUGIN_ID}: host runtime`-export interface Config {tickMs?: number}-export function apply(ctx: HostContext, config: Config = {}): void {- ctx.effect(() => server(ctx), SCHEDULER_ROUTES_EFFECT)+export async function apply(ctx: HostContext, config: Config = {}): Promise<void> {+ ctx.effect(() => server(ctx), `${PLUGIN_ID}: routes`)ctx.tools.register(createTaskTool())ctx.tools.register(listTasksTool())ctx.tools.register(updateTaskTool())ctx.tools.register(deleteTaskTool())+ if (ctx.get('sessionProjections') === undefined)+ console.warn('[scheduler origin] Public session projection unavailable; source marks disabled until declared.')+ await ctx.inject(['sessionProjections'], async (scoped: HostContext) => {+ await scoped.effect(() => registerSessionOrigin(scoped), `${PLUGIN_ID}: session origin`)+ })+const tickMs = Number.isFinite(config?.tickMs) && (config.tickMs as number) > 0? (config.tickMs as number): SCHEDULER_TICK_MS+ ctx.effect(() => startRuntime(tickMs), `${PLUGIN_ID}: host runtime`)+}- ctx.effect(() => {- void recovery.recover().catch((error: unknown) => {- ctx.logger?.warn?.('dsh-tauri-scheduler: recover interrupted runs failed', error)- })- }, SCHEDULER_RECOVER_EFFECT)-- ctx.effect(() => scheduler.start(tickMs), SCHEDULER_TICK_EFFECT)- ctx.effect(() => () => resetWriteQueue(), SCHEDULER_RUNTIME_EFFECT)+function startRuntime(tickMs: number): () => Promise<void> {+ resetWriteQueue()+ const stop = scheduler.start(tickMs)+ return async () => {+ await stop()+ resetWriteQueue()+ }}diff --git a/packages/dsh-tauri-scheduler/src/host/config/runtime.ts b/packages/dsh-tauri-scheduler/src/host/config/runtime.tsindex 002bb62d..4ff44bc5 100644--- a/packages/dsh-tauri-scheduler/src/host/config/runtime.ts+++ b/packages/dsh-tauri-scheduler/src/host/config/runtime.ts@@ -1,11 +1,49 @@+import type { PendingDelivery } from '../types'+let writeQueue: Promise<unknown> = Promise.resolve()+let taskQueue: Promise<unknown> = Promise.resolve()++export const runtime = {+ stopping: false,+ running: new Set<string>(),+ accepted: new Set<Promise<unknown>>(),+ pending: new Map<string, PendingDelivery>(),+ flushes: new Map<string, Promise<boolean>>(),+ failed: new Set<string>(),+}export function withWriteQueue<T>(fn: () => T | Promise<T>): Promise<T> {- const run = writeQueue.then(() => fn())+ const run = writeQueue.then(fn)writeQueue = run.then(() => undefined, () => undefined)return run}+export function withTaskQueue<T>(fn: () => T | Promise<T>): Promise<T> {+ const run = taskQueue.then(fn)+ taskQueue = run.then(() => undefined, () => undefined)+ return run+}++export function trackAccepted<T>(run: Promise<T>): Promise<T> {+ runtime.accepted.add(run)+ void run.then(() => runtime.accepted.delete(run), () => runtime.accepted.delete(run))+ return run+}++export async function drainRuntime(): Promise<void> {+ runtime.stopping = true+ await taskQueue+ await Promise.allSettled([...runtime.accepted])+ await writeQueue+}+export function resetWriteQueue(): void {writeQueue = Promise.resolve()+ taskQueue = Promise.resolve()+ runtime.stopping = false+ runtime.running.clear()+ runtime.accepted.clear()+ runtime.pending.clear()+ runtime.flushes.clear()+ runtime.failed.clear()}diff --git a/packages/dsh-tauri-scheduler/src/host/events/session-origin.ts b/packages/dsh-tauri-scheduler/src/host/events/session-origin.tsnew file mode 100644index 00000000..ad602303--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/events/session-origin.ts@@ -0,0 +1,27 @@+import type { SessionEvent, SessionHeader } from '@deepseek-ai/dsh-session'+import type { HostContext } from '../types'+import { SESSION_SCHEDULE_ORIGIN_PROJECTION } from '../../shared/constants'++export async function registerSessionOrigin(ctx: HostContext): Promise<() => void> {+ try {+ const module = await ctx.loader.import('zod')+ const z = module.z ?? ctx.loader.unwrapExports(module).z+ const stateSchema = z.object({ inheritedEventCount: z.number().int().nonnegative(), created: z.boolean() })+ return ctx.sessionProjections.register({+ key: SESSION_SCHEDULE_ORIGIN_PROJECTION,+ stateVersion: 1,+ stateSchema,+ init: (_header: SessionHeader, inheritedEventCount: number) => ({ inheritedEventCount, created: false }),+ apply: (state: { inheritedEventCount: number, created: boolean }, event: SessionEvent) => {+ if (state.created || event.seq < state.inheritedEventCount || event.type !== 'user/message' || event.data.source.kind !== 'scheduler')+ return state+ return { ...state, created: true }+ },+ wire: { viewSchema: z.boolean(), view: (state: { created: boolean }) => state.created },+ })+ }+ catch (error) {+ console.warn('[scheduler origin] Public session projection unavailable; source marks disabled.', error)+ return () => {}+ }+}diff --git a/packages/dsh-tauri-scheduler/src/host/server/index.test.ts b/packages/dsh-tauri-scheduler/src/host/server/index.test.tsindex 12e9f12f..e89fca6f 100644--- a/packages/dsh-tauri-scheduler/src/host/server/index.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/index.test.ts@@ -1,10 +1,25 @@import type { Context } from '@deepseek-ai/cordis'import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'+import type { MessageId, UserMessage } from '@deepseek-ai/dsh-llm'import type { IncomingMessage, Server, ServerResponse } from 'node:http'import type { AddressInfo } from 'node:net'+import type { SessionEventLike } from '../service/executor.utils'+import type { HistoryPage, OperationResult, SchedulerTask } from '../types'+import type { SetupAgentLike } from '../utils/agent-runtime.types'import { createServer } from 'node:http'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { server } from '.'+import { resetWriteQueue, runtime } from '../config/runtime'+import { history } from '../service/history'+import { scheduler } from '../service/scheduler'+import { task } from '../service/task'+import { storage } from '../storage'+import { createTaskTool } from '../tools/create-task'+import { deleteTaskTool } from '../tools/delete-task'+import { listTasksTool } from '../tools/list-tasks'+import { updateTaskTool } from '../tools/update-task'++vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))const P = '/api/tauri/scheduler'@@ -39,13 +54,95 @@ const UNDECLARED_METHOD = 'PATCH'interface Harness {registered: Map<string, WebRoute>ctx: Context+ core: ReturnType<typeof createCore>+}++const finishes: Array<() => void> = []+const coreStops: Array<() => void> = []++function createCore() {+ let messageSequence = 0+ const events: Array<{ type: string, data: { inserted: UserMessage[] } }> = []+ const session = { id: 'session-1' }+ const followup = vi.fn((message: UserMessage) => {+ events.push({ type: 'agent/inbox/spliced', data: { inserted: [message] } })+ })+ const agent = { session, followup }+ const listeners = new Set<(session: unknown, event: SessionEventLike) => void>()+ const controls: Array<{ finish: () => void, ready: Promise<void> }> = []+ let readyRun = () => {}+ let finishAutomatically = false+ const runReady = new Promise<void>((resolve) => {+ readyRun = resolve+ })+ coreStops.push(() => {+ finishAutomatically = true+ controls.forEach(control => control.finish())+ })+ const create = vi.fn(async (input: { sessionId: string, setup: (ctx: unknown, agent: SetupAgentLike) => Promise<void> }) => {+ const createdSession = { id: input.sessionId, seq: 0 }+ let finishIdle = () => {}+ let markReady = () => {}+ const idle = new Promise<void>((resolve) => {+ finishIdle = resolve+ })+ const ready = new Promise<void>((resolve) => {+ markReady = resolve+ })+ const emit = (type: string, data: Record<string, unknown>) => {+ createdSession.seq += 1+ for (const listener of listeners)+ listener(createdSession, { type, data, seq: createdSession.seq })+ }+ const finish = () => {+ emit('turn/end', { reason: { kind: 'completed' } })+ finishIdle()+ }+ controls.push({ finish, ready })+ finishes.push(finish)+ await input.setup({}, { session: createdSession })+ return { agent: { session: createdSession, followup: vi.fn(() => {+ emit('turn/start', {})+ markReady()+ readyRun()+ if (finishAutomatically)+ finish()+ }), whenIdle: vi.fn().mockResolvedValueOnce(undefined).mockReturnValue(idle), cancel: vi.fn(finish) } }+ })+ const workspace = { path: '/virtual/http-workspace', status: vi.fn(async () => 'ok'), attachSession: vi.fn(async () => {}) }+ const modules = new Map<string, unknown>([+ ['@deepseek-ai/dsh-llm', { createUserMessage: (input: Omit<UserMessage, 'id' | 'role'>) => ({ ...input, id: `http-message-${++messageSequence}` as MessageId, role: 'user' as const }) }],+ ['@deepseek-ai/dsh-agent', { installModelSelection: vi.fn() }],+ ['@deepseek-ai/dsh-user-approval', { setApprovalPolicy: vi.fn() }],+ ])+ return {+ agents: { create, currentInitiator: vi.fn<() => { session: { id: string } } | undefined>(), withoutInitiator: (fn: () => Promise<unknown>) => fn() },+ sessionController: { inspect: vi.fn(async (id: string) => ({ meta: { id }, events: structuredClone(events) })), resolveAgent: vi.fn(async () => ({ agent })) },+ workspaceRegistry: { archivedSessionIds: [] as string[], get: vi.fn(() => workspace) },+ sessions: { flush: vi.fn(async () => true) },+ permissionPresets: { defaultPreset: 'read-only', set: vi.fn() },+ agentPresets: { mount: vi.fn(async () => {}) },+ get: () => undefined,+ on: vi.fn((name: string, listener: (session: unknown, event: SessionEventLike) => void) => {+ if (name === 'session/event')+ listeners.add(listener)+ return () => listeners.delete(listener)+ }),+ loader: { import: vi.fn(async (name: string) => modules.get(name)), unwrapExports: (value: unknown) => value },+ controls,+ runReady,+ agent,+ }}function createHarness(): Harness {const registered = new Map<string, WebRoute>()+ const core = createCore()return {registered,+ core,ctx: {+ ...core,webServer: {register(route: WebRoute): () => void {const key = routeKey(route.kind, route.path)@@ -64,6 +161,9 @@ function createHarness(): Harness {const servers: Server[] = []const disposers: Array<() => void> = []+const state = new Map<string, unknown>()+const now = '2026-06-01T12:00:00.000Z'+const taskInput = { delivery: 'this-session', sessionId: 'session-1', name: 'HTTP reminder', prompt: 'real prompt', schedule: { kind: 'once', at: '2026-06-02T12:00:00.000Z', timeZone: 'UTC' } } as constasync function listen(registered: Map<string, WebRoute>): Promise<string> {const server = createServer((request: IncomingMessage, response: ServerResponse) => {@@ -100,9 +200,27 @@ function mount(harness: Harness): () => void {return dispose}+beforeEach(() => {+ vi.clearAllMocks()+ resetWriteQueue()+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(new Date(now))+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+})+afterEach(async () => {+ coreStops.splice(0).forEach(stop => stop())+ finishes.splice(0).forEach(finish => finish())+ await scheduler.stop()disposers.splice(0).forEach(dispose => dispose())await Promise.all(servers.splice(0).map(server => new Promise<void>(resolve => server.close(() => resolve()))))+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()})describe('调度器路由声明', () => {@@ -189,3 +307,196 @@ describe('调度器路由声明', () => {dispose()})})++describe('真实 HTTP 与 agent 工具共享协议', () => {+ it('hTTP 创建/list/update/delete 与四个工具读取同一任务来源', async () => {+ const harness = createHarness()+ mount(harness)+ const base = await listen(harness.registered)+ const createdResponse = await sendJson(base, 'POST', `${P}/tasks`, JSON.stringify(taskInput))+ expect(createdResponse.status).toBe(200)+ const created = await createdResponse.json() as { ok: true, task: SchedulerTask }+ expect(created).toMatchObject({ ok: true, task: { delivery: 'this-session', status: 'active', sessionId: 'session-1' } })+ expect(await listTasksTool().execute()).toEqual({ ok: true, tasks: [created.task] })+ expect(await updateTaskTool().execute({ task_id: created.task.id, prompt: 'tool rewrite' })).toMatchObject({ ok: true, taskId: created.task.id })+ const listed = await (await fetch(`${base}${P}/tasks`)).json() as { tasks: SchedulerTask[] }+ expect(listed.tasks[0]).toMatchObject({ prompt: 'tool rewrite', nextRunAt: taskInput.schedule.at })+ const missingExpected = await sendJson(base, 'PUT', `${P}/tasks`, JSON.stringify({ id: created.task.id, name: 'unsafe' }))+ expect(missingExpected.status).toBe(400)+ expect(await missingExpected.json()).toMatchObject({ ok: false, code: 'task_expected_required' })+ const partialExpected = await sendJson(base, 'PUT', `${P}/tasks`, JSON.stringify({ id: created.task.id, name: 'unsafe', expected: { id: created.task.id } }))+ expect(partialExpected.status).toBe(400)+ expect(await partialExpected.json()).toMatchObject({ ok: false, code: 'task_conflict' })+ const stale = await sendJson(base, 'PUT', `${P}/tasks`, JSON.stringify({ id: created.task.id, name: 'unsafe', expected: created.task }))+ expect(stale.status).toBe(400)+ expect(await stale.json()).toMatchObject({ ok: false, code: 'task_conflict' })+ const updated = await sendJson(base, 'PUT', `${P}/tasks`, JSON.stringify({ id: created.task.id, name: 'renamed', expected: { ...listed.tasks[0], waiting: true } }))+ expect(updated.status).toBe(200)+ expect(await updated.json()).toMatchObject({ ok: true, task: { name: 'renamed', prompt: 'tool rewrite' } })+ expect(await deleteTaskTool().execute({ task_id: created.task.id })).toEqual({ ok: true })+ expect(await (await fetch(`${base}${P}/tasks`)).json()).toEqual({ tasks: [] })+ expect(harness.core.sessionController.resolveAgent).not.toHaveBeenCalled()+ expect(harness.core.agent.followup).not.toHaveBeenCalled()+ })++ it('create 工具要求明确 delivery,捕获真实 initiator 并输出可重播卡片 metadata', async () => {+ const harness = createHarness()+ mount(harness)+ harness.core.agents.currentInitiator.mockReturnValue({ session: { id: 'session-1' } })+ const tool = createTaskTool()+ expect(tool.parameters.required).toEqual(['delivery', 'name', 'prompt', 'schedule'])+ expect(tool.parameters.properties.delivery.enum).toEqual(['this-session', 'new-session'])+ const created = await tool.execute({ ...taskInput, sessionId: undefined })+ expect(created).toMatchObject({ ok: true, taskId: expect.stringMatching(/^task-/), nextRunAt: taskInput.schedule.at, task: { delivery: 'this-session', status: 'active', sessionId: 'session-1', prompt: taskInput.prompt } })+ expect(JSON.parse(tool.output.render({}, created)[0].text)).toEqual(created)+ expect(await tool.execute({ ...taskInput, delivery: undefined })).toMatchObject({ ok: false, code: 'task_invalid' })+ expect(await tool.execute({ ...taskInput, sessionId: 'other' })).toMatchObject({ ok: false, code: 'session_mismatch' })+ expect(await tool.execute({ ...taskInput, permission: 'danger-full-access' })).toMatchObject({ ok: false, code: 'task_invalid' })+ expect(await listTasksTool().execute()).toMatchObject({ ok: true, tasks: [{ id: created.taskId }] })+ expect(harness.core.sessionController.resolveAgent).not.toHaveBeenCalled()+ })++ it('history 强制 limit,混合分页支持失活/不可用 Session 且不激活来源', async () => {+ const harness = createHarness()+ mount(harness)+ const base = await listen(harness.registered)+ const response = await sendJson(base, 'POST', `${P}/tasks`, JSON.stringify(taskInput))+ const created = await response.json() as { task: SchedulerTask }+ const target = { ...created.task, status: 'inactive' as const }+ state.set('tasks', { version: 2, tasks: [target] })+ await history.saveRun({ id: 'run-a', taskId: target.id, taskName: target.name, trigger: 'schedule', status: 'succeeded', scheduledFor: '2026-06-01T09:00:00.000Z', startedAt: now, finishedAt: now })+ await history.commit({ task: target, trigger: 'schedule', scheduledAt: '2026-06-01T10:00:00.000Z', deliveredAt: now, message: { id: 'receipt-a' as MessageId, role: 'user', content: [], source: { kind: 'schedule' } } })+ await history.commit({ task: target, trigger: 'manual', scheduledAt: '2026-06-01T11:00:00.000Z', deliveredAt: now, message: { id: 'receipt-b' as MessageId, role: 'user', content: [], source: { kind: 'schedule' } } })+ harness.core.workspaceRegistry.archivedSessionIds.push('session-1')+ harness.core.sessionController.inspect.mockRejectedValue(new Error('unavailable source'))+ harness.core.sessionController.inspect.mockClear()+ for (const limit of ['', '0', '101', '1.2', '-1', 'NaN', '2&limit=3']) {+ const invalid = await fetch(`${base}${P}/history?taskId=${target.id}${limit === '' ? '' : `&limit=${limit}`}`)+ expect(invalid.status, limit).toBe(400)+ expect(await invalid.json()).toMatchObject({ ok: false, code: 'history_invalid_limit' })+ }+ const firstResponse = await fetch(`${base}${P}/history?taskId=${target.id}&limit=2`)+ expect(firstResponse.status).toBe(200)+ const first = await firstResponse.json() as OperationResult<HistoryPage>+ expect(first).toMatchObject({ ok: true, records: [{ id: 'receipt-b', delivery: 'this-session' }, { id: 'receipt-a', delivery: 'this-session' }], runs: [], nextBefore: 'receipt-a', retention: { days: 30, records: 200 } })+ const second = await (await fetch(`${base}${P}/history?taskId=${target.id}&limit=2&before=receipt-a`)).json()+ expect(second).toMatchObject({ ok: true, records: [{ id: 'run-a', delivery: 'new-session' }], runs: [{ id: 'run-a' }] })+ expect(second).not.toHaveProperty('nextBefore')+ const global = await (await fetch(`${base}${P}/history?limit=10`)).json()+ expect(global).toMatchObject({ ok: true, runs: [{ id: 'run-a' }] })+ const invalidCursor = await fetch(`${base}${P}/history?taskId=${target.id}&limit=10&before=not-present`)+ expect(invalidCursor.status).toBe(400)+ expect(await invalidCursor.json()).toMatchObject({ ok: false, code: 'delivery_cursor_not_found' })+ const deleted = await sendJson(base, 'DELETE', `${P}/history`, JSON.stringify({ id: 'receipt-a' }))+ expect(deleted.status).toBe(200)+ expect(await (await fetch(`${base}${P}/history?taskId=${target.id}&limit=10`)).json()).toMatchObject({ ok: true, earlierRecordsPruned: true, records: [{ id: 'receipt-b' }, { id: 'run-a' }] })+ expect(harness.core.sessionController.inspect).not.toHaveBeenCalled()+ expect(harness.core.sessionController.resolveAgent).not.toHaveBeenCalled()+ expect(harness.core.agent.followup).not.toHaveBeenCalled()+ })++ it.each(['once', 'interval'] as const)('重复 HTTP recover 不消费 active %s run,完成后才更新 task/journal', async (kind) => {+ const harness = createHarness()+ mount(harness)+ const base = await listen(harness.registered)+ const dueAt = '2026-06-01T11:02:17.000Z'+ const target: SchedulerTask = {+ id: 'live-task',+ name: 'live',+ delivery: 'new-session',+ status: 'active',+ enabled: true,+ prompt: 'active prompt',+ workspaceId: 'http-workspace',+ createdAt: now,+ updatedAt: now,+ nextRunAt: dueAt,+ schedule: kind === 'once' ? { kind, at: dueAt, timeZone: 'UTC' } : { kind, everyMinutes: 15, anchor: dueAt, timeZone: 'UTC' },+ }+ state.set('tasks', { version: 2, tasks: [target] })+ await scheduler.tick()+ await harness.core.runReady+ expect(harness.core.controls).toHaveLength(1)+ const originalJournal = await history.journals(target.id)+ const originalRuns = await history.listRuns(target.id)+ expect(originalRuns).toMatchObject([{ status: 'running' }])+ expect(originalJournal).toMatchObject([{ task: target }])+ expect(originalJournal[0]).not.toHaveProperty('completedAt')+ for (let i = 0; i < 2; i++) {+ vi.setSystemTime(new Date('2026-06-01T13:02:17.000Z'))+ const response = await sendJson(base, 'POST', `${P}/runs/recover`, '{}')+ expect(response.status).toBe(200)+ expect(await response.json()).toEqual({ ok: true })+ await scheduler.tick()+ expect(await task.get(target.id)).toEqual(target)+ expect(await history.listRuns(target.id)).toEqual(originalRuns)+ expect(await history.journals(target.id)).toEqual(originalJournal)+ expect(harness.core.agents.create).toHaveBeenCalledTimes(1)+ }+ const accepted = [...runtime.accepted]+ expect(accepted).toHaveLength(1)+ harness.core.controls[0]!.finish()+ await Promise.all(accepted)+ expect(await history.journals()).toEqual([])+ expect(await history.listRuns(target.id)).toMatchObject([{ status: 'succeeded', finishedAt: '2026-06-01T13:02:17.000Z' }])+ expect(await task.get(target.id)).toMatchObject(kind === 'once' ? { status: 'inactive' } : { status: 'active', nextRunAt: '2026-06-01T13:17:17.000Z' })+ await scheduler.tick()+ expect(harness.core.agents.create).toHaveBeenCalledTimes(1)+ })++ it.each(['once', 'interval'] as const)('active %s run 拒绝 rename/pause 工具或 HTTP 编辑且不重跑同 occurrence', async (kind) => {+ const harness = createHarness()+ mount(harness)+ const base = await listen(harness.registered)+ const dueAt = '2026-06-01T11:02:17.000Z'+ const target: SchedulerTask = {+ id: 'live-task',+ name: 'live',+ delivery: 'new-session',+ status: 'active',+ enabled: true,+ prompt: 'active prompt',+ workspaceId: 'http-workspace',+ createdAt: now,+ updatedAt: now,+ nextRunAt: dueAt,+ schedule: kind === 'once' ? { kind, at: dueAt, timeZone: 'UTC' } : { kind, everyMinutes: 15, anchor: dueAt, timeZone: 'UTC' },+ }+ state.set('tasks', { version: 2, tasks: [target] })+ await scheduler.tick()+ await harness.core.runReady+ const renamed = await sendJson(base, 'PUT', `${P}/tasks`, JSON.stringify({ id: target.id, expected: target, name: 'changed' }))+ expect(renamed.status).toBe(400)+ expect(await renamed.json()).toMatchObject({ ok: false, code: 'task_busy' })+ const paused = await sendJson(base, 'POST', `${P}/tasks/toggle`, JSON.stringify({ id: target.id, enabled: false }))+ expect(paused.status).toBe(400)+ expect(await paused.json()).toMatchObject({ ok: false, code: 'task_busy' })+ expect(await updateTaskTool().execute({ task_id: target.id, name: 'changed by tool' })).toMatchObject({ ok: false, code: 'task_busy' })+ expect(await task.get(target.id)).toEqual(target)+ vi.setSystemTime(new Date('2026-06-01T13:02:17.000Z'))+ const accepted = [...runtime.accepted]+ harness.core.controls[0]!.finish()+ await Promise.all(accepted)+ await scheduler.tick()+ expect(harness.core.agents.create).toHaveBeenCalledTimes(1)+ expect(await history.journals()).toEqual([])+ expect(await task.get(target.id)).toMatchObject(kind === 'once' ? { name: 'live', status: 'inactive' } : { name: 'live', nextRunAt: '2026-06-01T13:17:17.000Z' })+ })++ it('run/toggle 返回终态领域错误,非法 enabled 不会变成暂停', async () => {+ const harness = createHarness()+ mount(harness)+ const base = await listen(harness.registered)+ const created = await (await sendJson(base, 'POST', `${P}/tasks`, JSON.stringify(taskInput))).json() as { task: SchedulerTask }+ const invalid = await sendJson(base, 'POST', `${P}/tasks/toggle`, JSON.stringify({ id: created.task.id, enabled: 'yes' }))+ expect(invalid.status).toBe(400)+ expect(await invalid.json()).toMatchObject({ ok: false, code: 'task_invalid' })+ state.set('tasks', { version: 2, tasks: [{ ...created.task, status: 'inactive' }] })+ for (const path of ['run', 'toggle']) {+ const response = await sendJson(base, 'POST', `${P}/tasks/${path}`, JSON.stringify({ id: created.task.id, enabled: true }))+ expect(response.status).toBe(400)+ expect(await response.json()).toMatchObject({ ok: false, code: 'task_inactive' })+ }+ expect(harness.core.sessionController.resolveAgent).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/history/delete.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/history/delete.tsindex 613353e6..92d1c949 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/history/delete.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/history/delete.ts@@ -1,7 +1,7 @@import type { EventHandlerRequest } from 'h3'import type { ActionResult, IdBody } from '../index.types'import { defineEventHandler, readBody } from 'h3'-import { runs } from '../../../service/runs'+import { history } from '../../../service/history'export default defineEventHandler<EventHandlerRequest, Promise<ActionResult>>(async (event) => {const body = await readBody<IdBody>(event)@@ -10,7 +10,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<ActionResult>>(asevent.res.status = 400return { error: '缺少执行记录 id' }}- if (!await runs.remove(id)) {+ if (!await history.remove(id)) {event.res.status = 400return { error: '执行记录不存在' }}diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/history/get.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/history/get.tsindex e2ab7150..e805d5e6 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/history/get.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/history/get.ts@@ -1,11 +1,14 @@import type { EventHandlerRequest } from 'h3'import type { GetHistoryQuery, RunListResponse } from '../index.types'import { defineEventHandler, getQuery } from 'h3'-import { castArray } from 'lodash-es'-import { runs } from '../../../service/runs'+import { history } from '../../../service/history'export default defineEventHandler<EventHandlerRequest, Promise<RunListResponse>>(async (event) => {- const raw = getQuery<GetHistoryQuery>(event).taskId- const taskId = castArray(raw)[0] ?? ''- return { runs: await runs.list(taskId === '' ? undefined : taskId) }+ const query = getQuery<GetHistoryQuery>(event)+ const rawLimit = query.limit as unknown+ const limit = typeof rawLimit === 'string' && /^\d+$/.test(rawLimit) ? Number(rawLimit) : typeof rawLimit === 'number' ? rawLimit : Number.NaN+ const result = await history.query({ taskId: query.taskId, limit, before: query.before })+ if (!result.ok)+ event.res.status = 400+ return result})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/index.types.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/index.types.tsindex d092f33f..894c4638 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/index.types.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/index.types.ts@@ -1,6 +1,8 @@-import type { SchedulerRun, SchedulerScheduleInput, SchedulerTask } from '../../types'+import type { HistoryPage, OperationResult, SchedulerScheduleInput, SchedulerTask, TaskDelivery } from '../../types'export interface TaskCreateBody {+ delivery: TaskDelivery+ sessionId?: stringname: stringschedule: SchedulerScheduleInputprompt: string@@ -15,6 +17,9 @@ export interface TaskCreateBody {export interface TaskUpdateBody {id: string+ expected: SchedulerTask+ delivery?: TaskDelivery+ sessionId?: stringname?: stringschedule?: SchedulerScheduleInputprompt?: string@@ -40,14 +45,13 @@ export interface TaskListResponse {tasks: SchedulerTask[]}-export interface RunListResponse {- runs: SchedulerRun[]-}+export type RunListResponse = OperationResult<HistoryPage>export interface TaskActionResult {ok?: booleantask?: SchedulerTaskerror?: string+ code?: string}export interface GetTasksQuery {@@ -56,9 +60,12 @@ export interface GetTasksQuery {export interface GetHistoryQuery {taskId?: string+ limit: number+ before?: string}export interface ActionResult {ok?: booleanerror?: string+ code?: string}diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/delete.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/delete.tsindex 7c8596e4..f25cd428 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/delete.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/delete.ts@@ -13,7 +13,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<ActionResult>>(asconst result = await task.remove(id)if (!result.ok) {event.res.status = 400- return { error: result.error }+ return { ok: false, error: result.error, code: result.code }}return { ok: true }})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/post.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/post.tsindex 10a339df..041a5d33 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/post.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/post.ts@@ -12,7 +12,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<TaskActionResult>const result = await task.create(body)if (!result.ok) {event.res.status = 400- return { error: result.error }+ return { ok: false, error: result.error, code: result.code }}return { ok: true, task: result.task }})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/put.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/put.tsindex 6d11aefd..c57edf38 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/put.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/put.ts@@ -6,14 +6,19 @@ import { task } from '../../../service/task'export default defineEventHandler<EventHandlerRequest, Promise<TaskActionResult>>(async (event) => {const body = await readBody<TaskUpdateBody>(event)const id = typeof body?.id === 'string' ? body.id : ''- if (id.length === 0) {+ if (!body || id.length === 0) {event.res.status = 400return { error: '缺少任务 id' }}- const result = await task.update(id, body ?? {})+ if (!body.expected || typeof body.expected !== 'object' || Array.isArray(body.expected)) {+ event.res.status = 400+ return { ok: false, error: '缺少完整 expected 任务记录', code: 'task_expected_required' }+ }+ const { id: _id, expected, ...patch } = body+ const result = await task.update(id, patch, expected)if (!result.ok) {event.res.status = 400- return { error: result.error }+ return { ok: false, error: result.error, code: result.code }}return { ok: true, task: result.task }})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/run/post.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/run/post.tsindex 5ce1b8f2..29e535fb 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/run/post.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/run/post.ts@@ -13,7 +13,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<ActionResult>>(asconst result = await scheduler.trigger(id)if (!result.ok) {event.res.status = 400- return { error: result.error }+ return { ok: false, error: result.error, code: result.code }}return { ok: true }})diff --git a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/toggle/post.ts b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/toggle/post.tsindex 3225f089..4e4a6414 100644--- a/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/toggle/post.ts+++ b/packages/dsh-tauri-scheduler/src/host/server/routes/tasks/toggle/post.ts@@ -6,14 +6,14 @@ import { task } from '../../../../service/task'export default defineEventHandler<EventHandlerRequest, Promise<TaskActionResult>>(async (event) => {const body = await readBody<TaskToggleBody>(event)const id = typeof body?.id === 'string' ? body.id : ''- if (id.length === 0) {+ if (!body || id.length === 0) {event.res.status = 400return { error: '缺少任务 id' }}- const result = await task.toggle(id, body?.enabled === true)+ const result = await task.toggle(id, body.enabled)if (!result.ok) {event.res.status = 400- return { error: result.error }+ return { ok: false, error: result.error, code: result.code }}return { ok: true, task: result.task }})diff --git a/packages/dsh-tauri-scheduler/src/host/service/binding-platform.test.ts b/packages/dsh-tauri-scheduler/src/host/service/binding-platform.test.tsnew file mode 100644index 00000000..00cc1f1b--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/binding-platform.test.ts@@ -0,0 +1,278 @@+import type { WebRoute } from '@deepseek-ai/dsh-host-webserver'+import type { SessionId } from '@deepseek-ai/dsh-session'+import type { Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import type { PendingDelivery, SchedulerTask } from '../types'+import { createServer } from 'node:http'+import { Context } from '@deepseek-ai/cordis'+import * as sessionControllerModule from '@deepseek-ai/dsh-api-session-controller'+import { ApiSessionNotFound, SessionController } from '@deepseek-ai/dsh-api-session-controller'+import * as llmModule from '@deepseek-ai/dsh-llm'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { inject } from '../../index'+import { resetWriteQueue } from '../config/runtime'+import { server } from '../server'+import { storage } from '../storage'+import { delivery } from './delivery'+import { history } from './history'+import { task } from './task'++vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))++const state = new Map<string, unknown>()+const contexts: Context[] = []+const httpServers: Server[] = []+const sessionId = 'platform-session' as SessionId+const schedule = { kind: 'once', at: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' } as const+const input = { delivery: 'this-session', sessionId, name: 'platform reminder', prompt: 'preserve this reminder', schedule } as const++async function createHarness(dependencies: readonly string[], missing = false, wrappedExports = false) {+ const root = new Context()+ contexts.push(root)+ const routes = new Map<string, WebRoute>()+ const disposeObservation = vi.fn()+ const observeSession = vi.fn(async (id: string) => ({+ header: missing ? { id } : { id, cwd: '/virtual/platform-session' },+ inheritedEventCount: 0,+ events: [],+ [Symbol.dispose]: disposeObservation,+ }))+ const agents = { currentInitiator: vi.fn<() => { session: { id: string } } | undefined>(), withoutInitiator: <T>(operation: () => T): T => operation(), get: vi.fn(() => undefined), create: vi.fn(), resume: vi.fn() }+ const workspaceRegistry = { archivedSessionIds: [] as string[] }+ const sessions = { get: vi.fn(() => undefined), flush: vi.fn(async () => true) }+ const loader = {+ import: vi.fn(async (name: string) => {+ if (name === '@deepseek-ai/dsh-api-session-controller')+ return wrappedExports ? { default: sessionControllerModule } : sessionControllerModule+ if (name === '@deepseek-ai/dsh-llm')+ return llmModule+ throw new Error(`Unexpected platform import: ${name}`)+ }),+ unwrapExports: vi.fn((value: unknown) => (value as { default?: unknown }).default ?? value),+ }+ root.accessor('loader', { get: () => loader })+ await root.plugin({+ name: 'scheduler-platform-boundaries',+ apply(ctx) {+ const values: Record<string, unknown> = {+ tools: {},+ webServer: { register: (route: WebRoute) => {+ routes.set(route.path, route)+ return () => routes.delete(route.path)+ } },+ agents,+ sessions,+ sessionQuery: { observeSession },+ sessionProjections: { register: vi.fn(), onChanged: vi.fn() },+ workspaceRegistry,+ agentDefaultModel: {},+ agentPresets: {},+ permissionPresets: {},+ llm: llmModule,+ attachments: { imageLimits: { maxImageBytes: 1024 } },+ fileUploads: { registerAgentResolver: () => () => {} },+ fs: {},+ fileReferences: {},+ typert: { lookups: { configure: vi.fn() }, contexts: { configureHost: vi.fn() } },+ connection: { fetch: { register: () => () => {} } },+ }+ for (const [name, value] of Object.entries(values))+ ctx.provide(name, value)+ },+ })+ await root.plugin(SessionController, { nativeOpen: false })+ const controller = root.get('sessionController') as SessionController+ let pluginContext: Context | undefined+ await root.plugin({+ name: 'scheduler-binding-platform-regression',+ inject: [...dependencies],+ apply(ctx) {+ pluginContext = ctx+ ctx.effect(() => server(ctx))+ },+ })+ const httpServer = createServer((request, response) => {+ const pathname = new URL(request.url ?? '/', 'http://127.0.0.1').pathname+ const route = routes.get(pathname)+ if (!route) {+ response.writeHead(404)+ response.end()+ return+ }+ void Promise.resolve(route.handler(request, response)).catch(() => {+ if (!response.headersSent) {+ response.writeHead(500)+ response.end()+ }+ })+ })+ httpServers.push(httpServer)+ await new Promise<void>(resolve => httpServer.listen(0, '127.0.0.1', () => resolve()))+ const base = `http://127.0.0.1:${(httpServer.address() as AddressInfo).port}`+ return { root, pluginContext, controller, agents, sessions, workspaceRegistry, observeSession, disposeObservation, loader, base }+}++function createRequest(base: string, body: unknown): Promise<Response> {+ return fetch(`${base}/api/tauri/scheduler/tasks`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ })+}++beforeEach(() => {+ vi.clearAllMocks()+ resetWriteQueue()+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+})++afterEach(async () => {+ await Promise.all(httpServers.splice(0).map(httpServer => new Promise<void>((resolve, reject) => {+ httpServer.close((error) => {+ if (error)+ reject(error)+ else+ resolve()+ })+ })))+ await Promise.all(contexts.splice(0).map(ctx => ctx.fiber.dispose()))+ resetWriteQueue()+ vi.restoreAllMocks()+})++describe('scheduler binding against actual platform contracts', () => {+ it('declares the controller injection needed by real Cordis HTTP binding, without activating the Session', async () => {+ const harness = await createHarness(inject)+ const { sessionId: _sessionId, ...withoutBinding } = input+ const missingBinding = await createRequest(harness.base, withoutBinding)+ expect(missingBinding.status).toBe(400)+ const response = await createRequest(harness.base, input)+ expect(response.status, await response.clone().text()).toBe(200)+ expect(await response.json()).toMatchObject({ ok: true, task: { delivery: 'this-session', sessionId } })+ expect(harness.observeSession).toHaveBeenCalledWith(sessionId, { projectionMode: 'none' })+ expect(harness.disposeObservation).toHaveBeenCalledTimes(1)+ expect(harness.agents.create).not.toHaveBeenCalled()+ expect(harness.agents.resume).not.toHaveBeenCalled()+ expect(harness.sessions.flush).not.toHaveBeenCalled()+ })++ it.each([false, true])('maps the actual cold inspect ApiSessionNotFound from loader exports (wrapped=%s)', async (wrappedExports) => {+ const harness = await createHarness([...inject, 'sessionController'], true, wrappedExports)+ const error: unknown = await harness.controller.inspect(sessionId).catch(reason => reason)+ expect(error).toBeInstanceOf(ApiSessionNotFound)+ expect(error).not.toHaveProperty('code')+ const exported = await harness.loader.import('@deepseek-ai/dsh-api-session-controller')+ const actualExports = wrappedExports ? harness.loader.unwrapExports(exported) : exported+ expect((actualExports as typeof sessionControllerModule).ApiSessionNotFound).toBe(ApiSessionNotFound)+ harness.loader.import.mockClear()+ harness.loader.unwrapExports.mockClear()+ const response = await createRequest(harness.base, input)+ expect(response.status, await response.clone().text()).toBe(400)+ expect(await response.json()).toEqual({ ok: false, error: '目标会话不存在', code: 'session_not_found' })+ expect(harness.loader.import).toHaveBeenCalledWith('@deepseek-ai/dsh-api-session-controller')+ expect(harness.agents.create).not.toHaveBeenCalled()+ expect(harness.agents.resume).not.toHaveBeenCalled()+ expect(await task.list()).toEqual([])+ })++ it.each(['archived', 'missing'] as const)('allows unchanged %s binding rename and pause without inspecting or activating its Session', async (unavailable) => {+ const harness = await createHarness([...inject, 'sessionController'], unavailable === 'missing')+ if (unavailable === 'archived')+ harness.workspaceRegistry.archivedSessionIds.push(sessionId)+ const target: SchedulerTask = {+ ...input,+ id: 'unavailable-binding-task',+ enabled: true,+ status: 'active',+ nextRunAt: schedule.at,+ createdAt: '2029-01-01T00:00:00.000Z',+ updatedAt: '2029-01-01T00:00:00.000Z',+ }+ state.set('tasks', { version: 2, tasks: [target] })+ const response = await fetch(`${harness.base}/api/tauri/scheduler/tasks`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id: target.id, expected: target, name: 'renamed unavailable reminder' }),+ })+ expect(response.status, await response.clone().text()).toBe(200)+ expect(await response.json()).toMatchObject({ ok: true, task: { name: 'renamed unavailable reminder', sessionId } })+ await expect(task.update(target.id, { enabled: false })).resolves.toMatchObject({ ok: true, task: { enabled: false, status: 'active', sessionId } })+ expect(harness.observeSession).not.toHaveBeenCalled()+ expect(harness.agents.create).not.toHaveBeenCalled()+ expect(harness.agents.resume).not.toHaveBeenCalled()+ })++ it('still rejects resource overrides and a different actual tool initiator on an unchanged unavailable binding', async () => {+ const harness = await createHarness([...inject, 'sessionController'], true)+ const target: SchedulerTask = {+ ...input,+ id: 'authority-binding-task',+ enabled: true,+ status: 'active',+ nextRunAt: schedule.at,+ createdAt: '2029-01-01T00:00:00.000Z',+ updatedAt: '2029-01-01T00:00:00.000Z',+ }+ state.set('tasks', { version: 2, tasks: [target] })+ await expect(task.update(target.id, { permission: 'danger-full-access' })).resolves.toMatchObject({ ok: false, code: 'task_invalid' })+ harness.agents.currentInitiator.mockReturnValue({ session: { id: 'different-initiator' } })+ await expect(task.update(target.id, { name: 'unauthorized change' })).resolves.toMatchObject({ ok: false, code: 'session_mismatch' })+ expect(await task.get(target.id)).toEqual(target)+ expect(harness.observeSession).not.toHaveBeenCalled()+ })++ it.each(['this-session', 'new-session'] as const)('revalidates a changed %s binding before adopting a missing Session', async (originalDelivery) => {+ const harness = await createHarness([...inject, 'sessionController'], true)+ const target: SchedulerTask = {+ ...input,+ delivery: originalDelivery,+ sessionId: originalDelivery === 'this-session' ? sessionId : undefined,+ id: 'changed-binding-task',+ enabled: true,+ status: 'active',+ nextRunAt: schedule.at,+ createdAt: '2029-01-01T00:00:00.000Z',+ updatedAt: '2029-01-01T00:00:00.000Z',+ }+ state.set('tasks', { version: 2, tasks: [target] })+ const before = await task.get(target.id)+ await expect(task.update(target.id, { delivery: 'this-session', sessionId: 'missing-new-binding' })).resolves.toMatchObject({ ok: false, code: 'session_not_found' })+ expect(harness.observeSession).toHaveBeenCalledWith('missing-new-binding', { projectionMode: 'none' })+ expect(await task.get(target.id)).toEqual(before)+ expect(harness.agents.create).not.toHaveBeenCalled()+ expect(harness.agents.resume).not.toHaveBeenCalled()+ })++ it('maps an actual cold inspect failure while recovering a pending identity without a receipt or second admission', async () => {+ const harness = await createHarness([...inject, 'sessionController'], true, true)+ const target: SchedulerTask = {+ ...input,+ id: 'pending-platform-task',+ enabled: true,+ status: 'active',+ nextRunAt: schedule.at,+ createdAt: '2029-01-01T00:00:00.000Z',+ updatedAt: '2029-01-01T00:00:00.000Z',+ }+ state.set('tasks', { version: 2, tasks: [target] })+ const pending: PendingDelivery = {+ task: target,+ trigger: 'schedule',+ scheduledAt: schedule.at,+ deliveredAt: schedule.at,+ message: llmModule.createUserMessage({ content: [{ type: 'text', text: input.prompt }], source: { kind: 'schedule', form: 'notice', summary: input.name } }),+ }+ await history.prepare(pending)+ await expect(delivery.run(target, 'schedule', schedule.at)).resolves.toEqual({ ok: false, error: '目标会话不存在', code: 'session_not_found' })+ expect(await history.pending(target.id)).toEqual([pending])+ expect(await history.query({ taskId: target.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ expect(await task.get(target.id)).toEqual(target)+ expect(harness.agents.create).not.toHaveBeenCalled()+ expect(harness.agents.resume).not.toHaveBeenCalled()+ expect(harness.sessions.flush).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.harness.ts b/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.harness.tsnew file mode 100644index 00000000..a4af4699--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.harness.ts@@ -0,0 +1,119 @@+import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { HostContext, SchedulerTask } from '../types'+import * as sessionControllerModule from '@deepseek-ai/dsh-api-session-controller'+import * as llmModule from '@deepseek-ai/dsh-llm'+import { vi } from 'vitest'+import { server } from '../server'+import { storage } from '../storage'++export const NOW = '2026-06-01T12:15:00.000Z'+export const DUE = '2026-06-01T12:00:00.000Z'+export const target: SchedulerTask = {+ id: 'deadline-task',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'deadline-session',+ name: 'deadline reminder',+ prompt: 'preserve the original reminder',+ schedule: { kind: 'once', at: DUE, timeZone: 'UTC' },+ enabled: true,+ createdAt: '2026-05-31T12:00:00.000Z',+ updatedAt: '2026-05-31T12:00:00.000Z',+ nextRunAt: DUE,+}+export const unrelated: SchedulerTask = {+ id: 'unrelated-task',+ delivery: 'new-session',+ status: 'active',+ name: 'unrelated paused task',+ prompt: 'do not execute this task',+ schedule: { kind: 'once', at: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' },+ enabled: false,+ createdAt: '2026-05-31T12:00:00.000Z',+ updatedAt: '2026-05-31T12:00:00.000Z',+ nextRunAt: '2030-01-01T12:00:00.000Z',+}++export interface SessionInspection {+ meta: { id: string }+ events: Array<{ type: string, data: { inserted: UserMessage[] } }>+}++const state = new Map<string, unknown>()+const releases: Array<() => void> = []+const operations: Promise<unknown>[] = []++export function seed(...tasks: SchedulerTask[]): void {+ state.set('tasks', { version: 2, tasks: structuredClone(tasks) })+}++export function resetStorage(): void {+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+}++export function deferred<T>(cleanupValue: T) {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason: unknown) => void+ const promise = new Promise<T>((accept, fail) => {+ resolve = accept+ reject = fail+ })+ releases.push(() => resolve(cleanupValue))+ return { promise, resolve, reject }+}++export function observe<T>(promise: Promise<T>) {+ const settled = vi.fn()+ const completion = promise.then((value) => {+ settled(value)+ return value+ })+ operations.push(completion)+ return { promise: completion, settled }+}++export async function releaseOperations(): Promise<void> {+ for (const release of releases.splice(0))+ release()+ await vi.advanceTimersByTimeAsync(0)+ await Promise.all(operations.splice(0))+}++export function installHost() {+ const session = { id: 'deadline-session', seq: 0 }+ const events: SessionInspection['events'] = []+ const followup = vi.fn((message: UserMessage) => {+ events.push({ type: 'agent/inbox/spliced', data: { inserted: [structuredClone(message)] } })+ })+ const agent = { session, followup, whenIdle: vi.fn(), steer: vi.fn(), inject: vi.fn() }+ const inspect = vi.fn<(id: string) => Promise<SessionInspection>>(async id => ({ meta: { id }, events: structuredClone(events) }))+ const resolveAgent = vi.fn<(id: string) => Promise<{ agent: typeof agent }>>(async () => ({ agent }))+ const flush = vi.fn<(session: unknown) => Promise<boolean>>(async () => true)+ const create = vi.fn()+ const logger = { warn: vi.fn() }+ const loader = {+ import: vi.fn<(name: string) => Promise<unknown>>(async (name) => {+ if (name === '@deepseek-ai/dsh-llm')+ return llmModule+ if (name === '@deepseek-ai/dsh-api-session-controller')+ return sessionControllerModule+ throw new Error(`Unexpected platform import: ${name}`)+ }),+ unwrapExports: vi.fn((exports: unknown) => exports),+ }+ const context = {+ agents: { create, currentInitiator: () => undefined, withoutInitiator: <T>(fn: () => T): T => fn() },+ sessionController: { inspect, resolveAgent },+ sessions: { flush },+ workspaceRegistry: { archivedSessionIds: [] },+ logger,+ loader,+ webServer: { register: () => () => {} },+ }+ const dispose = server(context as unknown as HostContext)+ return { agent, session, events, followup, inspect, resolveAgent, flush, create, loader, logger, dispose }+}diff --git a/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.ts b/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.tsnew file mode 100644index 00000000..feabb143--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/delivery.deadline.test.ts@@ -0,0 +1,420 @@+import type { PendingDelivery, TaskInput } from '../types'+import type { SessionInspection } from './delivery.deadline.test.harness'+import { createUserMessage } from '@deepseek-ai/dsh-llm'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetWriteQueue, runtime } from '../config/runtime'+import { deferred, DUE, installHost, NOW, observe, releaseOperations, resetStorage, seed, target, unrelated } from './delivery.deadline.test.harness'+import { history } from './history'+import { scheduler } from './scheduler'+import { task } from './task'++vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))++const SESSION_TIMEOUT = { ok: false, error: '等待宿主会话操作超时', code: 'session_unavailable' } as const+const DELIVERY_PENDING = { ok: false, error: 'Session persistence did not acknowledge the reminder', code: 'delivery_pending' } as const+let host: ReturnType<typeof installHost>++beforeEach(() => {+ vi.resetAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(NOW))+ resetStorage()+ seed(target, unrelated)+ host = installHost()+})++afterEach(async () => {+ await releaseOperations()+ await scheduler.stop()+ host.dispose()+ resetWriteQueue()+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++async function expectNoReceipt(): Promise<void> {+ expect(await history.query({ taskId: target.id, limit: 20 })).toEqual({+ ok: true,+ records: [],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ })+}++async function expectRetainedPending(scheduledAt: string, trigger: 'schedule' | 'manual'): Promise<PendingDelivery> {+ const pending = await history.pending(target.id)+ expect(pending).toHaveLength(1)+ const item = pending[0]!+ expect(item).toEqual({ task: target, trigger, scheduledAt, deliveredAt: NOW, message: host.followup.mock.calls[0]![0] })+ expect(runtime.pending.get(target.id)).toEqual(item)+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ return item+}++async function expectTimedOut(observation: ReturnType<typeof observe>): Promise<void> {+ await vi.advanceTimersByTimeAsync(9999)+ expect(observation.settled).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(observation.settled, 'the real task-queue operation must settle at 10,000 ms rather than waiting for the platform forever').toHaveBeenCalledTimes(1)+ expect(runtime.accepted.size).toBe(0)+}++describe('bounded this-session platform operations', () => {+ it('commits a normal acknowledged reminder with no deadline timer or execution success claim', async () => {+ await scheduler.tick()+ expect(host.resolveAgent).toHaveBeenCalledExactlyOnceWith('deadline-session')+ expect(host.flush).toHaveBeenCalledExactlyOnceWith(host.session)+ expect(host.followup).toHaveBeenCalledTimes(1)+ const message = host.followup.mock.calls[0]![0]+ expect(message.role).toBe('user')+ expect(message.id).toBeTypeOf('string')+ expect(message.source).toEqual({ kind: 'schedule', form: 'notice', summary: 'Scheduled: deadline reminder' })+ expect(await history.query({ taskId: target.id, limit: 20 })).toEqual({+ ok: true,+ records: [{ id: message.id, messageId: message.id, taskId: 'deadline-task', taskName: 'deadline reminder', delivery: 'this-session', occurrence: DUE, trigger: 'schedule', sessionId: 'deadline-session', scheduledAt: DUE, deliveredAt: NOW, prompt: 'preserve the original reminder' }],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ })+ const { nextRunAt: _nextRunAt, ...completed } = target+ expect(await task.get(target.id)).toEqual({ ...completed, status: 'inactive', lastRunAt: NOW, updatedAt: NOW })+ expect(await history.pending()).toEqual([])+ expect(await history.journals()).toEqual([])+ expect(runtime.pending.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ expect(host.create).not.toHaveBeenCalled()+ expect(host.agent.whenIdle).not.toHaveBeenCalled()+ expect(host.agent.steer).not.toHaveBeenCalled()+ expect(host.agent.inject).not.toHaveBeenCalled()+ })++ it('preserves false-flush failure and retries the admitted message identity without another followup', async () => {+ host.flush.mockResolvedValueOnce(false)+ expect(await scheduler.trigger(target.id)).toEqual(DELIVERY_PENDING)+ const pending = await expectRetainedPending(NOW, 'manual')+ expect(runtime.failed.has(target.id)).toBe(false)+ expect(vi.getTimerCount()).toBe(0)+ expect(await scheduler.trigger(target.id)).toEqual({ ok: true })+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(2)+ expect(await history.query({ taskId: target.id, limit: 20 })).toMatchObject({ ok: true, records: [{ id: pending.message.id, messageId: pending.message.id, trigger: 'manual', scheduledAt: NOW }] })+ expect(await task.get(target.id)).toEqual({ ...target, lastRunAt: NOW, updatedAt: NOW })+ expect(await history.pending()).toEqual([])+ })++ it('automatically retries rejected persistence on the next tick without duplicating the admitted identity', async () => {+ host.flush.mockRejectedValueOnce(new Error('isolated platform persistence failure'))+ await scheduler.tick()+ const pending = await expectRetainedPending(DUE, 'schedule')+ await scheduler.tick()+ expect(host.flush).toHaveBeenCalledTimes(2)+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: target.id, limit: 20 })).toMatchObject({ ok: true, records: [{ messageId: pending.message.id }] })+ expect(await history.pending()).toEqual([])+ expect(await task.get(target.id)).toMatchObject({ status: 'inactive' })+ expect(runtime.failed.has(target.id)).toBe(false)+ })++ it('automatically retries unavailable session inspection on the next tick', async () => {+ host.inspect.mockRejectedValueOnce(new Error('temporary session read failure'))+ await scheduler.tick()+ expect(host.followup).not.toHaveBeenCalled()+ await expectNoReceipt()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await task.get(target.id)).toMatchObject({ status: 'inactive' })+ expect(runtime.failed.has(target.id)).toBe(false)+ })++ it('does not automatically retry a confirmed missing target', async () => {+ host.inspect.mockRejectedValueOnce(Object.assign(new Error('session missing'), { code: 'session/not-found' }))+ await scheduler.tick()+ await scheduler.tick()+ expect(host.inspect).toHaveBeenCalledTimes(1)+ expect(host.followup).not.toHaveBeenCalled()+ expect(runtime.failed.has(target.id)).toBe(true)+ await expectNoReceipt()+ })++ it('fails a hung resolve at 10 seconds, releases the queue, and never follows up a late restored Agent', async () => {+ const resolving = deferred({ agent: host.agent })+ host.resolveAgent.mockReturnValueOnce(resolving.promise)+ const run = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ expect(host.resolveAgent).toHaveBeenCalledExactlyOnceWith('deadline-session')+ const removal = observe(task.remove(unrelated.id))+ await vi.advanceTimersByTimeAsync(0)+ expect(removal.settled).not.toHaveBeenCalled()+ await expectTimedOut(run)+ expect(await run.promise).toEqual(SESSION_TIMEOUT)+ expect(removal.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await removal.promise).toEqual({ ok: true })+ expect(await task.get(target.id)).toEqual(target)+ expect(await history.pending()).toEqual([])+ await expectNoReceipt()+ resolving.resolve({ agent: host.agent })+ await vi.advanceTimersByTimeAsync(0)+ expect(host.resolveAgent).toHaveBeenCalledTimes(1)+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).not.toHaveBeenCalled()+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ expect(vi.getTimerCount()).toBe(0)+ })++ it.each(['initial binding', 'post-restoration recheck'] as const)('fails a hung %s inspect without admission or blocking a later task mutation', async (phase) => {+ const inspection = deferred<SessionInspection>({ meta: { id: 'deadline-session' }, events: [] })+ if (phase === 'post-restoration recheck')+ host.inspect.mockResolvedValueOnce({ meta: { id: 'deadline-session' }, events: [] })+ host.inspect.mockReturnValueOnce(inspection.promise)+ const run = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ expect(host.inspect).toHaveBeenCalledTimes(phase === 'initial binding' ? 1 : 2)+ expect(host.resolveAgent).toHaveBeenCalledTimes(phase === 'initial binding' ? 0 : 1)+ const removal = observe(task.remove(unrelated.id))+ await expectTimedOut(run)+ expect(await run.promise).toEqual(SESSION_TIMEOUT)+ expect(removal.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await removal.promise).toEqual({ ok: true })+ expect(await task.get(target.id)).toEqual(target)+ expect(await history.pending()).toEqual([])+ await expectNoReceipt()+ inspection.resolve({ meta: { id: 'deadline-session' }, events: [] })+ await vi.advanceTimersByTimeAsync(0)+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).not.toHaveBeenCalled()+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ expect(vi.getTimerCount()).toBe(0)+ })++ it('bounds cold pending inspection while preserving the prepared identity and ignoring late evidence', async () => {+ const message = createUserMessage({ content: [{ type: 'text', text: 'already admitted reminder' }], source: { kind: 'schedule', form: 'notice', summary: 'durable pending reminder' } })+ const pending: PendingDelivery = { task: target, trigger: 'schedule', scheduledAt: DUE, deliveredAt: NOW, message }+ await history.prepare(pending)+ host.events.push({ type: 'agent/inbox/spliced', data: { inserted: [message] } })+ const inspection = deferred<SessionInspection>({ meta: { id: 'deadline-session' }, events: structuredClone(host.events) })+ host.inspect.mockReturnValueOnce(inspection.promise)+ const run = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ expect(host.inspect).toHaveBeenCalledExactlyOnceWith('deadline-session')+ const removal = observe(task.remove(unrelated.id))+ await expectTimedOut(run)+ expect(await run.promise).toEqual(SESSION_TIMEOUT)+ expect(removal.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await removal.promise).toEqual({ ok: true })+ expect(await history.pending(target.id)).toEqual([pending])+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ inspection.resolve({ meta: { id: 'deadline-session' }, events: structuredClone(host.events) })+ await vi.advanceTimersByTimeAsync(0)+ expect(host.resolveAgent).not.toHaveBeenCalled()+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).not.toHaveBeenCalled()+ expect(await history.pending(target.id)).toEqual([pending])+ expect(vi.getTimerCount()).toBe(0)+ })++ it('returns pending at 10 seconds for a hung flush and frees a later mutation without fabricating durability', async () => {+ const flushing = deferred(true)+ host.flush.mockReturnValueOnce(flushing.promise)+ const run = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ expect(host.flush).toHaveBeenCalledExactlyOnceWith(host.session)+ expect(host.followup).toHaveBeenCalledTimes(1)+ const removal = observe(task.remove(unrelated.id))+ await expectTimedOut(run)+ expect(await run.promise).toEqual(DELIVERY_PENDING)+ expect(removal.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await removal.promise).toEqual({ ok: true })+ await expectRetainedPending(NOW, 'manual')+ expect(runtime.failed.has(target.id)).toBe(false)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('bounds successive drives of one hung flush without accumulating platform calls or duplicate message identities', async () => {+ const flushing = deferred(true)+ host.flush.mockReturnValueOnce(flushing.promise)+ const first = observe(scheduler.tick())+ await vi.advanceTimersByTimeAsync(0)+ await expectTimedOut(first)+ await first.promise+ const pending = await expectRetainedPending(DUE, 'schedule')+ const retry = observe(scheduler.tick())+ await vi.advanceTimersByTimeAsync(0)+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(1)+ await expectTimedOut(retry)+ await retry.promise+ expect(await history.pending(target.id)).toEqual([pending])+ expect(runtime.pending.get(target.id)?.message.id).toBe(pending.message.id)+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ })++ it('accepts a late true flush only on the next explicit drive while retaining the original occurrence and message identity', async () => {+ const flushing = deferred(true)+ host.flush.mockReturnValueOnce(flushing.promise)+ const first = observe(scheduler.tick())+ await vi.advanceTimersByTimeAsync(0)+ await expectTimedOut(first)+ await first.promise+ const pending = await expectRetainedPending(DUE, 'schedule')+ flushing.resolve(true)+ await vi.advanceTimersByTimeAsync(1000)+ expect(await history.pending(target.id)).toEqual([pending])+ expect(await task.get(target.id)).toEqual(target)+ await expectNoReceipt()+ expect(await scheduler.trigger(target.id)).toEqual({ ok: true })+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: target.id, limit: 20 })).toEqual({+ ok: true,+ records: [{ id: pending.message.id, messageId: pending.message.id, taskId: 'deadline-task', taskName: 'deadline reminder', delivery: 'this-session', occurrence: DUE, trigger: 'schedule', sessionId: 'deadline-session', scheduledAt: DUE, deliveredAt: '2026-06-01T12:15:11.000Z', prompt: 'preserve the original reminder' }],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ })+ const { nextRunAt: _nextRunAt, ...completed } = target+ expect(await task.get(target.id)).toEqual({ ...completed, status: 'inactive', lastRunAt: '2026-06-01T12:15:11.000Z', updatedAt: '2026-06-01T12:15:11.000Z' })+ expect(await history.pending()).toEqual([])+ expect(await history.journals()).toEqual([])+ expect(runtime.pending.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('keeps a late false flush unacknowledged and retries durability without re-following up the admitted reminder', async () => {+ const flushing = deferred(false)+ host.flush.mockReturnValueOnce(flushing.promise)+ const first = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ await expectTimedOut(first)+ expect(await first.promise).toEqual(DELIVERY_PENDING)+ const pending = await expectRetainedPending(NOW, 'manual')+ flushing.resolve(false)+ await vi.advanceTimersByTimeAsync(0)+ expect(await history.pending(target.id)).toEqual([pending])+ await expectNoReceipt()+ expect(await scheduler.trigger(target.id)).toEqual({ ok: true })+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(2)+ expect(await history.query({ taskId: target.id, limit: 20 })).toMatchObject({ ok: true, records: [{ messageId: pending.message.id, scheduledAt: NOW, trigger: 'manual' }] })+ })++ it('preserves a late flush rejection without detached side effects and retries the same admitted identity', async () => {+ const flushing = deferred(true)+ host.flush.mockReturnValueOnce(flushing.promise)+ const first = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ await expectTimedOut(first)+ expect(await first.promise).toEqual(DELIVERY_PENDING)+ const pending = await expectRetainedPending(NOW, 'manual')+ flushing.reject(new Error('late platform persistence rejection'))+ await vi.advanceTimersByTimeAsync(0)+ expect(await history.pending(target.id)).toEqual([pending])+ expect(await task.get(target.id)).toEqual(target)+ expect(runtime.failed.has(target.id)).toBe(false)+ expect(host.flush).toHaveBeenCalledTimes(1)+ await expectNoReceipt()+ expect(await scheduler.trigger(target.id)).toEqual({ ok: true })+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(2)+ expect(await history.query({ taskId: target.id, limit: 20 })).toMatchObject({ ok: true, records: [{ id: pending.message.id, messageId: pending.message.id, trigger: 'manual', scheduledAt: NOW }] })+ expect(await history.pending()).toEqual([])+ expect(await history.journals()).toEqual([])+ expect(vi.getTimerCount()).toBe(0)+ })++ it('lets scheduler shutdown drain a hung durability barrier at its deadline while preserving recovery evidence', async () => {+ const flushing = deferred(true)+ host.flush.mockReturnValueOnce(flushing.promise)+ const first = observe(scheduler.tick())+ await vi.advanceTimersByTimeAsync(0)+ const stopped = observe(scheduler.stop())+ await vi.advanceTimersByTimeAsync(9999)+ expect(stopped.settled).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(first.settled).toHaveBeenCalledTimes(1)+ expect(stopped.settled).toHaveBeenCalledTimes(1)+ await first.promise+ await stopped.promise+ const pending = await expectRetainedPending(DUE, 'schedule')+ flushing.resolve(true)+ await vi.advanceTimersByTimeAsync(0)+ expect(await history.pending(target.id)).toEqual([pending])+ await expectNoReceipt()+ expect(runtime.accepted.size).toBe(0)+ expect(await scheduler.trigger(target.id)).toEqual({ ok: false, error: '调度器正在卸载', code: 'scheduler_stopping' })+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it.each(['inspect', 'resolveAgent', 'flush'] as const)('accepts a successful %s settled at 9,999 ms and cancels the unused deadline', async (operation) => {+ const inspection = deferred<SessionInspection>({ meta: { id: 'deadline-session' }, events: [] })+ const resolving = deferred({ agent: host.agent })+ const flushing = deferred(true)+ if (operation === 'inspect')+ host.inspect.mockReturnValueOnce(inspection.promise)+ if (operation === 'resolveAgent')+ host.resolveAgent.mockReturnValueOnce(resolving.promise)+ if (operation === 'flush')+ host.flush.mockReturnValueOnce(flushing.promise)+ const run = observe(scheduler.trigger(target.id))+ await vi.advanceTimersByTimeAsync(0)+ await vi.advanceTimersByTimeAsync(9999)+ expect(run.settled).not.toHaveBeenCalled()+ inspection.resolve({ meta: { id: 'deadline-session' }, events: [] })+ resolving.resolve({ agent: host.agent })+ flushing.resolve(true)+ await vi.advanceTimersByTimeAsync(0)+ expect(run.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await run.promise).toEqual({ ok: true })+ expect(host.resolveAgent).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.pending()).toEqual([])+ expect(await task.get(target.id)).toEqual({ ...target, lastRunAt: '2026-06-01T12:15:09.999Z', updatedAt: '2026-06-01T12:15:09.999Z' })+ expect(vi.getTimerCount()).toBe(0)+ await vi.advanceTimersByTimeAsync(1)+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(run.settled).toHaveBeenCalledTimes(1)+ })+})++describe('bounded cold inspection in real task mutations', () => {+ it.each(['create', 'update'] as const)('fails a hung %s binding inspection without holding either queue or applying a late validation', async (operation) => {+ const sessionId = operation === 'create' ? 'deadline-session' : 'rebinding-session'+ const inspection = deferred<SessionInspection>({ meta: { id: sessionId }, events: [] })+ host.inspect.mockReturnValueOnce(inspection.promise)+ const input: TaskInput = { delivery: 'this-session', sessionId, name: 'new bound reminder', prompt: 'never commit a timed-out validation', schedule: { kind: 'once', at: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' }, enabled: false }+ const mutation = observe(operation === 'create' ? task.create(input) : task.update(target.id, { sessionId, prompt: 'never commit a timed-out edit' }, target))+ await vi.advanceTimersByTimeAsync(0)+ expect(host.inspect).toHaveBeenCalledExactlyOnceWith(sessionId)+ const removal = observe(task.remove(unrelated.id))+ await vi.advanceTimersByTimeAsync(9999)+ expect(mutation.settled).not.toHaveBeenCalled()+ expect(removal.settled).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(mutation.settled, 'a hung cold binding read must not hold the task or storage write queue forever').toHaveBeenCalledExactlyOnceWith(SESSION_TIMEOUT)+ expect(await mutation.promise).toEqual(SESSION_TIMEOUT)+ expect(removal.settled).toHaveBeenCalledExactlyOnceWith({ ok: true })+ expect(await removal.promise).toEqual({ ok: true })+ expect(await task.list()).toEqual([target])+ inspection.resolve({ meta: { id: sessionId }, events: [] })+ await vi.advanceTimersByTimeAsync(0)+ expect(await task.list()).toEqual([target])+ expect(host.resolveAgent).not.toHaveBeenCalled()+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).not.toHaveBeenCalled()+ await expectNoReceipt()+ expect(vi.getTimerCount()).toBe(0)+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/service/delivery.recovery-message.test.ts b/packages/dsh-tauri-scheduler/src/host/service/delivery.recovery-message.test.tsnew file mode 100644index 00000000..ce5a7bb4--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/delivery.recovery-message.test.ts@@ -0,0 +1,182 @@+import type { InboxTarget } from '@deepseek-ai/dsh-agent/types'+import type { UserMessage } from '@deepseek-ai/dsh-llm'+import type { SessionEvent } from '@deepseek-ai/dsh-session'+import type { PendingDelivery, SchedulerTask } from '../types'+import { Context } from '@deepseek-ai/cordis'+import * as llmModule from '@deepseek-ai/dsh-llm'+import { Session, SessionId } from '@deepseek-ai/dsh-session'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetWriteQueue, runtime } from '../config/runtime'+import { server } from '../server'+import { storage } from '../storage'+import { delivery } from './delivery'+import { history } from './history'+import { scheduler } from './scheduler'+import { task } from './task'++vi.mock('../storage', async () => {+ const { createStorage } = await import('unstorage')+ return { storage: createStorage() }+})++const now = '2026-06-01T12:15:00.000Z'+const due = '2026-06-01T12:00:00.000Z'+const sessionId = SessionId('recovery-message-session')+const target: SchedulerTask = {+ id: 'recovery-message-task',+ delivery: 'this-session',+ status: 'active',+ sessionId,+ name: 'recover consumed reminder',+ prompt: 'preserve the original delivery identity',+ schedule: { kind: 'once', at: due, timeZone: 'UTC' },+ enabled: true,+ createdAt: '2026-05-31T12:00:00.000Z',+ updatedAt: '2026-05-31T12:00:00.000Z',+ nextRunAt: due,+}+const contexts: Context[] = []+const disposers: Array<() => void> = []++function createMessage(): UserMessage {+ return llmModule.createUserMessage({+ content: [{ type: 'text', text: target.prompt }],+ source: { kind: 'schedule', form: 'notice', summary: target.name },+ })+}++function createHarness() {+ const session = Session.create(sessionId)+ const events: SessionEvent[] = []+ const inboxTarget: InboxTarget = 'next-turn'+ const appendInbox = (message: UserMessage) => {+ const event = session.append('agent/inbox/spliced', { target: inboxTarget, start: 0, inserted: [message] })+ events.push(event)+ return event+ }+ const appendMessage = (message: UserMessage) => {+ const event = session.append('user/message', message, { surfaceOp: 'append' })+ events.push(event)+ return event+ }+ const followup = vi.fn(appendInbox)+ const agent = { session, runningStatus: 'running', followup, whenIdle: vi.fn(), steer: vi.fn(), inject: vi.fn() }+ const inspect = vi.fn(async () => ({ meta: session.header, inheritedEventCount: session.inheritedEventCount, events: [...events] }))+ const resolveAgent = vi.fn(async () => ({ agent }))+ const flush = vi.fn(async (flushedSession: Session) => {+ expect(flushedSession).toBe(session)+ expect(await history.query({ taskId: target.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ expect(await task.get(target.id)).toEqual(target)+ return true+ })+ const context = new Context()+ contexts.push(context)+ const services: Record<string, unknown> = {+ agents: { currentInitiator: vi.fn(), withoutInitiator: <T>(operation: () => T): T => operation() },+ sessionController: { inspect, resolveAgent },+ sessions: { flush },+ workspaceRegistry: { archivedSessionIds: [] },+ webServer: { register: () => () => {} },+ }+ for (const [name, value] of Object.entries(services))+ context.provide(name, value)+ context.accessor('loader', { get: () => ({ import: vi.fn(async () => llmModule), unwrapExports: (value: unknown) => value }) })+ disposers.push(server(context))+ return { session, events, appendInbox, appendMessage, agent, followup, inspect, resolveAgent, flush }+}++async function prepare(message: UserMessage): Promise<PendingDelivery> {+ await storage.setItem('tasks', { version: 2, tasks: [structuredClone(target)] })+ const pending: PendingDelivery = { task: target, trigger: 'schedule', scheduledAt: due, deliveredAt: due, message }+ await history.prepare(pending)+ resetWriteQueue()+ expect(runtime.pending.size).toBe(0)+ return pending+}++async function assertCompleted(message: UserMessage): Promise<void> {+ await expect(history.pending(target.id)).resolves.toEqual([])+ await expect(history.journals(target.id)).resolves.toEqual([])+ expect(runtime.pending.size).toBe(0)+ expect(runtime.flushes.size).toBe(0)+ const page = await history.query({ taskId: target.id, limit: 10 })+ expect(page).toMatchObject({ ok: true, records: [{ id: message.id, messageId: message.id, scheduledAt: due, deliveredAt: now }], runs: [] })+ if (!page.ok)+ throw new Error(page.error)+ expect(page.records).toHaveLength(1)+ expect(await task.get(target.id)).toMatchObject({ status: 'inactive', lastRunAt: now })+ expect(await task.get(target.id)).not.toHaveProperty('nextRunAt')+ await scheduler.tick()+ expect(await history.query({ taskId: target.id, limit: 10 })).toEqual(page)+}++beforeEach(async () => {+ vi.clearAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(now))+ await storage.clear()+})++afterEach(async () => {+ disposers.splice(0).forEach(dispose => dispose())+ await Promise.all(contexts.splice(0).map(context => context.fiber.dispose()))+ await storage.clear()+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('durable delivery identity after cold Session recovery', () => {+ it('recognizes a consumed user/message with data.id and no inbox event, then flushes one original receipt without followup', async () => {+ const host = createHarness()+ const message = createMessage()+ await prepare(message)+ const event = host.appendMessage(message)+ expect(event.data.id).toBe(message.id)+ expect(event.data).not.toHaveProperty('message')+ expect(host.events.map(item => item.type)).toEqual(['user/message'])+ await expect(delivery.run(target, 'schedule', due)).resolves.toEqual({ ok: true })+ await assertCompleted(message)+ expect(host.inspect).toHaveBeenCalledWith(sessionId)+ expect(host.resolveAgent).toHaveBeenCalledWith(sessionId)+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(host.session.deriveMessages().filter(item => item.id === message.id)).toHaveLength(1)+ })++ it('does not confuse equal prompt content with a different user/message id and admits the original pending identity once', async () => {+ const host = createHarness()+ const message = createMessage()+ const differentMessage = createMessage()+ expect(differentMessage.id).not.toBe(message.id)+ expect(differentMessage.content).toEqual(message.content)+ await prepare(message)+ host.appendMessage(differentMessage)+ await expect(delivery.run(target, 'schedule', due)).resolves.toEqual({ ok: true })+ await assertCompleted(message)+ expect(host.followup).toHaveBeenCalledExactlyOnceWith(message)+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(host.events).toMatchObject([+ { type: 'user/message', data: { id: differentMessage.id } },+ { type: 'agent/inbox/spliced', data: { inserted: [{ id: message.id }] } },+ ])+ })++ it('recognizes the original identity still in a busy agent inbox and flushes without another followup or turn mutation', async () => {+ const host = createHarness()+ const message = createMessage()+ await prepare(message)+ const event = host.appendInbox(message)+ expect(event.data.inserted[0]?.id).toBe(message.id)+ expect(host.events.map(item => item.type)).toEqual(['agent/inbox/spliced'])+ await expect(delivery.run(target, 'schedule', due)).resolves.toEqual({ ok: true })+ await assertCompleted(message)+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(host.agent.whenIdle).not.toHaveBeenCalled()+ expect(host.agent.steer).not.toHaveBeenCalled()+ expect(host.agent.inject).not.toHaveBeenCalled()+ expect(host.events).toHaveLength(1)+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/service/delivery.ts b/packages/dsh-tauri-scheduler/src/host/service/delivery.tsnew file mode 100644index 00000000..b6b3b324--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/delivery.ts@@ -0,0 +1,160 @@+import type { SessionController } from '@deepseek-ai/dsh-api-session-controller'+import type { SessionEvent } from '@deepseek-ai/dsh-session'+import type { HostContext, OperationResult, RunTrigger, SchedulerTask } from '../types'+import type { PlatformModuleLoader } from '../utils/agent-runtime.types'+import { getServerContext } from 'dsh-h3/utils'+import { defineService } from 'dsh-tauri'+import { runtime } from '../config/runtime'+import { server } from '../server'+import { isSchedulerSessionNotFound, loadSchedulerMessageFactory } from '../utils/agent-runtime'+import { nextFutureOccurrence } from '../utils/occurrence'+import { SessionOperationTimeout, withSessionDeadline } from '../utils/session-deadline'+import { sameTaskRecord } from '../utils/task-record'+import { history } from './history'+import { task } from './task'++export const delivery = defineService({+ async run(target: SchedulerTask, trigger: RunTrigger, scheduledAt: string): Promise<OperationResult> {+ const ctx = getServerContext<HostContext>(server)+ if (typeof ctx.sessionController?.resolveAgent !== 'function' || typeof ctx.sessionController?.inspect !== 'function' || typeof ctx.sessions?.flush !== 'function')+ return { ok: false, error: '宿主无法恢复或持久化目标会话', code: 'session_unavailable' }+ let pending = runtime.pending.get(target.id) ?? (await history.pending(target.id))[0]+ let enqueued = runtime.pending.has(target.id)+ if (pending && !enqueued) {+ try {+ const inspected = await withSessionDeadline<Awaited<ReturnType<SessionController['inspect']>>>(ctx.sessionController.inspect(pending.task.sessionId!))+ enqueued = containsMessage(inspected.events, pending.message.id)+ }+ catch (error) {+ if (error instanceof SessionOperationTimeout)+ return { ok: false, error: error.message, code: 'session_unavailable' }+ return await isSchedulerSessionNotFound(ctx.loader, error)+ ? { ok: false, error: '目标会话不存在', code: 'session_not_found' }+ : { ok: false, error: '宿主无法读取目标会话', code: 'session_unavailable' }+ }+ }+ const snapshot = pending?.task ?? target+ const occurrence = pending?.scheduledAt ?? scheduledAt+ const runTrigger = pending?.trigger ?? trigger+ if (!enqueued) {+ const allowed = await canEnqueue(snapshot, runTrigger, occurrence)+ if (allowed === 'changed') {+ if (pending)+ await history.discardPending(target.id)+ return { ok: true }+ }+ if (allowed === 'future')+ return { ok: false, error: '计划尚未到期', code: 'delivery_not_due' }+ }+ const bound = await task.validateTarget(snapshot)+ if (!bound.ok)+ return bound+ let resolved: Awaited<ReturnType<SessionController['resolveAgent']>>+ try {+ resolved = await withSessionDeadline<Awaited<ReturnType<SessionController['resolveAgent']>>>(ctx.sessionController.resolveAgent(snapshot.sessionId!))+ }+ catch (error) {+ if (error instanceof SessionOperationTimeout)+ return { ok: false, error: error.message, code: 'session_unavailable' }+ throw error+ }+ if ('error' in resolved)+ return { ok: false, error: resolved.error.message, code: resolved.error.code }+ const agent = resolved.agent+ const rechecked = await task.validateTarget(snapshot)+ if (!rechecked.ok)+ return rechecked+ if (agent.session?.id !== snapshot.sessionId)+ return { ok: false, error: '恢复的会话与任务绑定不匹配', code: 'session_mismatch' }+ if (!enqueued) {+ const allowed = await canEnqueue(snapshot, runTrigger, occurrence)+ if (allowed === 'changed') {+ if (pending)+ await history.discardPending(target.id)+ return { ok: true }+ }+ if (allowed === 'future')+ return { ok: false, error: '计划尚未到期', code: 'delivery_not_due' }+ }+ if (!pending) {+ const createMessage = await loadSchedulerMessageFactory(ctx.loader as PlatformModuleLoader)+ const message = createMessage({+ content: [{ type: 'text', text: framing(target, scheduledAt) }],+ source: { kind: 'schedule', form: 'notice', summary: `Scheduled: ${target.name}`.slice(0, 120) },+ })+ if (typeof message.id !== 'string')+ throw new TypeError('SCHEDULER_MESSAGE_ID_MISSING')+ pending = { task: target, trigger, scheduledAt, deliveredAt: new Date().toISOString(), message }+ await history.prepare(pending)+ }+ if (!enqueued) {+ const allowed = await canEnqueue(snapshot, runTrigger, occurrence)+ if (allowed === 'changed') {+ await history.discardPending(target.id)+ return { ok: true }+ }+ if (allowed === 'future')+ return { ok: false, error: '计划尚未到期', code: 'delivery_not_due' }+ if (ctx.workspaceRegistry.archivedSessionIds.includes(snapshot.sessionId))+ return { ok: false, error: '目标会话已归档', code: 'session_archived' }+ agent.followup(pending.message)+ }+ runtime.pending.set(target.id, pending)+ let flush = runtime.flushes.get(pending.message.id)+ if (!flush) {+ flush = Promise.resolve(ctx.sessions.flush(agent.session))+ runtime.flushes.set(pending.message.id, flush)+ const identity = pending.message.id+ void flush.then((acknowledged) => {+ if (acknowledged !== true && runtime.flushes.get(identity) === flush)+ runtime.flushes.delete(identity)+ }, () => {+ if (runtime.flushes.get(identity) === flush)+ runtime.flushes.delete(identity)+ })+ }+ let flushed: boolean+ try {+ flushed = await withSessionDeadline(flush)+ }+ catch (error) {+ if (error instanceof SessionOperationTimeout)+ return { ok: false, error: 'Session persistence did not acknowledge the reminder', code: 'delivery_pending' }+ throw error+ }+ if (flushed !== true)+ return { ok: false, error: 'Session persistence did not acknowledge the reminder', code: 'delivery_pending' }+ pending.deliveredAt = new Date().toISOString()+ const next = pending.trigger === 'schedule' ? nextFutureOccurrence(pending.task.schedule, Date.parse(pending.scheduledAt), Date.now()) : undefined+ pending.nextRunAt = next === undefined ? undefined : new Date(next).toISOString()+ await history.commit(pending)+ await task.complete(pending.task, pending.deliveredAt, pending.nextRunAt, pending.trigger === 'schedule')+ await history.acknowledge(pending.message.id)+ runtime.flushes.delete(pending.message.id)+ runtime.pending.delete(target.id)+ return { ok: true }+ },+})++async function canEnqueue(snapshot: SchedulerTask, trigger: RunTrigger, scheduledAt: string): Promise<'ready' | 'changed' | 'future'> {+ const current = await task.get(snapshot.id)+ if (!sameTaskRecord(current, snapshot) || current?.status !== 'active' || (trigger === 'schedule' && !current.enabled))+ return 'changed'+ return trigger === 'schedule' && Date.parse(scheduledAt) > Date.now() ? 'future' : 'ready'+}++function framing(target: SchedulerTask, scheduledAt: string): string {+ return [+ '[SCHEDULE REMINDER]',+ 'This is a scheduled message from the user.',+ 'This reminder may have been queued while the session was busy. Check the current conversation before acting; do not override a newer request or repeat completed work. Ask for clarification if its context is stale.',+ `schedule_id_json: ${JSON.stringify(target.id)}`,+ `occurrence_at: ${scheduledAt}`,+ `reminder_prompt_json: ${JSON.stringify(target.prompt)}`,+ ].join('\n')+}++function containsMessage(events: readonly SessionEvent[], id: string): boolean {+ return events.some(event => (event.type === 'user/message' && event.data.id === id)+ || (event.type === 'agent/inbox/spliced' && event.data.inserted.some(message => message.id === id)))+}diff --git a/packages/dsh-tauri-scheduler/src/host/service/executor.test.ts b/packages/dsh-tauri-scheduler/src/host/service/executor.test.tsindex 3335df2c..05bdfd7f 100644--- a/packages/dsh-tauri-scheduler/src/host/service/executor.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/executor.test.ts@@ -1,25 +1,39 @@-import type { HostContext, SchedulerTask } from '../types'+import type { TurnEndReason, UserMessage } from '@deepseek-ai/dsh-session'+import type { HostContext, SchedulerRun, SchedulerTask } from '../types'+import type { SetupAgentLike } from '../utils/agent-runtime.types'+import type { SessionEventLike } from './executor.utils'+import { mkdir } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { Context } from '@deepseek-ai/cordis'+import { createUserMessage } from '@deepseek-ai/dsh-llm'+import { SessionId, SessionLogOffset, SessionStore } from '@deepseek-ai/dsh-session'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { apply } from '../apply'import { resetWriteQueue } from '../config/runtime'+import { registerSessionOrigin } from '../events/session-origin'import { server } from '../server'--import { loadSchedulerRuntimeModules } from '../utils/agent-runtime'import { executor } from './executor'import { runs } from './runs'+import { scheduler } from './scheduler'-vi.mock('../utils/agent-runtime', () => ({- loadSchedulerRuntimeModules: vi.fn(),- resolveSetupAgent: vi.fn(() => ({ session: {} })),-}))+const localRequire = createRequire(import.meta.url)+const platformRequire = createRequire(localRequire.resolve('@deepseek-ai/dsh-api-session-controller'))+const { SessionProjectionRegistry } = platformRequire('@deepseek-ai/dsh-session-projection')+const schemaModule = platformRequire('zod')-vi.mock('../utils/permission', () => ({ applyUnattendedPermission: vi.fn() }))+vi.mock('node:fs/promises', async importOriginal => ({+ ...await importOriginal<typeof import('node:fs/promises')>(),+ mkdir: vi.fn(),+}))vi.mock('./runs', () => ({- runs: { save: vi.fn(async () => undefined), load: vi.fn(async () => null) },+ runs: { save: vi.fn(), load: vi.fn() },}))const taskFixture: SchedulerTask = {id: 'task-1',+ delivery: 'new-session',+ status: 'active',name: 'nightly',schedule: { kind: 'interval', everyMinutes: 30, timeZone: 'UTC' },prompt: 'run the nightly job',@@ -30,151 +44,565 @@ const taskFixture: SchedulerTask = {}const disposers: Array<() => void> = []+const contexts: Context[] = []+const records = new Map<string, SchedulerRun>()-interface Harness {+interface AgentInput {+ sessionId: string+ meta: { cwd: string, agentPreset: string }+ agentOptions: { provider?: string, model?: string }+ setup: (agentCtx: unknown, createdAgent?: SetupAgentLike) => Promise<void>+}++interface RunControl {+ session: { id: string, seq: number, snapshotEvents: () => readonly SessionEventLike[] }+ agentContext: object+ followup: ReturnType<typeof vi.fn>cancel: ReturnType<typeof vi.fn>- flush: ReturnType<typeof vi.fn>- converge: () => void+ converge: (reason?: Record<string, unknown>) => voidfailConvergence: (error: unknown) => void}-/** 首轮 `whenIdle()` 兑现(进入 followup);次轮由 `converge()` / `failConvergence()` 决定收敛结果。 */-function installHost(): Harness {- const cancel = vi.fn()- const flush = vi.fn(async () => undefined)- const session = {- seq: 0,- snapshotEvents: () => [{ seq: 1, type: 'turn/end', data: { reason: { kind: 'aborted' } } }],+function installHost(nativeSessions?: SessionStore) {+ const controls: RunControl[] = []+ const listeners = new Set<(target: unknown, event: SessionEventLike) => void>()+ const stopWatch = vi.fn()+ const flush = vi.fn<(session: unknown) => Promise<boolean>>(async () => true)+ const mount = vi.fn<(agentCtx: unknown, preset: string) => Promise<void>>(async () => {})+ const rename = vi.fn()+ const permissions = { defaultPreset: 'read-only', set: vi.fn() }+ const defaultSelection = { provider: 'default-provider', model: 'default-model', reasoningEffort: 'medium' }+ const workspace = { path: '/tmp/ws', status: vi.fn(async () => 'ok'), attachSession: vi.fn(async () => {}) }+ const getWorkspace = vi.fn((id: string) => id === 'ws-1' ? workspace : undefined)+ const runtime = {+ createUserMessage: vi.fn<(input: Parameters<typeof createUserMessage>[0]) => unknown>(input => ({ runtime: 'host', input })),+ installModelSelection: vi.fn<(agentCtx: unknown, selection: unknown) => () => void>(() => () => {}),+ setApprovalPolicy: vi.fn(),}- let idleCalls = 0- let releaseIdle: () => void = () => {}- let rejectIdle: (error: unknown) => void = () => {}- const idleGate = new Promise<void>((resolve, reject) => {- releaseIdle = resolve- rejectIdle = reject+ const modules = new Map<string, unknown>([+ ['@deepseek-ai/dsh-agent', { installModelSelection: runtime.installModelSelection, default: {} }],+ ['@deepseek-ai/dsh-llm', { createUserMessage: runtime.createUserMessage, default: {} }],+ ['@deepseek-ai/dsh-user-approval', { setApprovalPolicy: runtime.setApprovalPolicy, default: {} }],+ ])+ const loader = {+ import: vi.fn(async (name: string) => modules.get(name)),+ unwrapExports: vi.fn((value: unknown) => (value as { default?: unknown })?.default),+ }+ const create = vi.fn(async (input: AgentInput) => {+ const events: SessionEventLike[] = []+ const nativeSession = nativeSessions?.create(SessionId(input.sessionId), { meta: input.meta })+ const memorySession = { id: input.sessionId, seq: 0, snapshotEvents: vi.fn(() => events) }+ const session = nativeSession ?? memorySession+ const agentContext = Object.defineProperty({}, 'agent', {+ get(): never {+ throw new Error('cannot get property "agent" without inject')+ },+ })+ let releaseIdle: () => void = () => {}+ let rejectIdle: (error: unknown) => void = () => {}+ const idle = new Promise<void>((resolve, reject) => {+ releaseIdle = resolve+ rejectIdle = reject+ })+ const emit = (event: SessionEventLike) => {+ events.push(event)+ for (const listener of listeners) listener(session, event)+ }+ const followup = vi.fn((message: UserMessage) => {+ if (nativeSession) {+ emit(nativeSession.append('turn/start', { turn: 0 }))+ emit(nativeSession.append('user/message', message, { surfaceOp: 'append' }))+ return+ }+ memorySession.seq += 1+ emit({ seq: memorySession.seq, type: 'turn/start', data: {} })+ })+ const cancel = vi.fn()+ controls.push({+ session: session as RunControl['session'],+ agentContext,+ followup,+ cancel,+ converge: (reason = { kind: 'completed' }) => {+ if (nativeSession) {+ emit(nativeSession.append('turn/end', { turn: 0, reason: reason as TurnEndReason }))+ }+ else {+ memorySession.seq += 1+ emit({ seq: memorySession.seq, type: 'turn/end', data: { reason } })+ }+ releaseIdle()+ },+ failConvergence: rejectIdle,+ })+ await input.setup(agentContext, { session })+ return { agent: { session, followup, cancel, whenIdle: vi.fn().mockResolvedValueOnce(undefined).mockReturnValue(idle) } }})+ const withoutInitiator = vi.fn(async (fn: () => Promise<unknown>) => fn())const host = {- loader: {},- workspaceRegistry: { get: () => ({ path: '/tmp/ws', status: async () => 'ok' }) },+ loader,+ workspaceRegistry: { get: getWorkspace },sessions: { flush },- agents: {- create: async (input: { setup: (agentCtx: unknown, createdAgent: unknown) => Promise<void> }) => {- await input.setup({}, undefined)- return {- agent: {- session,- whenIdle: () => {- idleCalls += 1- return idleCalls === 1 ? Promise.resolve() : idleGate- },- // followup 之后 seq 才增长:waitForTurnStart 立即判定「已启动」,不进入 10ms 轮询。- followup: vi.fn(() => {- session.seq += 1- }),- cancel,- },- }- },- },+ agents: { create, withoutInitiator },+ agentPresets: { mount },+ permissionPresets: permissions,+ get: (name: string) => name === 'agentDefaultModel'+ ? { currentSelection: () => defaultSelection }+ : name === 'sessionTitle' ? { rename } : undefined,+ on: vi.fn((_name: string, listener: (target: unknown, event: SessionEventLike) => void) => {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ stopWatch()+ }+ }),}disposers.push(server({ ...host, webServer: { register: () => () => {} } } as unknown as HostContext))- return { cancel, flush, converge: releaseIdle, failConvergence: rejectIdle }+ return { controls, create, withoutInitiator, flush, mount, rename, permissions, defaultSelection, workspace, getWorkspace, loader, runtime, stopWatch }}beforeEach(() => {- vi.mocked(loadSchedulerRuntimeModules).mockResolvedValue({- createUserMessage: (input: unknown) => input,- installModelSelection: vi.fn(),- setApprovalPolicy: vi.fn(),- } as never)+ vi.useFakeTimers()+ vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))+ records.clear()+ vi.mocked(mkdir).mockReset().mockResolvedValue(undefined)+ vi.mocked(runs.save).mockReset().mockImplementation(async (run) => {+ records.set(run.id, structuredClone(run))+ })+ vi.mocked(runs.load).mockReset().mockImplementation(async (id) => {+ const run = records.get(id)+ return run ? structuredClone(run) : null+ })})-afterEach(() => {+afterEach(async () => {disposers.splice(0).forEach(dispose => dispose())+ for (const context of contexts.splice(0))+ await context.fiber.dispose()resetWriteQueue()+ vi.useRealTimers()+ vi.unstubAllEnvs()+ vi.restoreAllMocks()})describe('executor.run', () => {- it('运行超时会取消 agent,并在其收敛后按 timeout 判失败落盘', async () => {- vi.mocked(runs.load).mockResolvedValue({ id: 'run-1' } as never)- vi.useFakeTimers()- try {- const { cancel, flush, converge } = installHost()- const pending = executor.run(taskFixture, 'schedule')-- await vi.advanceTimersByTimeAsync(0)- await vi.advanceTimersByTimeAsync(30 * 60 * 1000)-- expect(cancel).toHaveBeenCalledWith({ kind: 'hook', reason: 'scheduler run timeout' })- expect(runs.save).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-1', trigger: 'schedule', status: 'running' }))-- converge()- const outcome = await pending-- expect(flush).toHaveBeenCalledWith(expect.objectContaining({ seq: 1 }))- expect(outcome).toEqual({- ok: false,- sessionId: expect.any(String),- error: '定时任务超过最大运行时限。',- })- expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({- status: 'failed',- error: '定时任务超过最大运行时限。',- }))- }- finally {- vi.useRealTimers()- }+ it.each(['schedule', 'manual'] as const)('keeps %s execution origin in native session projections after replay and outside run history', async (trigger) => {+ const context = new Context()+ contexts.push(context)+ const sessions = new SessionStore(context)+ const projections = new SessionProjectionRegistry(context)+ const stopOrigin = await registerSessionOrigin({+ loader: { import: async () => schemaModule },+ sessionProjections: projections,+ })+ const host = installHost(sessions)+ host.runtime.createUserMessage.mockImplementation(createUserMessage)+ const pending = executor.run(taskFixture, trigger, '2025-12-31T23:30:00.000Z')+ await vi.advanceTimersByTimeAsync(0)+ const control = host.controls[0]!+ control.converge()+ await expect(pending).resolves.toMatchObject({ ok: true, sessionId: control.session.id })++ const session = sessions.get(SessionId(control.session.id))!+ expect(session.header.origin).toBeUndefined()+ expect(projections.snapshot(session).values).toMatchObject({ 'dsh-tauri-scheduler.origin': true })+ const events = session.snapshotEvents()+ const checkpoint = projections.checkpoint(session)+ records.clear()+ expect(projections.viewCheckpoint(checkpoint)).toMatchObject({ 'dsh-tauri-scheduler.origin': true })+ expect(projections.restore({}, events, SessionLogOffset(0), session.header, SessionLogOffset(0)).snapshot.values).toMatchObject({ 'dsh-tauri-scheduler.origin': true })++ const reminder = sessions.create(SessionId(`reminder-${trigger}`))+ reminder.append('user/message', createUserMessage({ content: [{ type: 'text', text: 'this-session reminder' }], source: { kind: 'schedule' } }), { surfaceOp: 'append' })+ expect(projections.snapshot(reminder).values).toMatchObject({ 'dsh-tauri-scheduler.origin': false })+ const fork = sessions.create(SessionId(`fork-${trigger}`), { seed: events, inheritedEventCount: SessionLogOffset(events.length), meta: { parentSession: session.id, isSeeded: true } })+ expect(projections.snapshot(fork).values).toMatchObject({ 'dsh-tauri-scheduler.origin': false })+ stopOrigin()+ expect(projections.snapshot(session).values).not.toHaveProperty('dsh-tauri-scheduler.origin')})- it('取消后 agent 未能收敛时报 cancel_convergence_timeout,且不冲刷日志', async () => {- vi.mocked(runs.load).mockResolvedValue({ id: 'run-2' } as never)- vi.useFakeTimers()- try {- const { cancel, flush, failConvergence } = installHost()- const pending = executor.run(taskFixture, 'schedule')-- await vi.advanceTimersByTimeAsync(0)- await vi.advanceTimersByTimeAsync(30 * 60 * 1000)- expect(cancel).toHaveBeenCalledWith({ kind: 'hook', reason: 'scheduler run timeout' })- expect(flush).not.toHaveBeenCalled()-- failConvergence(new Error('cancel did not converge'))- const outcome = await pending-- expect(flush).not.toHaveBeenCalled()- expect(outcome).toEqual({- ok: false,- sessionId: expect.any(String),- error: '定时任务取消后未能在安全时限内停止。',- })- expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({- status: 'failed',- error: '定时任务取消后未能在安全时限内停止。',- }))- }- finally {- vi.useRealTimers()- }+ it('registers origin before starting the scheduler and owns late optional capability lifecycle', async () => {+ const context = new Context()+ contexts.push(context)+ const register = vi.fn(() => vi.fn())+ const start = vi.spyOn(scheduler, 'start').mockImplementation(() => {+ expect(register).toHaveBeenCalledTimes(1)+ return async () => {}+ })+ context.accessor('loader', { get: () => ({ import: vi.fn(async () => schemaModule) }) })+ await context.plugin({ name: 'origin-host', apply(ctx) {+ ctx.provide('tools', { register: vi.fn() })+ ctx.provide('webServer', { register: () => () => {} })+ ctx.provide('sessionProjections', { register })+ } })+ const mounted = await context.plugin({ name: 'scheduler-origin', inject: ['tools', 'webServer'], apply })+ expect(start).toHaveBeenCalledTimes(1)+ await mounted.dispose()+ expect(register.mock.results[0]!.value).toHaveBeenCalledTimes(1)++ const late = new Context()+ contexts.push(late)+ const stopOrigin = vi.fn()+ const registerLate = vi.fn(() => stopOrigin)+ const stopRuntime = vi.fn(async () => {})+ start.mockImplementation(() => stopRuntime)+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ late.accessor('loader', { get: () => ({ import: vi.fn(async () => schemaModule) }) })+ await late.plugin({ name: 'late-origin-host', apply(ctx) {+ ctx.provide('tools', { register: vi.fn() })+ ctx.provide('webServer', { register: () => () => {} })+ } })+ const waiting = await late.plugin({ name: 'scheduler-late-origin', inject: ['tools', 'webServer'], apply })+ expect(console.warn).toHaveBeenCalledWith('[scheduler origin] Public session projection unavailable; source marks disabled until declared.')+ expect(start).toHaveBeenCalledTimes(2)+ const provider = await late.plugin({ name: 'late-projections', apply(ctx) {+ ctx.provide('sessionProjections', { register: registerLate })+ } })+ await vi.advanceTimersByTimeAsync(0)+ expect(registerLate).toHaveBeenCalledTimes(1)+ await provider.dispose()+ expect(stopOrigin).toHaveBeenCalledTimes(1)+ expect(stopRuntime).not.toHaveBeenCalled()+ await waiting.dispose()+ expect(stopRuntime).toHaveBeenCalledTimes(1)})- it('插件卸载抛 INACTIVE_EFFECT 时记为 cancelled,不当作执行失败', async () => {- vi.mocked(runs.load).mockResolvedValue({ id: 'run-3' } as never)- installHost()- vi.mocked(loadSchedulerRuntimeModules).mockRejectedValueOnce(- Object.assign(new Error('inactive effect'), { code: 'INACTIVE_EFFECT' }),- )-- const outcome = await executor.run(taskFixture, 'schedule')-- expect(outcome).toEqual({- ok: false,- sessionId: expect.any(String),- error: '定时任务因插件卸载被取消。',+ it('fails safe when native origin projection registration is unavailable', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const register = vi.fn()+ const dispose = await registerSessionOrigin({ loader: { import: vi.fn(async () => {+ throw new Error('schema unavailable')+ }) }, sessionProjections: { register } })+ expect(register).not.toHaveBeenCalled()+ expect(console.warn).toHaveBeenCalledWith('[scheduler origin] Public session projection unavailable; source marks disabled.', expect.objectContaining({ message: 'schema unavailable' }))+ expect(() => dispose()).not.toThrow()+ })++ it('定时运行保存实际到期时间,startedAt 使用启动时间', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'schedule', '2025-12-31T23:30:00.000Z')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: true })++ expect(runs.save).toHaveBeenNthCalledWith(1, expect.objectContaining({+ trigger: 'schedule',+ scheduledFor: '2025-12-31T23:30:00.000Z',+ startedAt: '2026-01-01T00:00:00.000Z',+ }), taskFixture)+ expect(host.runtime.createUserMessage).toHaveBeenCalledWith({+ content: [{ type: 'text', text: 'run the nightly job' }],+ source: { kind: 'scheduler', taskId: 'task-1', runId: expect.stringMatching(/^run-/), scheduledFor: '2025-12-31T23:30:00.000Z' },+ })+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ scheduledFor: '2025-12-31T23:30:00.000Z', status: 'succeeded' }))+ })++ it('定时运行未显式传到期时间时使用任务 nextRunAt', async () => {+ const host = installHost()+ const pending = executor.run({ ...taskFixture, nextRunAt: '2025-12-31T23:00:00.000Z' }, 'schedule')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await pending++ expect(runs.save).toHaveBeenNthCalledWith(1, expect.objectContaining({+ scheduledFor: '2025-12-31T23:00:00.000Z',+ startedAt: '2026-01-01T00:00:00.000Z',+ }), { ...taskFixture, nextRunAt: '2025-12-31T23:00:00.000Z' })+ })++ it('手动运行的到期时间始终取当前时间', async () => {+ const host = installHost()+ const pending = executor.run({ ...taskFixture, nextRunAt: '2025-12-31T23:00:00.000Z' }, 'manual', '2025-12-31T23:30:00.000Z')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await pending++ expect(runs.save).toHaveBeenNthCalledWith(1, expect.objectContaining({+ trigger: 'manual',+ scheduledFor: '2026-01-01T00:00:00.000Z',+ startedAt: '2026-01-01T00:00:00.000Z',+ }), { ...taskFixture, nextRunAt: '2025-12-31T23:00:00.000Z' })+ expect(host.runtime.createUserMessage).toHaveBeenCalledWith(expect.objectContaining({+ source: expect.objectContaining({ scheduledFor: '2026-01-01T00:00:00.000Z' }),+ }))+ })++ it('新会话保存并发送运行开始时的 prompt,不受任务后续更新影响', async () => {+ const host = installHost()+ const target = { ...taskFixture }+ const pending = executor.run(target, 'manual')+ target.prompt = 'edited after launch'+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await pending++ expect(runs.save).toHaveBeenNthCalledWith(1, expect.objectContaining({ prompt: 'run the nightly job' }), taskFixture)+ expect(host.runtime.createUserMessage).toHaveBeenCalledWith(expect.objectContaining({+ content: [{ type: 'text', text: 'run the nightly job' }],+ }))+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ prompt: 'run the nightly job' }))+ })++ it('新会话使用宿主 runtime 和 scoped Agent 装配独立模型、权限及 preset', async () => {+ const host = installHost()+ const pending = executor.run({+ ...taskFixture,+ provider: 'task-provider',+ model: 'task-model',+ reasoningEffort: 'high',+ permission: 'workspace-write',+ agentPreset: ' custom ',+ }, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ const control = host.controls[0]!+ control.converge()+ await expect(pending).resolves.toMatchObject({ ok: true, sessionId: control.session.id, model: 'task-model' })++ expect(host.loader.import.mock.calls).toEqual([+ ['@deepseek-ai/dsh-agent'],+ ['@deepseek-ai/dsh-llm'],+ ['@deepseek-ai/dsh-user-approval'],+ ])+ expect(host.loader.unwrapExports).not.toHaveBeenCalled()+ expect(host.withoutInitiator).toHaveBeenCalledTimes(1)+ expect(host.create).toHaveBeenCalledWith(expect.objectContaining({+ sessionId: control.session.id,+ meta: { cwd: '/tmp/ws', agentPreset: 'custom' },+ agentOptions: { provider: 'task-provider', model: 'task-model' },+ }))+ expect(host.mount).toHaveBeenCalledTimes(1)+ expect(host.mount.mock.calls[0]![0]).toBe(control.agentContext)+ expect(host.mount.mock.calls[0]![1]).toBe('custom')+ expect(host.runtime.installModelSelection).toHaveBeenCalledTimes(1)+ expect(host.runtime.installModelSelection.mock.calls[0]![0]).toBe(control.agentContext)+ expect(host.runtime.installModelSelection.mock.calls[0]![1]).toEqual({+ current: { provider: 'task-provider', model: 'task-model', reasoningEffort: 'high' },+ assembled: undefined,})- expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({- status: 'cancelled',- error: '定时任务因插件卸载被取消。',+ expect(host.permissions.set).toHaveBeenCalledWith(control.session, 'workspace-write')+ expect(host.runtime.setApprovalPolicy).toHaveBeenCalledWith(control.session, 'never')+ expect(host.workspace.attachSession).toHaveBeenCalledWith(control.session.id)+ expect(host.rename).toHaveBeenCalledWith(control.session, 'nightly')+ expect(control.followup.mock.calls[0]![0]).toBe(host.runtime.createUserMessage.mock.results[0]!.value)+ })++ it('未指定资源时使用宿主默认模型、权限与 standard preset', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ const control = host.controls[0]!+ control.converge()+ await pending++ expect(host.create).toHaveBeenCalledWith(expect.objectContaining({+ meta: { cwd: '/tmp/ws', agentPreset: 'standard' },+ agentOptions: { provider: 'default-provider', model: 'default-model' },}))+ expect(host.runtime.installModelSelection.mock.calls[0]![0]).toBe(control.agentContext)+ expect(host.runtime.installModelSelection.mock.calls[0]![1]).toEqual({+ current: { provider: 'default-provider', model: 'default-model', reasoningEffort: 'medium' },+ assembled: undefined,+ })+ expect(host.permissions.set).toHaveBeenCalledWith(control.session, 'read-only')+ expect(host.runtime.setApprovalPolicy).toHaveBeenCalledWith(control.session, 'never')+ })++ it('并行运行的 run、session、资源设置与收尾状态互不污染', async () => {+ const host = installHost()+ const secondWorkspace = { ...host.workspace, path: '/tmp/second', attachSession: vi.fn(async () => {}) }+ host.getWorkspace.mockImplementation(id => id === 'ws-2' ? secondWorkspace : host.workspace)+ const first = executor.run({ ...taskFixture, permission: 'read-only', provider: 'p-1', model: 'm-1', reasoningEffort: 'low' }, 'schedule')+ const second = executor.run({ ...taskFixture, id: 'task-2', workspaceId: 'ws-2', permission: 'danger-full-access', provider: 'p-2', model: 'm-2', reasoningEffort: 'high' }, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ expect(host.controls).toHaveLength(2)+ const [one, two] = host.controls as [RunControl, RunControl]+ expect(one.session.id).not.toBe(two.session.id)+ expect(records.size).toBe(2)+ expect(new Set([...records.values()].map(run => run.id)).size).toBe(2)+ expect(host.create).toHaveBeenNthCalledWith(1, expect.objectContaining({ meta: { cwd: '/tmp/ws', agentPreset: 'standard' }, agentOptions: { provider: 'p-1', model: 'm-1' } }))+ expect(host.create).toHaveBeenNthCalledWith(2, expect.objectContaining({ meta: { cwd: '/tmp/second', agentPreset: 'standard' }, agentOptions: { provider: 'p-2', model: 'm-2' } }))+ expect(host.runtime.installModelSelection.mock.calls[0]![0]).toBe(one.agentContext)+ expect(host.runtime.installModelSelection.mock.calls[0]![1]).toEqual({ current: { provider: 'p-1', model: 'm-1', reasoningEffort: 'low' }, assembled: undefined })+ expect(host.runtime.installModelSelection.mock.calls[1]![0]).toBe(two.agentContext)+ expect(host.runtime.installModelSelection.mock.calls[1]![1]).toEqual({ current: { provider: 'p-2', model: 'm-2', reasoningEffort: 'high' }, assembled: undefined })+ expect(host.permissions.set.mock.calls).toEqual([[one.session, 'read-only'], [two.session, 'danger-full-access']])++ two.converge()+ await expect(second).resolves.toMatchObject({ ok: true, sessionId: two.session.id, model: 'm-2' })+ expect([...records.values()].find(run => run.taskId === 'task-1')).toMatchObject({ status: 'running' })+ one.converge({ kind: 'error', error: { code: 'first_failed', message: 'first failed' } })+ await expect(first).resolves.toMatchObject({ ok: false, sessionId: one.session.id, error: 'first failed' })+ expect([...records.values()].find(run => run.taskId === 'task-1')).toMatchObject({ status: 'failed', error: 'first failed' })+ expect([...records.values()].find(run => run.taskId === 'task-2')).toMatchObject({ status: 'succeeded', error: undefined })+ expect(host.stopWatch).toHaveBeenCalledTimes(2)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('未绑定工作区的新会话使用隔离的 automations 目录', async () => {+ vi.stubEnv('DSH_HOME', 'C:/isolated-scheduler')+ const host = installHost()+ const pending = executor.run({ ...taskFixture, workspaceId: undefined }, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: true })++ expect(mkdir).toHaveBeenCalledWith('C:/isolated-scheduler/automations', { recursive: true })+ expect(host.getWorkspace).not.toHaveBeenCalled()+ expect(host.create).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: 'C:/isolated-scheduler/automations', agentPreset: 'standard' } }))+ })++ it('目标工作区不存在时失败落盘,不创建 Agent', async () => {+ const host = installHost()+ host.getWorkspace.mockReturnValueOnce(undefined)+ await expect(executor.run(taskFixture, 'manual')).resolves.toMatchObject({ ok: false, error: '目标工作区已不存在。' })++ expect(host.create).not.toHaveBeenCalled()+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: '目标工作区已不存在。' }))+ })++ it('首次运行记录无法落盘时拒绝执行,不加载 runtime 或创建 Agent', async () => {+ const host = installHost()+ vi.mocked(runs.save).mockRejectedValueOnce(new Error('initial run write failed'))+ await expect(executor.run(taskFixture, 'manual')).rejects.toThrow('initial run write failed')++ expect(records.size).toBe(0)+ expect(host.loader.import).not.toHaveBeenCalled()+ expect(host.create).not.toHaveBeenCalled()+ })++ it('会话日志保存返回 false 时 completed 也判失败,不写成功记录', async () => {+ const host = installHost()+ host.flush.mockResolvedValueOnce(false)+ const pending = executor.run(taskFixture, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: false, error: '定时任务会话日志保存失败。' })++ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: '定时任务会话日志保存失败。' }))+ expect(runs.save).not.toHaveBeenCalledWith(expect.objectContaining({ status: 'succeeded' }))+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('会话日志保存拒绝时记录具体错误并释放运行资源', async () => {+ const host = installHost()+ host.flush.mockRejectedValueOnce(new Error('session flush unavailable'))+ const pending = executor.run(taskFixture, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: false, error: 'session flush unavailable' })++ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: 'session flush unavailable' }))+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('成功终态无法落盘时返回失败,并记录持久化错误', async () => {+ const host = installHost()+ vi.mocked(runs.save).mockImplementation(async (run) => {+ if (run.status === 'succeeded')+ throw new Error('settlement write failed')+ records.set(run.id, structuredClone(run))+ })+ const pending = executor.run(taskFixture, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: false, error: 'settlement write failed' })++ expect([...records.values()]).toEqual([expect.objectContaining({ status: 'failed', error: 'settlement write failed' })])+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('所有终态写入都失败时拒绝,保留 running 记录供崩溃恢复', async () => {+ const host = installHost()+ vi.mocked(runs.save).mockImplementation(async (run) => {+ if (run.status !== 'running')+ throw new Error('run history unavailable')+ records.set(run.id, structuredClone(run))+ })+ const pending = executor.run(taskFixture, 'manual')+ const rejected = expect(pending).rejects.toThrow('run history unavailable')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await rejected++ expect([...records.values()]).toEqual([expect.objectContaining({ status: 'running' })])+ expect(runs.save).toHaveBeenCalledTimes(3)+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('运行超时取消 Agent,宽限期内收敛后仍按 timeout 失败落盘', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'schedule')+ await vi.advanceTimersByTimeAsync(0)+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000)+ const control = host.controls[0]!+ expect(control.cancel).toHaveBeenCalledWith({ kind: 'hook', reason: 'scheduler run timeout' })+ expect(host.flush).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(5000)+ control.converge()+ await expect(pending).resolves.toMatchObject({ ok: false, sessionId: control.session.id, error: '定时任务超过最大运行时限。' })++ expect(host.flush).toHaveBeenCalledWith(control.session)+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: '定时任务超过最大运行时限。' }))+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('取消后 Agent 永不收敛时在 10 秒宽限期后失败,不冲刷日志', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'schedule')+ await vi.advanceTimersByTimeAsync(0)+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000)+ expect(host.controls[0]!.cancel).toHaveBeenCalledWith({ kind: 'hook', reason: 'scheduler run timeout' })+ expect(vi.getTimerCount()).toBe(1)+ await vi.advanceTimersByTimeAsync(9999)+ expect([...records.values()]).toEqual([expect.objectContaining({ status: 'running' })])+ expect(host.flush).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ await expect(pending).resolves.toMatchObject({ ok: false, error: '定时任务取消后未能在安全时限内停止。' })++ expect(host.flush).not.toHaveBeenCalled()+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: '定时任务取消后未能在安全时限内停止。' }))+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('取消后的收敛 Promise 拒绝时失败,不冲刷日志且清理宽限 timer', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'schedule')+ await vi.advanceTimersByTimeAsync(0)+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000)+ host.controls[0]!.failConvergence(new Error('cancel did not converge'))+ await expect(pending).resolves.toMatchObject({ ok: false, error: '定时任务取消后未能在安全时限内停止。' })++ expect(host.flush).not.toHaveBeenCalled()+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'failed', error: '定时任务取消后未能在安全时限内停止。' }))+ expect(vi.getTimerCount()).toBe(0)+ })++ it('正常执行结束后释放 deadline timer 与事件订阅,不再取消 Agent', async () => {+ const host = installHost()+ const pending = executor.run(taskFixture, 'manual')+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.converge()+ await expect(pending).resolves.toMatchObject({ ok: true })+ await vi.advanceTimersByTimeAsync(30 * 60 * 1000 + 10_000)++ expect(host.controls[0]!.cancel).not.toHaveBeenCalled()+ expect(host.flush).toHaveBeenCalledTimes(1)+ expect(host.stopWatch).toHaveBeenCalledTimes(1)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('插件卸载抛 INACTIVE_EFFECT 时记为 cancelled,不当作执行失败', async () => {+ const host = installHost()+ host.loader.import.mockRejectedValueOnce(Object.assign(new Error('inactive effect'), { code: 'INACTIVE_EFFECT' }))+ await expect(executor.run(taskFixture, 'schedule')).resolves.toMatchObject({ ok: false, error: '定时任务因插件卸载被取消。' })++ expect(host.create).not.toHaveBeenCalled()+ expect(runs.save).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'cancelled', error: '定时任务因插件卸载被取消。' }))})})diff --git a/packages/dsh-tauri-scheduler/src/host/service/executor.ts b/packages/dsh-tauri-scheduler/src/host/service/executor.tsindex efa3c427..fdd793b8 100644--- a/packages/dsh-tauri-scheduler/src/host/service/executor.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/executor.ts@@ -35,22 +35,25 @@ interface ExecuteOutcome {}export const executor = defineService({- async run(task: SchedulerTask, trigger: RunTrigger): Promise<ExecuteOutcome> {+ async run(task: SchedulerTask, trigger: RunTrigger, scheduledFor?: string): Promise<ExecuteOutcome> {const ctx = getServerContext<HostContext>(server)const runId = `run-${randomUUID()}`- const scheduledFor = new Date().toISOString()+ const startedAt = new Date().toISOString()+ const dueAt = trigger === 'manual' ? startedAt : scheduledFor ?? task.nextRunAt ?? startedAtconst sessionId = `task-${randomUUID()}`+ const prompt = task.promptawait runs.save({id: runId,taskId: task.id,taskName: task.name,+ prompt,trigger,status: 'running',- scheduledFor,- startedAt: scheduledFor,+ scheduledFor: dueAt,+ startedAt,sessionId,- })+ }, structuredClone(task))let watched: SessionEventWatch | undefinedtry {@@ -91,8 +94,8 @@ export const executor = defineService({const firstSeq = handle.agent.session.seqwatched = watchSessionEvents(ctx, handle.agent.session, firstSeq)handle.agent.followup(runtime.createUserMessage({- content: [{ type: 'text', text: task.prompt }],- source: { kind: 'scheduler', taskId: task.id, runId, scheduledFor },+ content: [{ type: 'text', text: prompt }],+ source: { kind: 'scheduler', taskId: task.id, runId, scheduledFor: dueAt },}))const started = await waitForTurnStart(handle.agent.session, firstSeq)@@ -113,7 +116,9 @@ export const executor = defineService({result = { status: 'failed', error: { code: 'cancel_convergence_timeout', message: '定时任务取消后未能在安全时限内停止。' } }}else {- await (ctx.sessions as { flush: (session: unknown) => Promise<unknown> }).flush(handle.agent.session)+ const flushed = await (ctx.sessions as { flush: (session: unknown) => Promise<unknown> }).flush(handle.agent.session)+ if (flushed === false)+ throw new Error('定时任务会话日志保存失败。')const outcome = summarizeCollectedRun(watched?.events ?? [], handle.agent.session, firstSeq)const decision = decideRunOutcome({ started, timedOut, reason: outcome.reason })@@ -254,10 +259,10 @@ async function settle(id: string, status: RunStatus, outcome: ExecuteOutcome): P})}-function settlesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {+async function settlesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {let timer: ReturnType<typeof setTimeout> | undefinedtry {- return Promise.race([+ return await Promise.race([promise.then(() => true, () => false),new Promise<false>((resolve) => { timer = setTimeout(resolve, timeoutMs, false) }),])diff --git a/packages/dsh-tauri-scheduler/src/host/service/executor.utils.test.ts b/packages/dsh-tauri-scheduler/src/host/service/executor.utils.test.tsindex 7c066522..7b80113a 100644--- a/packages/dsh-tauri-scheduler/src/host/service/executor.utils.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/executor.utils.test.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {decideRunOutcome,describeFailure,@@ -19,6 +19,11 @@ const runEvents = [const failureReason = { kind: 'error', error: { code: 'llm_error', message: 'boom' } }+afterEach(() => {+ vi.useRealTimers()+ vi.restoreAllMocks()+})+describe('decideRunOutcome', () => {it('超时优先判失败(即使 turn 已启动)', () => {expect(decideRunOutcome({ started: true, timedOut: true, reason: { kind: 'completed' } }))@@ -69,25 +74,39 @@ describe('describeFailure', () => {})describe('waitForTurnStart', () => {- it('seq 增长即返回 true', async () => {+ it('seq 已增长时立即返回 true,不分配轮询 timer', async () => {+ vi.useFakeTimers()+ await expect(waitForTurnStart({ seq: 8 }, 7, 50)).resolves.toBe(true)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('等待期间 seq 增长时在下一轮询返回 true 并释放 timer', async () => {+ vi.useFakeTimers()const session = { seq: 7 }- setTimeout(() => {- session.seq = 8- }, 15)- await expect(waitForTurnStart(session, 7, 500)).resolves.toBe(true)+ const pending = waitForTurnStart(session, 7, 50)+ await vi.advanceTimersByTimeAsync(10)+ session.seq = 8+ await vi.advanceTimersByTimeAsync(10)+ await expect(pending).resolves.toBe(true)+ expect(vi.getTimerCount()).toBe(0)})- it('始终没启动时在窗口后返回 false', async () => {+ it('始终没启动时到截止时间返回 false,之前仍保持等待', async () => {vi.useFakeTimers()- try {- const session = { seq: 7 }- const pending = waitForTurnStart(session, 7, 50)- await vi.advanceTimersByTimeAsync(80)- await expect(pending).resolves.toBe(false)- }- finally {- vi.useRealTimers()- }+ const pending = waitForTurnStart({ seq: 7 }, 7, 50)+ const settled = vi.fn()+ void pending.then(settled)+ await vi.advanceTimersByTimeAsync(49)+ expect(settled).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ await expect(pending).resolves.toBe(false)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('启动窗口为 0 时不启动轮询,立即返回 false', async () => {+ vi.useFakeTimers()+ await expect(waitForTurnStart({ seq: 7 }, 7, 0)).resolves.toBe(false)+ expect(vi.getTimerCount()).toBe(0)})})diff --git a/packages/dsh-tauri-scheduler/src/host/service/history.test.ts b/packages/dsh-tauri-scheduler/src/host/service/history.test.tsnew file mode 100644index 00000000..e8cd91dc--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/history.test.ts@@ -0,0 +1,201 @@+import type { MessageId } from '@deepseek-ai/dsh-llm'+import type { HistoryRecord, PendingDelivery, SchedulerRun, SchedulerTask } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetWriteQueue } from '../config/runtime'+import { storage } from '../storage'+import { history } from './history'+import { recovery } from './recovery'+import { runs } from './runs'++vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))++const state = new Map<string, unknown>()+const now = '2026-06-01T12:00:00.000Z'+const taskFixture: SchedulerTask = {+ id: 'task-1',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'session-1',+ name: 'reminder',+ prompt: 'original prompt',+ schedule: { kind: 'daily', time: '12:00', timeZone: 'UTC' },+ enabled: true,+ createdAt: now,+ updatedAt: now,+ nextRunAt: now,+}++function run(id: string, occurrence = now, taskId = 'task-1'): SchedulerRun {+ return { id, taskId, taskName: 'job', prompt: 'run prompt', trigger: 'schedule', status: 'succeeded', scheduledFor: occurrence, startedAt: now, finishedAt: now, sessionId: 'run-session' }+}++function pending(id: string, scheduledAt = now, taskId = 'task-1'): PendingDelivery {+ return {+ task: { ...taskFixture, id: taskId },+ trigger: 'schedule',+ scheduledAt,+ deliveredAt: now,+ nextRunAt: '2026-06-02T12:00:00.000Z',+ message: { id: id as MessageId, role: 'user', content: [{ type: 'text', text: 'framed reminder' }], source: { kind: 'schedule' } },+ }+}++beforeEach(() => {+ vi.clearAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(now))+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+})++afterEach(() => {+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('mixed occurrence history', () => {+ it.each([undefined, 0, 101, 1.5, Number.NaN, '10'])('requires an integer limit in 1..100: %j', async (limit) => {+ expect(await history.query({ limit } as never)).toMatchObject({ ok: false, code: 'history_invalid_limit' })+ expect(storage.getItem).not.toHaveBeenCalled()+ })++ it('sorts by occurrence rather than start/delivery and pages by stable identity ties', async () => {+ await history.saveRun(run('run-z', '2026-06-01T10:00:00.000Z'))+ await history.commit(pending('message-b', '2026-06-01T11:00:00.000Z'))+ await history.saveRun(run('run-a', '2026-06-01T11:00:00.000Z'))+ await history.commit(pending('message-a', '2026-06-01T11:00:00.000Z'))+ const first = await history.query({ taskId: 'task-1', limit: 2 })+ expect(first).toMatchObject({ ok: true, records: [{ id: 'run-a' }, { id: 'message-b' }], nextBefore: 'message-b', retention: { days: 30, records: 200 } })+ const second = await history.query({ taskId: 'task-1', limit: 2, before: 'message-b' })+ expect(second).toMatchObject({ ok: true, records: [{ id: 'message-a' }, { id: 'run-z' }] })+ expect(second).not.toHaveProperty('nextBefore')+ if (!first.ok)+ throw new Error(first.error)+ expect(first.runs).toEqual([run('run-a', '2026-06-01T11:00:00.000Z')])+ })++ it('rejects a missing or cross-task cursor instead of silently restarting the page', async () => {+ await history.saveRun(run('run-1'))+ await history.commit(pending('message-2', now, 'task-2'))+ expect(await history.query({ taskId: 'task-1', limit: 10, before: 'message-2' })).toMatchObject({ ok: false, code: 'delivery_cursor_not_found' })+ expect(await history.query({ taskId: 'task-1', limit: 10, before: 'missing' })).toMatchObject({ ok: false, code: 'delivery_cursor_not_found' })+ })++ it('retains actual legacy runs with unavailable metadata and no fabricated delivery', async () => {+ state.set('runs', { version: 1, runs: [run('legacy')] })+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [{ delivery: 'new-session', id: 'legacy', occurrence: now }], earlierRecordsUnavailable: true, earlierRecordsPruned: false })+ expect(state.has('history')).toBe(true)+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, earlierRecordsUnavailable: true })+ await history.commit(pending('new-message'))+ const page = await history.query({ taskId: 'task-1', limit: 10 })+ expect(page).toMatchObject({ ok: true, records: expect.arrayContaining([{ ...run('legacy'), delivery: 'new-session', occurrence: now }]), earlierRecordsUnavailable: true })+ })++ it('keeps message identity and immutable sent content in committed receipts', async () => {+ const delivery = pending('message-1')+ await history.prepare(delivery)+ expect(await history.pending('task-1')).toEqual([delivery])+ await history.commit(delivery)+ delivery.task.prompt = 'edited later'+ expect(await history.pending()).toEqual([])+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [{ id: 'message-1', messageId: 'message-1', prompt: 'original prompt', scheduledAt: now, deliveredAt: now }] })+ expect(await history.latestDelivered('task-1')).toMatchObject({ messageId: 'message-1' })+ })++ it('combines both deliveries under a per-task 200-record cap, not a global cap', async () => {+ for (let i = 0; i < 210; i++) {+ const at = new Date(Date.parse(now) - i * 60_000).toISOString()+ if (i % 2)+ await history.commit(pending(`message-${String(i).padStart(3, '0')}`, at))+ else+ await history.saveRun(run(`run-${String(i).padStart(3, '0')}`, at))+ }+ await history.saveRun(run('other-task', now, 'task-2'))+ const first = await history.query({ taskId: 'task-1', limit: 100 })+ expect(first).toMatchObject({ ok: true, earlierRecordsPruned: true })+ if (!first.ok || !first.nextBefore)+ throw new Error('missing first page')+ const second = await history.query({ taskId: 'task-1', limit: 100, before: first.nextBefore })+ if (!second.ok)+ throw new Error(second.error)+ expect(first.records).toHaveLength(100)+ expect(second.records).toHaveLength(100)+ expect(first.records[0]!.id).toBe('run-000')+ expect(second.records.at(-1)!.id).toBe('message-199')+ expect(second).not.toHaveProperty('nextBefore')+ expect(await history.query({ taskId: 'task-2', limit: 100 })).toMatchObject({ ok: true, records: [{ id: 'other-task' }], earlierRecordsPruned: false })+ const saved = state.get('history') as { records: HistoryRecord[] }+ expect(saved.records).toHaveLength(201)+ })++ it('prunes by actual receipt/run retention time and persists sticky flags on reads', async () => {+ const oldDelivery = pending('old-message', '2026-05-31T12:00:00.000Z')+ oldDelivery.deliveredAt = '2026-04-30T12:00:00.000Z'+ await history.commit(oldDelivery)+ await history.saveRun({ ...run('old-run'), startedAt: '2026-04-30T12:00:00.000Z', finishedAt: '2026-04-30T12:00:00.000Z' })+ await history.commit(pending('recent-but-late', '2025-01-01T12:00:00.000Z'))+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [{ id: 'recent-but-late' }], earlierRecordsPruned: true })+ vi.setSystemTime(new Date('2026-07-02T12:00:00.000Z'))+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [], earlierRecordsPruned: true })+ expect((state.get('history') as { records: HistoryRecord[] }).records).toEqual([])+ })++ it('recovers unfinished new-session runs without altering this-session receipts', async () => {+ await runs.save({ ...run('unfinished'), status: 'running', finishedAt: undefined })+ await history.commit(pending('receipt'))+ await recovery.recover()+ expect(await runs.load('unfinished')).toMatchObject({ status: 'interrupted', error: 'host_interrupted', finishedAt: now })+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: expect.arrayContaining([expect.objectContaining({ delivery: 'this-session', messageId: 'receipt' })]) })+ })++ it('explicit history deletion is shared by both deliveries and marks pruning', async () => {+ await history.commit(pending('receipt'))+ await runs.save(run('run'))+ expect(await history.remove('receipt')).toBe(true)+ expect(await runs.remove('run')).toBe(true)+ expect(await history.remove('absent')).toBe(false)+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [], earlierRecordsPruned: true })+ })++ it('keeps transaction journals outside history retention and explicit record deletion', async () => {+ const target: SchedulerTask = { ...taskFixture, delivery: 'new-session', sessionId: undefined }+ const running = { ...run('transaction'), status: 'running' as const, finishedAt: undefined }+ await runs.save(running, target)+ target.prompt = 'edited after initial save'+ await runs.save({ ...running, status: 'succeeded', finishedAt: now })+ expect(await history.journals('task-1')).toMatchObject([{ id: 'transaction', task: { prompt: 'original prompt' }, completedAt: now, run: { status: 'succeeded' } }])+ expect(await history.remove('transaction')).toBe(true)+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [] })+ expect(await runs.load('transaction')).toMatchObject({ status: 'succeeded' })+ vi.setSystemTime(new Date('2026-08-01T12:00:00.000Z'))+ expect(await history.journals()).toHaveLength(1)+ await history.acknowledge('transaction')+ expect(await history.journals()).toEqual([])+ })++ it('recovers a running journal whose public history entry was already pruned', async () => {+ const target: SchedulerTask = { ...taskFixture, delivery: 'new-session', sessionId: undefined }+ await runs.save({ ...run('lost-history'), status: 'running', finishedAt: undefined }, target)+ vi.setSystemTime(new Date('2026-08-01T12:00:00.000Z'))+ expect(await history.query({ taskId: 'task-1', limit: 10 })).toMatchObject({ ok: true, records: [], earlierRecordsPruned: true })+ await recovery.recover()+ expect(await history.journals()).toMatchObject([{ id: 'lost-history', completedAt: '2026-08-01T12:00:00.000Z', run: { status: 'interrupted', error: 'host_interrupted' } }])+ })++ it('accepts pre-journal version two storage without inventing transaction evidence', async () => {+ state.set('history', { version: 2, records: [], pending: [], flags: {} })+ expect(await history.journals()).toEqual([])+ expect(storage.setItem).not.toHaveBeenCalled()+ })++ it('refuses to overwrite malformed persisted history', async () => {+ state.set('history', { version: 2, records: [{ delivery: 'this-session' }], flags: {}, pending: [] })+ await expect(history.saveRun(run('new'))).rejects.toThrow('SCHEDULER_HISTORY_INVALID: refusing to overwrite malformed history')+ expect(storage.setItem).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/service/history.ts b/packages/dsh-tauri-scheduler/src/host/service/history.tsnew file mode 100644index 00000000..848e4c03--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/history.ts@@ -0,0 +1,315 @@+import type { DeliveryRecord, HistoryPage, HistoryQuery, HistoryRecord, OccurrenceJournal, OperationResult, PendingDelivery, SchedulerRun, SchedulerTask } from '../types'+import { defineService } from 'dsh-tauri'+import { runtime, withWriteQueue } from '../config/runtime'+import { storage } from '../storage'++const HISTORY_KEY = 'history'+const HISTORY_DAYS = 30+const HISTORY_RECORDS = 200+const DAY_MS = 86_400_000+const RUN_STATUSES = new Set(['queued', 'running', 'succeeded', 'failed', 'interrupted', 'skipped', 'cancelled'])+const SCHEDULER_INTERRUPTED_ERROR = 'host_interrupted'++interface RetentionFlags {+ earlierRecordsUnavailable: boolean+ earlierRecordsPruned: boolean+}++interface HistoryState {+ version: 2+ records: HistoryRecord[]+ flags: Record<string, RetentionFlags>+ pending: PendingDelivery[]+ journal: OccurrenceJournal[]+}++export const history = defineService({+ async query(query: HistoryQuery): Promise<OperationResult<HistoryPage>> {+ if (!Number.isInteger(query.limit) || query.limit < 1 || query.limit > 100)+ return { ok: false, error: 'limit 必须是 1 到 100 的整数', code: 'history_invalid_limit' }+ if ((query.taskId !== undefined && (typeof query.taskId !== 'string' || query.taskId.length === 0))+ || (query.before !== undefined && (typeof query.before !== 'string' || query.before.length === 0))) {+ return { ok: false, error: '历史查询参数无效', code: 'history_invalid_query' }+ }+ return withWriteQueue(async () => {+ const state = await loadState()+ if (prune(state))+ await saveState(state)+ const all = order(state.records.filter(record => query.taskId === undefined || record.taskId === query.taskId))+ const beforeIndex = query.before === undefined ? -1 : all.findIndex(record => record.id === query.before)+ if (query.before !== undefined && beforeIndex === -1)+ return { ok: false, error: '历史游标不存在或已被清理', code: 'delivery_cursor_not_found' }+ const offset = beforeIndex + 1+ const records = all.slice(offset, offset + query.limit)+ const flags = query.taskId === undefined ? Object.values(state.flags) : [state.flags[query.taskId] ?? emptyFlags()]+ return {+ ok: true,+ records,+ runs: records.flatMap(record => record.delivery === 'new-session' ? [asRun(record)] : []),+ ...(offset + records.length < all.length ? { nextBefore: records.at(-1)!.id } : {}),+ earlierRecordsUnavailable: flags.some(item => item.earlierRecordsUnavailable),+ earlierRecordsPruned: flags.some(item => item.earlierRecordsPruned),+ retention: { days: HISTORY_DAYS, records: HISTORY_RECORDS },+ }+ })+ },++ async listRuns(taskId?: string): Promise<SchedulerRun[]> {+ return withWriteQueue(async () => {+ const state = await loadState()+ if (prune(state))+ await saveState(state)+ return order(state.records).flatMap(record => record.delivery === 'new-session' && (taskId === undefined || record.taskId === taskId) ? [asRun(record)] : [])+ })+ },++ async saveRun(run: SchedulerRun, expected?: SchedulerTask): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ const record: HistoryRecord = { ...run, delivery: 'new-session', occurrence: run.scheduledFor }+ upsert(state, record)+ if (expected && !state.journal.some(item => item.id === run.id))+ state.journal.push({ id: run.id, task: structuredClone(expected), trigger: run.trigger, scheduledAt: run.scheduledFor })+ const journal = state.journal.find(item => item.id === run.id)+ if (journal) {+ journal.run = run+ journal.completedAt = run.status === 'queued' || run.status === 'running' ? undefined : run.finishedAt ?? run.startedAt+ }+ prune(state)+ await saveState(state)+ })+ },++ async recoverRuns(): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ const stored = state.records.flatMap(record => record.delivery === 'new-session' ? [asRun(record)] : [])+ const journalRuns = state.journal.flatMap(item => item.run ? [item.run] : [])+ let changed = false+ for (const run of new Map([...stored, ...journalRuns].map(item => [item.id, item])).values()) {+ if (run.status !== 'running' || runtime.running.has(run.taskId))+ continue+ const interrupted: SchedulerRun = { ...run, status: 'interrupted', finishedAt: new Date().toISOString(), error: run.error || SCHEDULER_INTERRUPTED_ERROR }+ upsert(state, { ...interrupted, delivery: 'new-session', occurrence: interrupted.scheduledFor })+ const journal = state.journal.find(item => item.id === run.id)+ if (journal) {+ journal.run = interrupted+ journal.completedAt = interrupted.finishedAt+ }+ changed = true+ }+ if (changed) {+ prune(state)+ await saveState(state)+ }+ })+ },++ async journals(taskId?: string): Promise<OccurrenceJournal[]> {+ return withWriteQueue(async () => (await loadState()).journal.filter(item => taskId === undefined || item.task.id === taskId))+ },++ async acknowledge(id: string): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ state.journal = state.journal.filter(item => item.id !== id)+ await saveState(state)+ })+ },++ async remove(id: string): Promise<boolean> {+ return withWriteQueue(async () => {+ const state = await loadState()+ const found = state.records.find(record => record.id === id)+ if (!found)+ return false+ state.records = state.records.filter(record => record.id !== id)+ flagsFor(state, found.taskId).earlierRecordsPruned = true+ prune(state)+ await saveState(state)+ return true+ })+ },++ async pending(taskId?: string): Promise<PendingDelivery[]> {+ return withWriteQueue(async () => {+ const state = await loadState()+ return state.pending.filter(item => taskId === undefined || item.task.id === taskId)+ })+ },++ async prepare(pending: PendingDelivery): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ if (state.pending.some(item => item.task.id === pending.task.id))+ return+ state.pending.push(pending)+ await saveState(state)+ })+ },++ async commit(pending: PendingDelivery): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ const record: DeliveryRecord = {+ id: pending.message.id,+ taskId: pending.task.id,+ taskName: pending.task.name,+ delivery: 'this-session',+ occurrence: pending.scheduledAt,+ trigger: pending.trigger,+ sessionId: pending.task.sessionId!,+ scheduledAt: pending.scheduledAt,+ deliveredAt: pending.deliveredAt,+ messageId: pending.message.id,+ prompt: pending.task.prompt,+ }+ upsert(state, record)+ if (!state.journal.some(item => item.id === record.id))+ state.journal.push({ id: record.id, task: pending.task, trigger: pending.trigger, scheduledAt: pending.scheduledAt, completedAt: pending.deliveredAt })+ state.pending = state.pending.filter(item => item.task.id !== pending.task.id)+ prune(state)+ await saveState(state)+ })+ },++ async discardPending(taskId: string): Promise<void> {+ await withWriteQueue(async () => {+ const state = await loadState()+ state.pending = state.pending.filter(item => item.task.id !== taskId)+ await saveState(state)+ })+ },++ async latestDelivered(taskId: string): Promise<DeliveryRecord | undefined> {+ return withWriteQueue(async () => {+ const state = await loadState()+ return order(state.records).find((record): record is DeliveryRecord => record.delivery === 'this-session' && record.taskId === taskId && record.trigger === 'schedule')+ })+ },+})++async function loadState(): Promise<HistoryState> {+ const saved = await storage.getItem<HistoryState>(HISTORY_KEY)+ if (saved !== null && saved !== undefined) {+ if (saved.version !== 2 || !Array.isArray(saved.records) || !saved.records.every(isRecord)+ || !Array.isArray(saved.pending) || !saved.pending.every(isPending) || !saved.flags || typeof saved.flags !== 'object'+ || (saved.journal !== undefined && (!Array.isArray(saved.journal) || !saved.journal.every(isJournal)))) {+ throw new Error('SCHEDULER_HISTORY_INVALID: refusing to overwrite malformed history')+ }+ return { ...saved, journal: saved.journal ?? [] }+ }+ const legacy = await storage.getItem<{ runs?: unknown[] }>('runs')+ const records = (Array.isArray(legacy?.runs) ? legacy.runs : []).flatMap((run) => {+ if (!isRun(run))+ return []+ return [{ ...run, delivery: 'new-session' as const, occurrence: run.scheduledFor }]+ })+ const state: HistoryState = {+ version: 2,+ records,+ pending: [],+ journal: [],+ flags: Object.fromEntries(records.map(record => [record.taskId, { earlierRecordsUnavailable: true, earlierRecordsPruned: false }])),+ }+ if (legacy !== null && legacy !== undefined) {+ prune(state)+ await saveState(state)+ }+ return state+}++async function saveState(state: HistoryState): Promise<void> {+ await storage.setItem(HISTORY_KEY, `${JSON.stringify(state, null, 2)}\n`)+}++function upsert(state: HistoryState, record: HistoryRecord): void {+ const at = state.records.findIndex(item => item.id === record.id)+ if (at === -1)+ state.records.push(record)+ else+ state.records[at] = record+ flagsFor(state, record.taskId)+}++function prune(state: HistoryState): boolean {+ const floor = Date.now() - HISTORY_DAYS * DAY_MS+ const counts = new Map<string, number>()+ const before = state.records.length+ state.records = order(state.records).filter((record) => {+ const retainedAt = record.delivery === 'this-session' ? record.deliveredAt : record.finishedAt ?? record.startedAt+ const count = counts.get(record.taskId) ?? 0+ if (Date.parse(retainedAt) < floor || count >= HISTORY_RECORDS) {+ flagsFor(state, record.taskId).earlierRecordsPruned = true+ return false+ }+ counts.set(record.taskId, count + 1)+ return true+ })+ return before !== state.records.length+}++function order(records: HistoryRecord[]): HistoryRecord[] {+ return [...records].sort((left, right) => Date.parse(right.occurrence) - Date.parse(left.occurrence) || right.id.localeCompare(left.id, 'en'))+}++function flagsFor(state: HistoryState, taskId: string): RetentionFlags {+ return state.flags[taskId] ??= emptyFlags()+}++function emptyFlags(): RetentionFlags {+ return { earlierRecordsUnavailable: false, earlierRecordsPruned: false }+}++function asRun(record: Extract<HistoryRecord, { delivery: 'new-session' }>): SchedulerRun {+ const { delivery: _delivery, occurrence: _occurrence, ...run } = record+ return run+}++function isRun(value: unknown): value is SchedulerRun {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return false+ const run = value as SchedulerRun+ return typeof run.id === 'string' && typeof run.taskId === 'string' && typeof run.taskName === 'string'+ && RUN_STATUSES.has(run.status) && (run.trigger === 'schedule' || run.trigger === 'manual')+ && validInstant(run.scheduledFor) && validInstant(run.startedAt)+ && (run.finishedAt === undefined || validInstant(run.finishedAt))+}++function isRecord(value: unknown): value is HistoryRecord {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return false+ const record = value as HistoryRecord+ if (record.delivery === 'new-session')+ return isRun(record) && validInstant(record.occurrence)+ return record.delivery === 'this-session' && typeof record.id === 'string' && typeof record.taskId === 'string'+ && typeof record.taskName === 'string' && typeof record.prompt === 'string' && typeof record.sessionId === 'string'+ && typeof record.messageId === 'string' && record.id === record.messageId && validInstant(record.occurrence)+ && validInstant(record.scheduledAt) && validInstant(record.deliveredAt) && (record.trigger === 'schedule' || record.trigger === 'manual')+}++function isPending(value: unknown): value is PendingDelivery {+ if (!value || typeof value !== 'object')+ return false+ const pending = value as PendingDelivery+ return pending.task?.delivery === 'this-session' && typeof pending.task.id === 'string' && typeof pending.task.sessionId === 'string'+ && pending.message?.role === 'user' && typeof pending.message.id === 'string'+ && validInstant(pending.scheduledAt) && validInstant(pending.deliveredAt)+ && (pending.nextRunAt === undefined || validInstant(pending.nextRunAt))+ && (pending.trigger === 'schedule' || pending.trigger === 'manual')+}++function isJournal(value: unknown): value is OccurrenceJournal {+ if (!value || typeof value !== 'object' || Array.isArray(value))+ return false+ const journal = value as OccurrenceJournal+ return typeof journal.id === 'string' && typeof journal.task?.id === 'string'+ && (journal.task.delivery === 'this-session' || journal.task.delivery === 'new-session')+ && validInstant(journal.scheduledAt) && (journal.trigger === 'schedule' || journal.trigger === 'manual')+ && (journal.completedAt === undefined || validInstant(journal.completedAt))+ && (journal.run === undefined || (isRun(journal.run) && journal.run.id === journal.id && journal.run.taskId === journal.task.id))+}++function validInstant(value: unknown): value is string {+ return typeof value === 'string' && Number.isFinite(Date.parse(value))+}diff --git a/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts b/packages/dsh-tauri-scheduler/src/host/service/recovery.test.tsindex cefb7671..f66618b9 100644--- a/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts@@ -1,17 +1,55 @@-import { beforeEach, expect, it, vi } from 'vitest'+import type { SchedulerRun } from '../types'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { resetWriteQueue, runtime } from '../config/runtime'+import { storage } from '../storage'+import { history } from './history'import { recovery } from './recovery'import { runs } from './runs'-vi.mock('./runs', () => ({ runs: { list: vi.fn(), save: vi.fn() } }))+vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))-beforeEach(() => vi.clearAllMocks())+const state = new Map<string, unknown>()+const now = '2026-06-01T12:00:00.000Z'-it('interrupts only running records and keeps their existing errors', async () => {- const records = ['running', 'failed', 'queued', 'running'].map((status, index) => ({ id: String(index), status, error: index === 3 ? 'existing' : undefined }))- vi.mocked(runs.list).mockResolvedValue(records as never)+beforeEach(() => {+ vi.clearAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(now))+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+})++afterEach(() => {+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++it('interrupts only unclaimed running records, preserves errors and leaves live records untouched', async () => {+ const records: SchedulerRun[] = ['running', 'failed', 'queued', 'running', 'running'].map((status, index) => ({ id: String(index), taskId: `task-${index}`, taskName: 'job', scheduledFor: now, startedAt: now, trigger: 'schedule', status: status as SchedulerRun['status'], ...(index === 3 ? { error: 'existing' } : {}) }))+ for (const run of records)+ await runs.save(run)+ runtime.running.add('task-4')await recovery.recover()- expect(runs.save).toHaveBeenCalledTimes(2)- expect(runs.save).toHaveBeenNthCalledWith(1, { ...records[0], status: 'interrupted', error: 'host_interrupted', finishedAt: expect.any(String) })- expect(runs.save).toHaveBeenNthCalledWith(2, { ...records[3], status: 'interrupted', finishedAt: expect.any(String) })- expect(records[0].status).toBe('running')+ expect(await runs.load('0')).toEqual({ ...records[0], status: 'interrupted', error: 'host_interrupted', finishedAt: now })+ expect(await runs.load('1')).toEqual(records[1])+ expect(await runs.load('2')).toEqual(records[2])+ expect(await runs.load('3')).toEqual({ ...records[3], status: 'interrupted', finishedAt: now })+ expect(await runs.load('4')).toEqual(records[4])+ expect(records[0]!.status).toBe('running')+ vi.mocked(storage.setItem).mockClear()+ await recovery.recover()+ expect(storage.setItem).not.toHaveBeenCalled()+})++it('serializes recovery with completion so a stale running snapshot cannot overwrite success', async () => {+ const running: SchedulerRun = { id: 'race', taskId: 'race-task', taskName: 'job', scheduledFor: now, startedAt: now, trigger: 'manual', status: 'running' }+ await runs.save(running)+ const completed = { ...running, status: 'succeeded' as const, finishedAt: now }+ await Promise.all([history.saveRun(completed), recovery.recover()])+ expect(await runs.load(running.id)).toEqual(completed)})diff --git a/packages/dsh-tauri-scheduler/src/host/service/recovery.ts b/packages/dsh-tauri-scheduler/src/host/service/recovery.tsindex 54c2902a..521a89d9 100644--- a/packages/dsh-tauri-scheduler/src/host/service/recovery.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/recovery.ts@@ -1,17 +1,9 @@import { defineService } from 'dsh-tauri'-import { runs } from './runs'--const SCHEDULER_INTERRUPTED_ERROR = 'host_interrupted'+import { withTaskQueue } from '../config/runtime'+import { history } from './history'export const recovery = defineService({async recover(): Promise<void> {- for (const run of (await runs.list()).filter(run => run.status === 'running')) {- await runs.save({- ...run,- status: 'interrupted',- finishedAt: new Date().toISOString(),- error: run.error || SCHEDULER_INTERRUPTED_ERROR,- })- }+ await withTaskQueue(() => history.recoverRuns())},})diff --git a/packages/dsh-tauri-scheduler/src/host/service/runs.ts b/packages/dsh-tauri-scheduler/src/host/service/runs.tsindex 812d3e7e..75d427c9 100644--- a/packages/dsh-tauri-scheduler/src/host/service/runs.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/runs.ts@@ -1,61 +1,21 @@-import type { SchedulerRun } from '../types'+import type { SchedulerRun, SchedulerTask } from '../types'import { defineService } from 'dsh-tauri'-import { conformsTo, filter, find, findIndex, isArray, isString, orderBy, reject, takeRight } from 'lodash-es'-import { withWriteQueue } from '../config/runtime'-import { storage } from '../storage'--const SCHEDULER_RUNS_KEY = 'runs'--const SCHEDULER_RUNS_HISTORY_LIMIT = 200+import { history } from './history'export const runs = defineService({async list(taskId?: string): Promise<SchedulerRun[]> {- const raw = await storage.getItem<{ runs?: unknown[] }>(SCHEDULER_RUNS_KEY)- const all = filter(isArray(raw?.runs) ? raw.runs : [], isRun)- return orderBy(taskId ? filter(all, { taskId }) : all, 'startedAt', 'desc')+ return history.listRuns(taskId)},async load(id: string): Promise<SchedulerRun | null> {- return find(await runs.list(), { id }) ?? null+ return (await history.listRuns()).find(run => run.id === id) ?? (await history.journals()).find(item => item.id === id)?.run ?? null},- async save(run: SchedulerRun): Promise<void> {- await withWriteQueue(async () => {- const all = await runs.list()- const at = findIndex(all, { id: run.id })- if (at === -1)- all.push(run)- else- all[at] = run- await writeRuns(takeRight(all, SCHEDULER_RUNS_HISTORY_LIMIT))- })+ async save(run: SchedulerRun, expected?: SchedulerTask): Promise<void> {+ await history.saveRun(run, expected)},async remove(id: string): Promise<boolean> {- return withWriteQueue(async () => {- const all = await runs.list()- const remaining = reject(all, { id })- if (remaining.length === all.length)- return false- await writeRuns(remaining)- return true- })+ return history.remove(id)},})--// --- internal -----function isRun(value: unknown): value is SchedulerRun {- return conformsTo(value, {- id: isString,- taskId: isString,- taskName: isString,- status: isString,- startedAt: isString,- scheduledFor: isString,- })-}--async function writeRuns(all: SchedulerRun[]): Promise<void> {- await storage.setItem(SCHEDULER_RUNS_KEY, `${JSON.stringify({ version: 1, runs: all }, null, 2)}\n`)-}diff --git a/packages/dsh-tauri-scheduler/src/host/service/scheduler.resilience.test.ts b/packages/dsh-tauri-scheduler/src/host/service/scheduler.resilience.test.tsnew file mode 100644index 00000000..7c46ea54--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/service/scheduler.resilience.test.ts@@ -0,0 +1,236 @@+import type { HostContext, OperationResult, SchedulerRun, SchedulerTask } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetWriteQueue, runtime } from '../config/runtime'+import { server } from '../server'+import { storage } from '../storage'+import { delivery } from './delivery'+import { executor } from './executor'+import { history } from './history'+import { runs } from './runs'+import { scheduler } from './scheduler'+import { task } from './task'++vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))+vi.mock('./delivery', () => ({ delivery: { run: vi.fn() } }))+vi.mock('./executor', () => ({ executor: { run: vi.fn() } }))++const NOW = '2026-06-01T12:15:00.000Z'+const DUE = '2026-06-01T12:00:00.000Z'+const state = new Map<string, unknown>()+const releases: Array<() => void> = []+const stops: Array<() => Promise<void>> = []+const disposers: Array<() => void> = []+let host: ReturnType<typeof installHost>++function installHost() {+ const listeners = new Set<symbol>()+ const logger = { warn: vi.fn() }+ const context = {+ agents: {+ withoutInitiator: vi.fn((fn: () => Promise<unknown>) => fn()),+ currentInitiator: vi.fn(() => undefined),+ },+ sessionController: { inspect: vi.fn(async (id: string) => ({ meta: { id } })) },+ workspaceRegistry: { archivedSessionIds: [] },+ on: vi.fn(() => {+ const id = Symbol('scheduler-listener')+ listeners.add(id)+ return () => listeners.delete(id)+ }),+ logger,+ webServer: { register: () => () => {} },+ }+ disposers.push(server(context as unknown as HostContext))+ return { listeners, logger }+}++function scheduledTask(deliveryMode: SchedulerTask['delivery']): SchedulerTask {+ return {+ id: 'resilience-task',+ delivery: deliveryMode,+ status: 'active',+ ...(deliveryMode === 'this-session' ? { sessionId: 'bound-session' } : {}),+ name: 'resilience reminder',+ prompt: 'perform the scheduled action',+ schedule: { kind: 'once', at: DUE, timeZone: 'UTC' },+ enabled: true,+ createdAt: '2026-05-31T12:00:00.000Z',+ updatedAt: '2026-05-31T12:00:00.000Z',+ nextRunAt: DUE,+ }+}++function seed(...items: SchedulerTask[]): void {+ state.set('tasks', { version: 2, tasks: structuredClone(items) })+}++function deferred<T>() {+ let resolve!: (value: T | PromiseLike<T>) => void+ const promise = new Promise<T>((accept) => {+ resolve = accept+ })+ return { promise, resolve }+}++function decode(value: unknown): unknown {+ return typeof value === 'string' ? JSON.parse(value) : structuredClone(value)+}++beforeEach(() => {+ vi.resetAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(NOW))+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, decode(value))+ })+ vi.mocked(delivery.run).mockResolvedValue({ ok: true })+ vi.mocked(executor.run).mockResolvedValue({ ok: true })+ host = installHost()+})++afterEach(async () => {+ for (const release of releases.splice(0))+ release()+ await vi.advanceTimersByTimeAsync(0)+ for (const stop of stops.splice(0))+ await stop()+ await scheduler.stop()+ for (const dispose of disposers.splice(0))+ dispose()+ resetWriteQueue()+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.restoreAllMocks()+})++describe('scheduler resilience', () => {+ it('coalesces periodic ticks behind a blocked delivery so the next mutation can acquire the task queue', async () => {+ seed()+ const stop = scheduler.start(1)+ stops.push(stop)+ await vi.advanceTimersByTimeAsync(0)+ expect(runtime.accepted.size).toBe(0)++ const target = scheduledTask('this-session')+ const mutationTarget: SchedulerTask = {+ ...scheduledTask('new-session'),+ id: 'queued-mutation',+ schedule: { kind: 'once', at: '2026-06-02T12:00:00.000Z', timeZone: 'UTC' },+ nextRunAt: '2026-06-02T12:00:00.000Z',+ }+ seed(target, mutationTarget)+ const pending: OperationResult = { ok: false, code: 'delivery_pending', error: 'Session persistence did not acknowledge the reminder' }+ const first = deferred<OperationResult>()+ const backlog = deferred<OperationResult>()+ releases.push(() => first.resolve(pending), () => backlog.resolve(pending))+ vi.mocked(delivery.run).mockImplementationOnce(() => first.promise).mockImplementation(() => backlog.promise)++ await vi.advanceTimersByTimeAsync(1)+ expect(delivery.run).toHaveBeenCalledWith(target, 'schedule', DUE)+ await vi.advanceTimersByTimeAsync(1000)+ expect(delivery.run).toHaveBeenCalledTimes(1)++ let mutationResult: Awaited<ReturnType<typeof task.toggle>> | undefined+ const mutation = task.toggle(mutationTarget.id, false).then((result) => {+ mutationResult = result+ return result+ })+ await vi.advanceTimersByTimeAsync(0)+ expect(mutationResult).toBeUndefined()++ first.resolve(pending)+ await vi.advanceTimersByTimeAsync(0)+ expect(mutationResult).toMatchObject({ ok: true, task: { id: mutationTarget.id, enabled: false } })+ expect(await mutation).toMatchObject({ ok: true, task: { enabled: false } })+ expect(await task.get(mutationTarget.id)).toMatchObject({ enabled: false })+ expect(delivery.run).toHaveBeenCalledTimes(1)++ await vi.advanceTimersByTimeAsync(1)+ expect(delivery.run).toHaveBeenCalledTimes(2)+ backlog.resolve(pending)+ await vi.advanceTimersByTimeAsync(0)+ await stop()+ stops.splice(stops.indexOf(stop), 1)+ expect(host.listeners.size).toBe(0)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('suppresses automatic re-execution after all terminal history writes reject until an explicit drive', async () => {+ const target = scheduledTask('new-session')+ seed(target)+ const persistenceError = new Error('terminal history write rejected')+ let rejectTerminal = true+ const terminalWrites: Array<{ id: string, status: SchedulerRun['status'] }> = []+ const createdSessions: Array<{ sessionId: string, trigger: SchedulerRun['trigger'], scheduledFor: string }> = []+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ const saved = decode(value)+ if (key === 'history' && rejectTerminal) {+ const terminal = (saved as { records: SchedulerRun[] }).records.find(record => record.status === 'succeeded' || record.status === 'failed')+ if (terminal) {+ terminalWrites.push({ id: terminal.id, status: terminal.status })+ throw persistenceError+ }+ }+ state.set(key, saved)+ })+ vi.mocked(executor.run).mockImplementation(async (accepted, trigger, scheduledFor) => {+ const sequence = createdSessions.length + 1+ const sessionId = `created-session-${sequence}`+ const run: SchedulerRun = {+ id: `accepted-run-${sequence}`,+ taskId: accepted.id,+ taskName: accepted.name,+ prompt: accepted.prompt,+ trigger,+ status: 'running',+ scheduledFor: scheduledFor!,+ startedAt: new Date().toISOString(),+ sessionId,+ }+ await runs.save(run, accepted)+ createdSessions.push({ sessionId, trigger, scheduledFor: run.scheduledFor })+ try {+ await runs.save({ ...run, status: 'succeeded', finishedAt: new Date().toISOString() })+ return { ok: true, sessionId }+ }+ catch {+ await runs.save({ ...run, status: 'failed', finishedAt: new Date().toISOString(), error: persistenceError.message })+ return { ok: false, sessionId, error: persistenceError.message }+ }+ })++ await scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ expect(terminalWrites).toEqual([+ { id: 'accepted-run-1', status: 'succeeded' },+ { id: 'accepted-run-1', status: 'failed' },+ ])+ expect(createdSessions).toEqual([{ sessionId: 'created-session-1', trigger: 'schedule', scheduledFor: DUE }])+ expect(runtime.running.has(target.id)).toBe(false)+ expect(runtime.accepted.size).toBe(0)+ expect(await task.get(target.id)).toEqual(target)+ expect(await runs.list(target.id)).toMatchObject([{ id: 'accepted-run-1', status: 'running', scheduledFor: DUE }])+ expect(await history.journals(target.id)).toMatchObject([{ id: 'accepted-run-1', run: { status: 'running' } }])+ expect(host.logger.warn).toHaveBeenCalledWith('dsh-tauri-scheduler: new-session run failed', persistenceError)++ await scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ expect(createdSessions).toHaveLength(1)+ expect(runtime.failed.has(target.id)).toBe(true)+ expect(terminalWrites).toHaveLength(2)+ expect(await task.get(target.id)).toEqual(target)++ rejectTerminal = false+ expect(await scheduler.trigger(target.id)).toEqual({ ok: true })+ await vi.advanceTimersByTimeAsync(0)+ expect(createdSessions).toEqual([+ { sessionId: 'created-session-1', trigger: 'schedule', scheduledFor: DUE },+ { sessionId: 'created-session-2', trigger: 'manual', scheduledFor: NOW },+ ])+ expect(runtime.failed.has(target.id)).toBe(false)+ expect(runtime.running.has(target.id)).toBe(false)+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/service/scheduler.test.ts b/packages/dsh-tauri-scheduler/src/host/service/scheduler.test.tsindex 9dee7a27..4d449030 100644--- a/packages/dsh-tauri-scheduler/src/host/service/scheduler.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/scheduler.test.ts@@ -1,60 +1,655 @@-import type { SchedulerTask } from '../types'-import { beforeEach, describe, expect, it, vi } from 'vitest'-import { executor } from './executor'+import type { MessageId, UserMessage } from '@deepseek-ai/dsh-llm'+import type { HostContext, SchedulerTask } from '../types'+import type { SetupAgentLike } from '../utils/agent-runtime.types'+import type { SessionEventLike } from './executor.utils'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetWriteQueue, runtime } from '../config/runtime'+import { server } from '../server'+import { storage } from '../storage'+import { history } from './history'+import { recovery } from './recovery'+import { runs } from './runs'import { scheduler } from './scheduler'import { task } from './task'-vi.mock('./executor', () => ({ executor: { run: vi.fn() } }))+vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))-vi.mock('./task', () => ({ task: { get: vi.fn(), list: vi.fn(), advance: vi.fn() } }))--const taskFixture: SchedulerTask = {+const now = '2026-06-01T12:15:00.000Z'+const due = '2026-06-01T12:00:00.000Z'+const fixture: SchedulerTask = {id: 'task-1',- name: 'nightly',- schedule: { kind: 'interval', everyMinutes: 30, timeZone: 'UTC' },- prompt: 'run the nightly job',+ delivery: 'this-session',+ status: 'active',+ sessionId: 'session-1',+ name: 'reminder',+ prompt: 'original prompt',+ schedule: { kind: 'once', at: due, timeZone: 'UTC' },enabled: true,- createdAt: '2025-12-31T00:00:00.000Z',- updatedAt: '2025-12-31T00:00:00.000Z',+ createdAt: '2026-05-31T12:00:00.000Z',+ updatedAt: '2026-05-31T12:00:00.000Z',+ nextRunAt: due,+}++interface AgentInput {+ sessionId: string+ meta: { cwd: string, agentPreset: string }+ agentOptions: { provider?: string, model?: string }+ setup: (agentCtx: unknown, createdAgent?: SetupAgentLike) => Promise<void>+}++interface NewAgentControl {+ session: { id: string, seq: number }+ finish: () => void+}++const state = new Map<string, unknown>()+const disposers: Array<() => void> = []+const stops: Array<() => Promise<void>> = []+let host: ReturnType<typeof installHost>++function installHost() {+ let messageSequence = 0+ let autoFinish = true+ const archivedSessionIds: string[] = []+ const boundEvents: SessionEventLike[] = []+ const boundSession = { id: 'session-1', seq: 0 }+ const eventListeners = new Set<(target: unknown, event: SessionEventLike) => void>()+ const lifecycleListeners = new Map<string, (...args: never[]) => unknown>()+ const followup = vi.fn((message: UserMessage) => {+ boundEvents.push({ type: 'agent/inbox/spliced', data: { inserted: [message] } })+ })+ const boundAgent = { session: boundSession, runningStatus: 'running', followup, whenIdle: vi.fn(), steer: vi.fn(), inject: vi.fn() }+ const inspect = vi.fn(async (id: string) => {+ if (id !== 'session-1')+ throw Object.assign(new Error('Session not found'), { code: 'session/not-found' })+ return { meta: { id }, events: structuredClone(boundEvents) }+ })+ const resolveAgent = vi.fn(async (_id: string) => ({ agent: boundAgent }))+ const flush = vi.fn<(session: unknown) => Promise<boolean>>(async () => true)+ const createMessage = vi.fn((input: Omit<UserMessage, 'id' | 'role'>) => ({ ...input, role: 'user' as const, id: `message-${++messageSequence}` as MessageId }))+ const installModelSelection = vi.fn()+ const setApprovalPolicy = vi.fn()+ const modules = new Map<string, unknown>([+ ['@deepseek-ai/dsh-llm', { createUserMessage: createMessage }],+ ['@deepseek-ai/dsh-agent', { installModelSelection }],+ ['@deepseek-ai/dsh-user-approval', { setApprovalPolicy }],+ ])+ const controls: NewAgentControl[] = []+ const create = vi.fn(async (input: AgentInput) => {+ const session = { id: input.sessionId, seq: 0 }+ const agentContext = {}+ let finishIdle = () => {}+ const idle = new Promise<void>((resolve) => {+ finishIdle = resolve+ })+ const emit = (type: string, data: Record<string, unknown>) => {+ session.seq += 1+ for (const listener of eventListeners)+ listener(session, { seq: session.seq, type, data })+ }+ const finish = () => {+ emit('turn/end', { reason: { kind: 'completed' } })+ finishIdle()+ }+ controls.push({ session, finish })+ await input.setup(agentContext, { session })+ return {+ agent: {+ session,+ followup: vi.fn(() => {+ emit('turn/start', {})+ if (autoFinish)+ finish()+ }),+ whenIdle: vi.fn().mockResolvedValueOnce(undefined).mockReturnValue(idle),+ cancel: vi.fn(finish),+ },+ }+ })+ const workspace = { path: '/virtual/scheduler-workspace', status: vi.fn(async () => 'ok'), attachSession: vi.fn(async () => {}) }+ const workspaceRegistry = { archivedSessionIds, get: vi.fn((id: string) => id === 'ws-1' ? workspace : undefined) }+ const permissionPresets = { defaultPreset: 'read-only', set: vi.fn() }+ const agentPresets = { mount: vi.fn(async () => {}) }+ const rename = vi.fn()+ const logger = { warn: vi.fn(), error: vi.fn() }+ const context = {+ agents: { create, withoutInitiator: vi.fn((fn: () => Promise<unknown>) => fn()), currentInitiator: vi.fn() },+ sessionController: { inspect, resolveAgent },+ sessions: { flush },+ workspaceRegistry,+ permissionPresets,+ agentPresets,+ get: (name: string) => name === 'sessionTitle' ? { rename } : undefined,+ loader: { import: vi.fn(async (name: string) => modules.get(name)), unwrapExports: vi.fn((value: unknown) => value) },+ on: vi.fn((name: string, listener: (...args: never[]) => unknown) => {+ if (name === 'session/event')+ eventListeners.add(listener as (target: unknown, event: SessionEventLike) => void)+ else+ lifecycleListeners.set(name, listener)+ return () => {+ eventListeners.delete(listener as (target: unknown, event: SessionEventLike) => void)+ lifecycleListeners.delete(name)+ }+ }),+ logger,+ webServer: { register: () => () => {} },+ }+ disposers.push(server(context as unknown as HostContext))+ return { followup, boundAgent, boundSession, boundEvents, inspect, resolveAgent, flush, createMessage, create, controls, workspaceRegistry, permissionPresets, agentPresets, installModelSelection, setApprovalPolicy, rename, context, lifecycleListeners, logger, setAutoFinish: (value: boolean) => {+ autoFinish = value+ } }+}++function seed(...items: SchedulerTask[]): void {+ state.set('tasks', { version: 2, tasks: structuredClone(items) })+}++function newTask(id = 'new-task'): SchedulerTask {+ const { sessionId: _sessionId, ...base } = fixture+ return { ...base, id, delivery: 'new-session', workspaceId: 'ws-1', permission: 'read-only', provider: 'test-provider', model: 'test-model', reasoningEffort: 'high' }}beforeEach(() => {vi.clearAllMocks()+ resetWriteQueue()+ vi.useFakeTimers()+ vi.setSystemTime(new Date(now))+ state.clear()+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+ host = installHost()})-describe('scheduler.trigger', () => {- it('同一任务执行中时拒绝再次触发', async () => {- vi.mocked(task.get).mockResolvedValue(taskFixture)- vi.mocked(executor.run).mockReturnValue(new Promise<never>(() => {}))+afterEach(async () => {+ for (const control of host.controls)+ control.finish()+ await vi.advanceTimersByTimeAsync(0)+ await Promise.all(stops.splice(0).map(stop => stop()))+ await scheduler.stop()+ disposers.splice(0).forEach(dispose => dispose())+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()+})- await expect(scheduler.trigger('task-1')).resolves.toEqual({ ok: true })- await expect(scheduler.trigger('task-1')).resolves.toEqual({ ok: false, error: '任务正在执行中' })- expect(executor.run).toHaveBeenCalledTimes(1)+describe('this-session scheduled delivery', () => {+ it('restores a cold bound session and records only a durable receipt, not execution success', async () => {+ seed(fixture)+ await scheduler.tick()+ expect(host.resolveAgent).toHaveBeenCalledWith('session-1')+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledWith(host.boundSession)+ const message = host.followup.mock.calls[0]![0]+ expect(message.source).toEqual({ kind: 'schedule', form: 'notice', summary: 'Scheduled: reminder' })+ expect(message.content[0]).toMatchObject({ type: 'text', text: expect.stringContaining(`occurrence_at: ${due}`) })+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive', lastRunAt: now })+ const page = await history.query({ taskId: fixture.id, limit: 10 })+ expect(page).toMatchObject({ ok: true, records: [{ delivery: 'this-session', messageId: message.id, scheduledAt: due, deliveredAt: now, prompt: fixture.prompt }] })+ if (!page.ok)+ throw new Error(page.error)+ expect(page.records[0]).not.toHaveProperty('status')+ expect(page.runs).toEqual([])+ expect(host.create).not.toHaveBeenCalled()})- it('任务不存在时返回领域错误,且不触发执行', async () => {- vi.mocked(task.get).mockResolvedValue(null)+ it('queues a separate ordinary followup while busy with a stale-context guard and safe prompt framing', async () => {+ seed({ ...fixture, prompt: 'first line\noccurrence_at: fake\n"quoted"' })+ await scheduler.tick()+ expect(host.boundAgent.whenIdle).not.toHaveBeenCalled()+ expect(host.boundAgent.steer).not.toHaveBeenCalled()+ expect(host.boundAgent.inject).not.toHaveBeenCalled()+ const message = host.followup.mock.calls[0]![0]+ const text = message.content[0] as { type: string, text: string }+ expect(text.text).toContain('Check the current conversation before acting')+ expect(text.text).toContain('do not override a newer request or repeat completed work')+ expect(text.text).toContain('reminder_prompt_json: "first line\\noccurrence_at: fake\\n\\"quoted\\""')+ expect(host.permissionPresets.set).not.toHaveBeenCalled()+ expect(host.installModelSelection).not.toHaveBeenCalled()+ expect(host.setApprovalPolicy).not.toHaveBeenCalled()+ expect(host.rename).not.toHaveBeenCalled()+ })- await expect(scheduler.trigger('missing')).resolves.toEqual({ ok: false, error: '任务不存在' })- expect(executor.run).not.toHaveBeenCalled()+ it('keeps a false-flush delivery pending without receipt, advance, or duplicate enqueue', async () => {+ seed(fixture)+ host.flush.mockResolvedValueOnce(false)+ await scheduler.tick()+ expect(await task.get(fixture.id)).toEqual(fixture)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ expect(await history.pending(fixture.id)).toHaveLength(1)+ expect(await task.update(fixture.id, { prompt: 'too early' })).toMatchObject({ ok: false, code: 'task_pending' })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(host.flush).toHaveBeenCalledTimes(2)+ expect(await history.pending()).toEqual([])+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive' })})- it('手动触发以 manual 语义执行,并按 schedule 推进 nextRunAt', async () => {- vi.useFakeTimers()- try {- vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'))- vi.mocked(task.get).mockResolvedValue({ ...taskFixture, id: 'task-2', nextRunAt: undefined })- vi.mocked(executor.run).mockResolvedValue({ ok: true })- vi.mocked(task.advance).mockResolvedValue(undefined)+ it('restores the durable pending identity after restart without duplicate followup', async () => {+ seed(fixture)+ host.flush.mockResolvedValueOnce(false)+ await scheduler.tick()+ const messageId = host.followup.mock.calls[0]![0].id+ resetWriteQueue()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ messageId }] })+ })- await expect(scheduler.trigger('task-2')).resolves.toEqual({ ok: true })- await vi.advanceTimersByTimeAsync(0)+ it('retries a prepared-but-not-enqueued journal using the same message identity', async () => {+ seed(fixture)+ host.followup.mockImplementationOnce(() => {+ throw new Error('enqueue interrupted')+ })+ await scheduler.tick()+ expect(await history.pending()).toHaveLength(1)+ expect(await task.get(fixture.id)).toEqual(fixture)+ resetWriteQueue()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(2)+ expect(host.followup.mock.calls[1]![0].id).toBe(host.followup.mock.calls[0]![0].id)+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive' })+ })- expect(executor.run).toHaveBeenCalledWith(expect.objectContaining({ id: 'task-2' }), 'manual')- expect(task.advance).toHaveBeenCalledWith('task-2', '2026-01-01T00:00:00.000Z', '2026-01-01T00:30:00.000Z')- }- finally {- vi.useRealTimers()+ it('repairs a receipt committed before task advancement without replaying the reminder', async () => {+ seed(fixture)+ await history.commit({ task: fixture, trigger: 'schedule', scheduledAt: due, deliveredAt: now, message: { id: 'already-delivered' as MessageId, role: 'user', content: [], source: { kind: 'schedule' } } })+ await scheduler.tick()+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive', lastRunAt: now })+ expect(host.resolveAgent).not.toHaveBeenCalled()+ expect(host.followup).not.toHaveBeenCalled()+ })++ it('recognizes a followup accepted before throwing and never injects its identity twice', async () => {+ seed(fixture)+ host.followup.mockImplementationOnce((message) => {+ host.boundEvents.push({ type: 'agent/inbox/spliced', data: { inserted: [message] } })+ throw new Error('accepted before producer failure')+ })+ await scheduler.tick()+ const messageId = host.followup.mock.calls[0]![0].id+ expect(await history.pending()).toHaveLength(1)+ resetWriteQueue()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ messageId }] })+ })++ it('persists no receipt when the journal or acknowledgement write fails and reuses accepted identity', async () => {+ seed(fixture)+ let failHistory = true+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ if (key === 'history' && failHistory)+ throw new Error('history unavailable')+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+ await scheduler.tick()+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.flush).not.toHaveBeenCalled()+ expect(await task.get(fixture.id)).toEqual(fixture)+ failHistory = false+ resetWriteQueue()+ host.flush.mockImplementationOnce(async () => {+ failHistory = true+ return true+ })+ await scheduler.tick()+ const messageId = host.followup.mock.calls[0]![0].id+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ expect(await task.get(fixture.id)).toEqual(fixture)+ failHistory = false+ resetWriteQueue()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ messageId }] })+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive' })+ })++ it('repairs a task-write failure after committing a receipt without re-enqueue or rewriting history', async () => {+ seed(fixture)+ let failTaskWrite = true+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ if (key === 'tasks' && failTaskWrite) {+ failTaskWrite = false+ throw new Error('task commit unavailable')+ }+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.pending()).toEqual([])+ expect(await history.journals()).toHaveLength(1)+ const receipt = await history.query({ taskId: fixture.id, limit: 10 })+ await scheduler.tick()+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive' })+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toEqual(receipt)+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(runtime.pending.size).toBe(0)+ expect(await history.journals()).toEqual([])+ })++ it('folds missed recurring occurrences to the latest due slot and advances from it', async () => {+ seed({ ...fixture, schedule: { kind: 'interval', everyMinutes: 30, anchor: '2026-05-31T12:00:00.000Z', timeZone: 'UTC' }, nextRunAt: '2026-05-31T12:30:00.000Z' })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ scheduledAt: due }] })+ expect(await task.get(fixture.id)).toMatchObject({ status: 'active', nextRunAt: '2026-06-01T12:30:00.000Z' })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ })++ it('preserves interval phase and skips slots elapsed before flush acknowledgement', async () => {+ const target: SchedulerTask = { ...fixture, schedule: { kind: 'interval', everyMinutes: 15, anchor: '2026-06-01T12:00:00.000Z', timeZone: 'UTC' }, nextRunAt: '2026-06-01T12:02:17.000Z' }+ seed(target)+ host.flush.mockImplementationOnce(async () => {+ vi.setSystemTime(new Date('2026-06-01T13:32:17.000Z'))+ return true+ })+ await scheduler.tick()+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ scheduledAt: '2026-06-01T12:02:17.000Z', deliveredAt: '2026-06-01T13:32:17.000Z' }] })+ expect(await task.get(fixture.id)).toMatchObject({ nextRunAt: '2026-06-01T13:47:17.000Z' })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ })++ it('repairs a delayed receipt by skipping elapsed slots instead of replaying them', async () => {+ const target: SchedulerTask = { ...fixture, schedule: { kind: 'interval', everyMinutes: 15, anchor: due, timeZone: 'UTC' }, nextRunAt: '2026-06-01T12:02:17.000Z' }+ seed(target)+ await history.commit({ task: target, trigger: 'schedule', scheduledAt: target.nextRunAt!, deliveredAt: now, message: { id: 'durable-receipt' as MessageId, role: 'user', content: [], source: { kind: 'schedule' } } })+ vi.setSystemTime(new Date('2026-06-01T14:02:17.000Z'))+ await scheduler.tick()+ expect(await task.get(fixture.id)).toMatchObject({ nextRunAt: '2026-06-01T14:17:17.000Z', lastRunAt: now })+ expect(host.followup).not.toHaveBeenCalled()+ expect(host.resolveAgent).not.toHaveBeenCalled()+ expect(await history.journals()).toEqual([])+ })++ it('never advances an edited task from an old receipt snapshot', async () => {+ seed(fixture)+ await history.commit({ task: fixture, trigger: 'schedule', scheduledAt: due, deliveredAt: now, message: { id: 'old-receipt' as MessageId, role: 'user', content: [], source: { kind: 'schedule' } } })+ const update = await task.update(fixture.id, { prompt: 'new explicit request', enabled: false }, fixture)+ if (!update.ok)+ throw new Error(update.error)+ await scheduler.tick()+ expect(await task.get(fixture.id)).toEqual(update.task)+ expect(host.followup).not.toHaveBeenCalled()+ expect(await history.journals()).toEqual([])+ })++ it.each(['pause', 'edit', 'stop', 'delete'] as const)('discards an unaccepted pending identity after %s and restart', async (change) => {+ seed(fixture)+ host.followup.mockImplementationOnce(() => {+ throw new Error('not accepted')+ })+ await scheduler.tick()+ const oldId = host.followup.mock.calls[0]![0].id+ if (change === 'pause')+ expect(await task.toggle(fixture.id, false)).toMatchObject({ ok: true })+ if (change === 'edit')+ expect(await task.update(fixture.id, { prompt: 'new prompt', enabled: false })).toMatchObject({ ok: true })+ if (change === 'stop')+ await task.stopSession('session-1')+ if (change === 'delete')+ await task.remove(fixture.id)+ resetWriteQueue()+ await scheduler.tick()+ expect(await history.pending()).toEqual([])+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ if (change === 'edit') {+ expect(await task.toggle(fixture.id, true)).toMatchObject({ ok: true })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(2)+ expect(host.followup.mock.calls[1]![0].id).not.toBe(oldId)+ expect(host.followup.mock.calls[1]![0].content[0]).toMatchObject({ text: expect.stringContaining('reminder_prompt_json: "new prompt"') })}})++ it('flushes an already accepted pending identity after stop without advancing or re-enqueuing', async () => {+ seed(fixture)+ host.flush.mockResolvedValueOnce(false)+ await scheduler.tick()+ const messageId = host.followup.mock.calls[0]![0].id+ await task.stopSession('session-1')+ const stopped = await task.get(fixture.id)+ resetWriteQueue()+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await task.get(fixture.id)).toEqual(stopped)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ messageId }] })+ })++ it('rechecks wall time after cold restoration before accepting an occurrence', async () => {+ seed(fixture)+ host.resolveAgent.mockImplementationOnce(async () => {+ vi.setSystemTime(new Date('2026-06-01T11:59:00.000Z'))+ return { agent: host.boundAgent }+ })+ await scheduler.tick()+ expect(host.followup).not.toHaveBeenCalled()+ expect(runtime.failed.has(fixture.id)).toBe(false)+ vi.setSystemTime(new Date(now))+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ })++ it('does not use stale batch time after the preceding delivery rolls the clock back', async () => {+ seed(fixture, { ...fixture, id: 'task-2', nextRunAt: '2026-06-01T12:10:00.000Z', schedule: { kind: 'once', at: '2026-06-01T12:10:00.000Z', timeZone: 'UTC' } })+ host.flush.mockImplementationOnce(async () => {+ vi.setSystemTime(new Date('2026-06-01T11:50:00.000Z'))+ return true+ })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await task.get('task-2')).toMatchObject({ status: 'active', nextRunAt: '2026-06-01T12:10:00.000Z' })+ vi.setSystemTime(new Date(now))+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(2)+ })++ it('manual delivery uses now and preserves the next scheduled occurrence even while paused', async () => {+ seed({ ...fixture, enabled: false })+ expect(await scheduler.trigger(fixture.id)).toEqual({ ok: true })+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ trigger: 'manual', scheduledAt: now }] })+ expect(await task.get(fixture.id)).toMatchObject({ enabled: false, status: 'active', nextRunAt: due })+ })++ it('refuses archived/missing targets and a wrong restored session without delivery or advancement', async () => {+ seed(fixture)+ host.workspaceRegistry.archivedSessionIds.push('session-1')+ await scheduler.tick()+ expect(host.resolveAgent).not.toHaveBeenCalled()+ expect(await task.get(fixture.id)).toEqual(fixture)+ host.workspaceRegistry.archivedSessionIds.splice(0)+ host.inspect.mockRejectedValueOnce({ code: 'session/not-found' })+ expect(await scheduler.trigger(fixture.id)).toMatchObject({ ok: false, code: 'session_not_found' })+ host.resolveAgent.mockResolvedValueOnce({ agent: { ...host.boundAgent, session: { id: 'different', seq: 0 } } })+ expect(await scheduler.trigger(fixture.id)).toMatchObject({ ok: false, code: 'session_mismatch' })+ expect(host.followup).not.toHaveBeenCalled()+ })++ it('rechecks archive status after cold restoration', async () => {+ seed(fixture)+ host.resolveAgent.mockImplementationOnce(async () => {+ host.workspaceRegistry.archivedSessionIds.push('session-1')+ return { agent: host.boundAgent }+ })+ await scheduler.tick()+ expect(host.followup).not.toHaveBeenCalled()+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ })++ it('pause blocks due occurrences and terminal status blocks both automatic and manual execution', async () => {+ seed({ ...fixture, enabled: false })+ await scheduler.tick()+ expect(host.followup).not.toHaveBeenCalled()+ expect(await task.toggle(fixture.id, true)).toMatchObject({ ok: true })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await scheduler.trigger(fixture.id)).toMatchObject({ ok: false, code: 'task_inactive' })+ await scheduler.tick()+ expect(host.followup).toHaveBeenCalledTimes(1)+ })++ it('deletion racing an accepted delivery cannot resurrect the task', async () => {+ seed(fixture)+ let acknowledge = (_value: boolean) => {}+ host.flush.mockImplementationOnce(() => new Promise<boolean>((resolve) => {+ acknowledge = resolve+ }))+ const tick = scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ expect(host.followup).toHaveBeenCalledTimes(1)+ const removal = task.remove(fixture.id)+ acknowledge(true)+ await tick+ expect(await removal).toEqual({ ok: true })+ expect(await task.get(fixture.id)).toBeNull()+ await scheduler.tick()+ expect(await task.get(fixture.id)).toBeNull()+ expect(host.followup).toHaveBeenCalledTimes(1)+ })++ it('drains an already accepted durability barrier before unloading and rejects later work', async () => {+ seed(fixture)+ let acknowledge = (_value: boolean) => {}+ host.flush.mockImplementationOnce(() => new Promise<boolean>((resolve) => {+ acknowledge = resolve+ }))+ const tick = scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ let stopped = false+ const stopping = scheduler.stop().then(() => {+ stopped = true+ })+ await vi.advanceTimersByTimeAsync(0)+ expect(stopped).toBe(false)+ acknowledge(true)+ await tick+ await stopping+ expect(stopped).toBe(true)+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [{ messageId: expect.any(String) }] })+ expect(await scheduler.trigger(fixture.id)).toMatchObject({ ok: false, code: 'scheduler_stopping' })+ })+})++describe('new-session runtime and shared lifecycle', () => {+ it('keeps resource-scoped new-session execution, history, and real due occurrence', async () => {+ seed(newTask())+ await scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ expect(host.create).toHaveBeenCalledWith(expect.objectContaining({ meta: { cwd: '/virtual/scheduler-workspace', agentPreset: 'standard' }, agentOptions: { provider: 'test-provider', model: 'test-model' } }))+ expect(host.permissionPresets.set).toHaveBeenCalledWith(expect.objectContaining({ id: expect.stringMatching(/^task-/) }), 'read-only')+ expect(host.installModelSelection).toHaveBeenCalledWith(expect.anything(), { current: { provider: 'test-provider', model: 'test-model', reasoningEffort: 'high' }, assembled: undefined })+ expect(await history.query({ taskId: 'new-task', limit: 10 })).toMatchObject({ ok: true, records: [{ delivery: 'new-session', status: 'succeeded', scheduledFor: due, startedAt: now, prompt: fixture.prompt }] })+ expect(await task.get('new-task')).toMatchObject({ status: 'inactive' })+ expect(host.followup).not.toHaveBeenCalled()+ })++ it('advances a long new-session run from durable phase to a strictly future slot', async () => {+ seed({ ...newTask(), schedule: { kind: 'interval', everyMinutes: 15, anchor: due, timeZone: 'UTC' }, nextRunAt: '2026-06-01T12:02:17.000Z' })+ host.setAutoFinish(false)+ await scheduler.tick()+ await vi.advanceTimersByTimeAsync(0)+ vi.setSystemTime(new Date('2026-06-01T13:02:17.000Z'))+ host.controls[0]!.finish()+ await vi.advanceTimersByTimeAsync(0)+ expect(await task.get('new-task')).toMatchObject({ nextRunAt: '2026-06-01T13:17:17.000Z', lastRunAt: '2026-06-01T13:02:17.000Z' })+ expect(await history.query({ taskId: 'new-task', limit: 10 })).toMatchObject({ ok: true, records: [{ status: 'succeeded', scheduledFor: '2026-06-01T12:02:17.000Z' }] })+ await scheduler.tick()+ expect(host.create).toHaveBeenCalledTimes(1)+ expect(await history.journals()).toEqual([])+ })++ it('repairs a finished new-session journal after crash without executing the one-off again', async () => {+ const target = newTask()+ seed(target)+ const saved = { id: 'completed-run', taskId: target.id, taskName: target.name, prompt: target.prompt, trigger: 'schedule' as const, status: 'running' as const, scheduledFor: due, startedAt: now }+ await runs.save(saved, target)+ await runs.save({ ...saved, status: 'succeeded', finishedAt: now })+ resetWriteQueue()+ await recovery.recover()+ await scheduler.tick()+ expect(await task.get(target.id)).toMatchObject({ status: 'inactive', lastRunAt: now })+ expect(host.create).not.toHaveBeenCalled()+ expect(await history.journals()).toEqual([])+ expect(await history.query({ taskId: target.id, limit: 10 })).toMatchObject({ ok: true, records: [{ id: saved.id, status: 'succeeded' }] })+ })++ it('recovers an interrupted new-session journal and folds missed slots without a second run', async () => {+ const target: SchedulerTask = { ...newTask(), schedule: { kind: 'interval', everyMinutes: 15, anchor: due, timeZone: 'UTC' }, nextRunAt: '2026-06-01T12:02:17.000Z' }+ seed(target)+ await runs.save({ id: 'interrupted-run', taskId: target.id, taskName: target.name, trigger: 'schedule', status: 'running', scheduledFor: target.nextRunAt!, startedAt: now }, target)+ vi.setSystemTime(new Date('2026-06-01T14:02:17.000Z'))+ await recovery.recover()+ await scheduler.tick()+ expect(await task.get(target.id)).toMatchObject({ status: 'active', nextRunAt: '2026-06-01T14:17:17.000Z' })+ expect(host.create).not.toHaveBeenCalled()+ expect(await history.query({ taskId: target.id, limit: 10 })).toMatchObject({ ok: true, records: [{ status: 'interrupted', error: 'host_interrupted' }] })+ })++ it('cannot consume an edited task using an old new-session journal snapshot', async () => {+ const target = newTask()+ seed(target)+ await runs.save({ id: 'old-run', taskId: target.id, taskName: target.name, trigger: 'schedule', status: 'succeeded', scheduledFor: due, startedAt: now, finishedAt: now }, target)+ const updated = await task.update(target.id, { prompt: 'replacement', enabled: false }, target)+ if (!updated.ok)+ throw new Error(updated.error)+ await scheduler.tick()+ expect(await task.get(target.id)).toEqual(updated.task)+ expect(host.create).not.toHaveBeenCalled()+ expect(await history.journals()).toEqual([])+ })++ it('manual new-session execution preserves the automatic occurrence and rejects a concurrent duplicate', async () => {+ seed(newTask())+ host.setAutoFinish(false)+ expect(await scheduler.trigger('new-task')).toEqual({ ok: true })+ expect(await scheduler.trigger('new-task')).toMatchObject({ ok: false, code: 'task_busy' })+ await vi.advanceTimersByTimeAsync(0)+ host.controls[0]!.finish()+ await vi.advanceTimersByTimeAsync(0)+ expect(await task.get('new-task')).toMatchObject({ status: 'active', nextRunAt: due, lastRunAt: now })+ expect(await history.query({ taskId: 'new-task', limit: 10 })).toMatchObject({ ok: true, records: [{ trigger: 'manual', scheduledFor: now }] })+ })++ it('new-session completion after deletion does not resurrect the original task', async () => {+ seed(newTask())+ host.setAutoFinish(false)+ await scheduler.trigger('new-task')+ await vi.advanceTimersByTimeAsync(0)+ expect(await task.remove('new-task')).toEqual({ ok: true })+ host.controls[0]!.finish()+ await vi.advanceTimersByTimeAsync(0)+ expect(await task.get('new-task')).toBeNull()+ expect(await history.query({ taskId: 'new-task', limit: 10 })).toMatchObject({ ok: true, records: [{ status: 'succeeded' }] })+ })++ it('caps new-session concurrency while still delivering reminders without a waiting flag', async () => {+ seed(...Array.from({ length: 5 }, (_, index) => newTask(`job-${index}`)), fixture)+ host.setAutoFinish(false)+ await scheduler.tick()+ expect(runtime.running.size).toBe(4)+ expect(await scheduler.waitingIds()).toEqual(new Set(['job-4']))+ expect(host.followup).toHaveBeenCalledTimes(1)+ expect(await scheduler.trigger('job-4')).toMatchObject({ ok: false, code: 'scheduler_capacity' })+ })++ it('registers schedule activity for paused active records and ends bindings on session-stop', async () => {+ seed({ ...fixture, enabled: false }, newTask())+ const stop = scheduler.start(1000)+ stops.push(stop)+ await vi.advanceTimersByTimeAsync(0)+ const activity = host.lifecycleListeners.get('workspace/session-activity') as unknown as (request: { sessionId: string }, next: () => Promise<unknown[]>) => Promise<unknown[]>+ const ended = host.lifecycleListeners.get('workspace/session-stop') as unknown as (request: { sessionId: string }) => Promise<void>+ expect(await activity({ sessionId: 'session-1' }, async () => [{ kind: 'other', items: [] }])).toEqual([{ kind: 'schedule', items: [{ id: fixture.id, label: fixture.name }] }, { kind: 'other', items: [] }])+ await ended({ sessionId: 'session-1' })+ expect(await task.get(fixture.id)).toMatchObject({ status: 'inactive', enabled: false })+ expect(await activity({ sessionId: 'session-1' }, async () => [])).toEqual([])+ expect(await history.query({ taskId: fixture.id, limit: 10 })).toMatchObject({ ok: true, records: [] })+ await stop()+ stops.splice(stops.indexOf(stop), 1)+ expect(host.lifecycleListeners.size).toBe(0)+ })})diff --git a/packages/dsh-tauri-scheduler/src/host/service/scheduler.ts b/packages/dsh-tauri-scheduler/src/host/service/scheduler.tsindex 99e923a6..eaa6f1f1 100644--- a/packages/dsh-tauri-scheduler/src/host/service/scheduler.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/scheduler.ts@@ -1,80 +1,179 @@-import type { HostContext, OperationResult, SchedulerTask } from '../types'+import type { HostContext, OperationResult, RunTrigger, SchedulerTask } from '../types'import { getServerContext } from 'dsh-h3/utils'import { defineService } from 'dsh-tauri'-import { filter, isEmpty, isNil, take } from 'lodash-es'+import { drainRuntime, runtime, trackAccepted, withTaskQueue } from '../config/runtime'import { server } from '../server'-import { nextOccurrence } from '../utils/schedule'-import { isTaskDue, selectWaitingTaskIds } from '../utils/waiting'+import { nextFutureOccurrence } from '../utils/occurrence'+import { latestDueOccurrence } from '../utils/schedule'+import { selectWaitingTaskIds } from '../utils/waiting'+import { delivery } from './delivery'import { executor } from './executor'+import { history } from './history'+import { recovery } from './recovery'import { task } from './task'const SCHEDULER_MAX_CONCURRENT_RUNS = 4-const running = new Set<string>()-export const scheduler = defineService({- start(tickMs: number): () => void {+ start(tickMs: number): () => Promise<void> {+ runtime.stopping = false+ const ctx = getServerContext<HostContext>(server)+ const stopActivity = ctx.on?.('workspace/session-activity', sessionActivity)+ const stopSession = ctx.on?.('workspace/session-stop', sessionStop)+ let tickInFlight = true+ void trackAccepted(background(async () => {+ await recovery.recover()+ if (!runtime.stopping)+ await scheduler.tick()+ })).catch((error: unknown) => warn('recover interrupted runs failed', error)).finally(() => {+ tickInFlight = false+ })const timer = setInterval(() => {- void scheduler.tick().catch((error: unknown) => warn('tick failed', error))+ if (runtime.stopping || tickInFlight)+ return+ tickInFlight = true+ void trackAccepted(background(() => scheduler.tick())).catch((error: unknown) => warn('tick failed', error)).finally(() => {+ tickInFlight = false+ })}, tickMs)- return () => clearInterval(timer)+ return async () => {+ runtime.stopping = true+ clearInterval(timer)+ stopActivity?.()+ stopSession?.()+ await drainRuntime()+ }},async trigger(id: string): Promise<OperationResult> {- if (running.has(id))- return { ok: false, error: '任务正在执行中' }- const target = await task.get(id)- if (target === null)- return { ok: false, error: '任务不存在' }- void fire(target, 'manual').catch((error: unknown) => warn('manual run failed', error))- return { ok: true }+ return withTaskQueue(async () => {+ if (runtime.stopping)+ return { ok: false, error: '调度器正在卸载', code: 'scheduler_stopping' }+ if (runtime.running.has(id))+ return { ok: false, error: '任务正在执行中', code: 'task_busy' }+ await repairOccurrences(id)+ const target = await task.get(id)+ if (target === null)+ return { ok: false, error: '任务不存在', code: 'task_not_found' }+ if (target.status === 'inactive')+ return { ok: false, error: '任务已结束,不能重新启用或运行', code: 'task_inactive' }+ if (target.delivery === 'new-session' && runtime.running.size >= SCHEDULER_MAX_CONCURRENT_RUNS)+ return { ok: false, error: '调度器运行并发已满', code: 'scheduler_capacity' }+ runtime.failed.delete(id)+ if (target.delivery === 'this-session')+ return acceptDelivery(target, 'manual', new Date().toISOString())+ launchRun(target, 'manual', new Date().toISOString())+ return { ok: true }+ })},async tick(): Promise<void> {- const all = await task.list()- if (isEmpty(all))- return- const now = Date.now()- for (const item of filter(all, item => item.enabled && isNil(item.nextRunAt))) {- const occurrence = nextOccurrence(item.schedule, now)- if (occurrence !== undefined)- await task.advance(item.id, item.lastRunAt, new Date(occurrence).toISOString())- }- const pending = filter(all, item => isTaskDue(item, now) && !running.has(item.id))- for (const item of take(pending, SCHEDULER_MAX_CONCURRENT_RUNS - running.size))- void fire(item, 'schedule')+ await withTaskQueue(async () => {+ if (runtime.stopping)+ return+ await repairOccurrences()+ let all = await task.list()+ for (const item of all.filter(item => item.status === 'active' && item.enabled && !item.nextRunAt))+ await task.ensureTarget(item)+ all = await task.list()+ const pending = await history.pending()+ for (const item of pending) {+ if (runtime.failed.has(item.task.id))+ continue+ await acceptDelivery(item.task, item.trigger, item.scheduledAt)+ }+ all = await task.list()+ for (const item of all) {+ const now = Date.now()+ if (item.status !== 'active' || !item.enabled || !item.nextRunAt || Date.parse(item.nextRunAt) > now+ || runtime.running.has(item.id) || runtime.pending.has(item.id) || runtime.failed.has(item.id)) {+ continue+ }+ const occurrence = latestDueOccurrence(item.schedule, Date.parse(item.nextRunAt!), now)+ if (occurrence === undefined)+ continue+ const scheduledAt = new Date(occurrence).toISOString()+ if (item.delivery === 'this-session')+ await acceptDelivery(item, 'schedule', scheduledAt)+ else if (runtime.running.size < SCHEDULER_MAX_CONCURRENT_RUNS)+ launchRun(item, 'schedule', scheduledAt)+ }+ })},async waitingIds(): Promise<Set<string>> {- const all = await task.list()- return selectWaitingTaskIds(all, running, SCHEDULER_MAX_CONCURRENT_RUNS - running.size, Date.now())+ return selectWaitingTaskIds(await task.list(), runtime.running, SCHEDULER_MAX_CONCURRENT_RUNS - runtime.running.size, Date.now())+ },++ async stop(): Promise<void> {+ await drainRuntime()},})-// --- internal ---+async function repairOccurrences(taskId?: string): Promise<void> {+ for (const item of await history.journals(taskId)) {+ if (!item.completedAt)+ continue+ const next = item.trigger === 'schedule' ? nextFutureOccurrence(item.task.schedule, Date.parse(item.scheduledAt), Date.now()) : undefined+ await task.complete(item.task, item.completedAt, next === undefined ? undefined : new Date(next).toISOString(), item.trigger === 'schedule')+ await history.acknowledge(item.id)+ runtime.flushes.delete(item.id)+ if (runtime.pending.get(item.task.id)?.message.id === item.id)+ runtime.pending.delete(item.task.id)+ runtime.failed.delete(item.task.id)+ }+}++function launchRun(target: SchedulerTask, trigger: RunTrigger, scheduledAt: string): void {+ runtime.running.add(target.id)+ const accepted = background(async () => {+ try {+ await executor.run(target, trigger, scheduledAt)+ await repairOccurrences(target.id)+ }+ catch (error) {+ runtime.failed.add(target.id)+ throw error+ }+ finally {+ runtime.running.delete(target.id)+ }+ })+ void trackAccepted(accepted).catch((error: unknown) => warn('new-session run failed', error))+}-async function fire(target: SchedulerTask, trigger: 'schedule' | 'manual'): Promise<void> {- if (running.has(target.id))- return- running.add(target.id)- const lastRunAt = new Date().toISOString()+async function acceptDelivery(target: SchedulerTask, trigger: RunTrigger, scheduledAt: string): Promise<OperationResult> {+ const accepted = background(() => delivery.run(target, trigger, scheduledAt))try {- await executor.run(target, trigger)+ const result = await trackAccepted(accepted)+ if (!result.ok && result.code !== 'delivery_pending' && result.code !== 'delivery_not_due') {+ if (['session_archived', 'session_not_found', 'session/not-found', 'session_mismatch', 'task_invalid'].includes(result.code ?? ''))+ runtime.failed.add(target.id)+ warn('this-session delivery failed', result.error)+ }+ return result}- finally {- running.delete(target.id)- const now = Date.now()- const previous = target.nextRunAt ? new Date(target.nextRunAt).getTime() : now- const from = target.schedule.kind === 'interval' || target.schedule.kind === 'custom' ? previous : now- const next = nextOccurrence(target.schedule, from)- await task.advance(target.id, lastRunAt, next === undefined ? undefined : new Date(next).toISOString())+ catch (error) {+ warn('this-session delivery failed', error)+ return { ok: false, error: error instanceof Error ? error.message : String(error), code: 'delivery_failed' }}}+async function sessionActivity({ sessionId }: { sessionId: string }, next: () => Promise<unknown[]>): Promise<unknown[]> {+ const items = (await task.list()).filter(item => item.delivery === 'this-session' && item.sessionId === sessionId && item.status === 'active').map(item => ({ id: item.id, label: item.name }))+ const others = await next()+ return items.length ? [{ kind: 'schedule', items }, ...others] : others+}++async function sessionStop({ sessionId }: { sessionId: string }): Promise<void> {+ await task.stopSession(sessionId)+}++function background<T>(fn: () => Promise<T>): Promise<T> {+ const ctx = getServerContext<HostContext>(server)+ return typeof ctx.agents?.withoutInitiator === 'function' ? ctx.agents.withoutInitiator(fn) : fn()+}+function warn(message: string, error: unknown): void {- try {- getServerContext<HostContext>(server).logger?.warn?.(`dsh-tauri-scheduler: ${message}`, error)- }- catch {- }+ getServerContext<HostContext>(server).logger?.warn?.(`dsh-tauri-scheduler: ${message}`, error)}diff --git a/packages/dsh-tauri-scheduler/src/host/service/task.test.ts b/packages/dsh-tauri-scheduler/src/host/service/task.test.tsindex b2af5a90..b989686e 100644--- a/packages/dsh-tauri-scheduler/src/host/service/task.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/task.test.ts@@ -1,5 +1,8 @@-import type { SchedulerTask } from '../types'+import type { HostContext, SchedulerTask, TaskInput } from '../types'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { inject } from '../../index'+import { resetWriteQueue, runtime } from '../config/runtime'+import { server } from '../server'import { storage } from '../storage'import { task } from './task'@@ -7,6 +10,8 @@ vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }const current: SchedulerTask = {id: 'task-1',+ delivery: 'new-session',+ status: 'active',name: 'existing',prompt: 'run it',schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00', timeZone: 'UTC' },@@ -19,40 +24,236 @@ const current: SchedulerTask = {agentPreset: 'custom-preset',}+const input: TaskInput = {+ delivery: 'new-session',+ name: 'new task',+ prompt: 'remind me',+ schedule: { kind: 'daily', time: '10:00', timeZone: 'UTC' },+}++const state = new Map<string, unknown>()+const disposers: Array<() => void> = []+let host: ReturnType<typeof installHost>++function installHost() {+ const inspect = vi.fn(async (id: string) => ({ meta: { id }, events: [] }))+ const resolveAgent = vi.fn()+ const currentInitiator = vi.fn<() => { session: { id: string } } | undefined>()+ const workspaceRegistry = { archivedSessionIds: [] as string[] }+ const context = {+ agents: { currentInitiator },+ sessionController: { inspect, resolveAgent },+ workspaceRegistry,+ webServer: { register: () => () => {} },+ logger: { error: vi.fn() },+ }+ disposers.push(server(context as unknown as HostContext))+ return { inspect, resolveAgent, currentInitiator, workspaceRegistry, context }+}+beforeEach(() => {vi.clearAllMocks()+ resetWriteQueue()vi.useFakeTimers()vi.setSystemTime(new Date('2026-01-02T00:00:00.000Z'))- vi.mocked(storage.getItem).mockResolvedValue({ tasks: [structuredClone(current)] })+ state.clear()+ state.set('tasks', { version: 2, tasks: [structuredClone(current)] })+ vi.mocked(storage.getItem).mockImplementation(async key => structuredClone(state.get(key) ?? null) as never)+ vi.mocked(storage.setItem).mockImplementation(async (key, value) => {+ state.set(key, typeof value === 'string' ? JSON.parse(value) : structuredClone(value))+ })+ host = installHost()})-afterEach(() => vi.useRealTimers())+afterEach(() => {+ disposers.splice(0).forEach(dispose => dispose())+ resetWriteQueue()+ vi.useRealTimers()+ vi.restoreAllMocks()+})-describe('task storage and update', () => {- it('reads persisted protocol fields without pruning them', async () => {+describe('unified task storage and update', () => {+ it('reads legacy records as new-session active without losing protocol fields', async () => {+ const { delivery: _delivery, status: _status, ...legacy } = current+ state.set('tasks', { version: 1, tasks: [legacy] })expect(await task.get(current.id)).toEqual(current)+ expect(host.resolveAgent).not.toHaveBeenCalled()})- it('defaults undefined patches without mutating the caller and keeps deep-equal schedules', async () => {+ it('keeps omissions, legacy fields, and an unchanged durable occurrence', async () => {const patch = { name: undefined, permission: undefined, schedule: structuredClone(current.schedule) }const result = await task.update(current.id, patch)- expect(result).toMatchObject({ ok: true, task: { name: current.name, permission: current.permission, nextRunAt: current.nextRunAt } })+ expect(result).toMatchObject({ ok: true, task: { name: current.name, permission: current.permission, nextRunAt: current.nextRunAt, module: 'legacy-module', agentPreset: 'custom-preset' } })expect(patch).toEqual({ name: undefined, permission: undefined, schedule: current.schedule })- expect(storage.setItem).toHaveBeenCalledWith('tasks', expect.stringContaining(current.nextRunAt!))+ expect(await task.get(current.id)).toMatchObject({ nextRunAt: current.nextRunAt, module: 'legacy-module' })+ })++ it('recomputes a changed calendar schedule in its own timezone', async () => {+ const result = await task.update(current.id, { schedule: { kind: 'weekly', weekdays: ['MO'], time: '16:00', timeZone: 'UTC' } })+ expect(result).toMatchObject({ ok: true, task: { nextRunAt: '2026-01-05T16:00:00.000Z' } })+ })++ it('serializes partial updates without losing either patch', async () => {+ const results = await Promise.all([+ task.update(current.id, { name: 'renamed' }),+ task.update(current.id, { prompt: 'new prompt' }),+ ])+ expect(results.every(result => result.ok)).toBe(true)+ expect(await task.get(current.id)).toMatchObject({ name: 'renamed', prompt: 'new prompt' })+ })++ it('rejects a stale complete expected record but ignores derived waiting', async () => {+ expect(await task.update(current.id, { name: 'renamed' }, { ...current, waiting: true })).toMatchObject({ ok: true })+ expect(await task.update(current.id, { prompt: 'stale edit' }, current)).toMatchObject({ ok: false, code: 'task_conflict' })+ expect(await task.get(current.id)).toMatchObject({ name: 'renamed', prompt: current.prompt })+ })++ it('does not treat a partial expected record as a complete snapshot', async () => {+ expect(await task.update(current.id, { name: 'wrong' }, { id: current.id } as SchedulerTask)).toMatchObject({ ok: false, code: 'task_conflict' })+ expect(storage.setItem).not.toHaveBeenCalled()+ })++ it('blocks claimed live-run edits and toggles but still permits explicit deletion', async () => {+ runtime.running.add(current.id)+ expect(await task.update(current.id, { name: 'changed' }, current)).toMatchObject({ ok: false, code: 'task_busy' })+ expect(await task.update(current.id, { prompt: 'changed' })).toMatchObject({ ok: false, code: 'task_busy' })+ expect(await task.toggle(current.id, true)).toMatchObject({ ok: false, code: 'task_busy' })+ expect(await task.get(current.id)).toEqual(current)+ expect(storage.setItem).not.toHaveBeenCalled()+ expect(await task.remove(current.id)).toEqual({ ok: true })+ expect(await task.complete(current, '2026-01-02T00:00:00.000Z')).toBe(false)+ expect(await task.get(current.id)).toBeNull()+ })++ it('distinguishes reversible pause from terminal inactivity', async () => {+ expect(await task.toggle(current.id, true)).toMatchObject({ ok: true, task: { status: 'active', enabled: true } })+ expect(await task.toggle(current.id, false)).toMatchObject({ ok: true, task: { status: 'active', enabled: false } })+ state.set('tasks', { version: 2, tasks: [{ ...current, status: 'inactive' }] })+ expect(await task.toggle(current.id, true)).toMatchObject({ ok: false, code: 'task_inactive' })+ expect(await task.update(current.id, { prompt: 'restart' })).toMatchObject({ ok: false, code: 'task_inactive' })+ })++ it('completion and legacy target initialization never resurrect deleted records', async () => {+ expect(await task.remove(current.id)).toEqual({ ok: true })+ expect(await task.complete(current, '2026-01-02T00:00:00.000Z', '2026-01-09T16:00:00.000Z')).toBe(false)+ await task.ensureTarget({ ...current, nextRunAt: undefined })+ expect(await task.list()).toEqual([])+ })++ it('does not advance an edited task from an older run snapshot', async () => {+ await task.update(current.id, { schedule: { kind: 'daily', time: '12:00', timeZone: 'UTC' } })+ expect(await task.complete(current, '2026-01-02T01:00:00.000Z', '2026-02-13T16:00:00.000Z')).toBe(false)+ expect(await task.get(current.id)).toMatchObject({ nextRunAt: '2026-01-02T12:00:00.000Z', schedule: { kind: 'daily' } })})- it('recomputes nextRunAt for a changed weekday array', async () => {- const result = await task.update(current.id, { schedule: { ...current.schedule, kind: 'weekly', weekdays: ['MO'], time: '16:00' } })- expect(result).toMatchObject({ ok: true, task: { nextRunAt: new Date(2026, 0, 5, 16).toISOString() } })+ it('manual completion does not consume the next scheduled occurrence', async () => {+ expect(await task.complete(current, '2026-01-02T00:00:00.000Z', undefined, false)).toBe(true)+ expect(await task.get(current.id)).toMatchObject({ status: 'active', nextRunAt: current.nextRunAt, lastRunAt: '2026-01-02T00:00:00.000Z' })})- it.each([null, false, 0, '', [], { name: 'ok', prompt: 'ok', schedule: { kind: 'hourly', minute: Number.NaN } }])('keeps validation failures for %j', async (input) => {- await expect(task.create(input as never)).resolves.toMatchObject({ ok: false })+ it('scheduled one-shot completion ends the record but retains it for history', async () => {+ expect(await task.complete(current, '2026-01-02T00:00:00.000Z')).toBe(true)+ expect(await task.get(current.id)).toMatchObject({ status: 'inactive', enabled: false })+ })++ it.each([null, false, 0, '', [], { name: 'ok', prompt: 'ok', schedule: { kind: 'hourly', minute: 1 } }])('rejects invalid or implicit-delivery creation %j', async (value) => {+ expect(await task.create(value as never)).toMatchObject({ ok: false, code: 'task_invalid' })+ expect(storage.setItem).not.toHaveBeenCalled()+ })++ it('does not replace an explicitly null required field', async () => {+ expect(await task.update(current.id, { name: null } as never)).toMatchObject({ ok: false, error: '任务名称不能为空', code: 'task_invalid' })+ expect(storage.setItem).not.toHaveBeenCalled()+ })+})++describe('this-session binding and resource authority', () => {+ it('captures the owning public initiator and validates cold without activation', async () => {+ host.currentInitiator.mockReturnValue({ session: { id: 'owner' } })+ const pending = task.create({ ...input, delivery: 'this-session' })+ host.currentInitiator.mockReturnValue({ session: { id: 'different' } })+ expect(await pending).toMatchObject({ ok: true, task: { delivery: 'this-session', status: 'active', sessionId: 'owner' } })+ expect(host.inspect).toHaveBeenCalledWith('owner')+ expect(host.resolveAgent).not.toHaveBeenCalled()+ })++ it('rejects an explicit target different from the true initiator', async () => {+ host.currentInitiator.mockReturnValue({ session: { id: 'owner' } })+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'other' })).toMatchObject({ ok: false, code: 'session_mismatch' })+ expect(host.inspect).not.toHaveBeenCalled()+ })++ it('fails closed when no binding or public authority is available', async () => {+ expect(await task.create({ ...input, delivery: 'this-session' })).toMatchObject({ ok: false, code: 'session_unavailable' })+ delete (host.context as Partial<typeof host.context>).sessionController+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'owner' })).toMatchObject({ ok: false, code: 'session_unavailable' })+ })++ it('declares the session controller required by the host inject guard', () => {+ expect(inject).toContain('sessionController')+ })++ it('rejects the core cold-session absence class without hiding read failures', async () => {+ class ApiSessionNotFound extends Error {}+ const loader = {+ import: vi.fn<() => Promise<unknown>>(async () => ({ ApiSessionNotFound })),+ unwrapExports: vi.fn((value: unknown) => value),+ }+ Object.assign(host.context, { loader })+ host.inspect.mockRejectedValueOnce(new ApiSessionNotFound('missing'))+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'missing' })).toEqual({ ok: false, error: '目标会话不存在', code: 'session_not_found' })+ expect(loader.import).toHaveBeenCalledWith('@deepseek-ai/dsh-api-session-controller')+ loader.import.mockResolvedValueOnce({ default: { ApiSessionNotFound } })+ loader.unwrapExports.mockReturnValueOnce({ ApiSessionNotFound })+ host.inspect.mockRejectedValueOnce(new ApiSessionNotFound('missing wrapped export'))+ expect(await task.validateTarget({ ...current, permission: undefined, delivery: 'this-session', sessionId: 'missing' })).toEqual({ ok: false, error: '目标会话不存在', code: 'session_not_found' })+ host.inspect.mockRejectedValueOnce(new Error('disk read failed'))+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'owner' })).toEqual({ ok: false, error: '宿主无法读取目标会话', code: 'session_unavailable' })+ loader.import.mockRejectedValueOnce(new Error('module unavailable'))+ host.inspect.mockRejectedValueOnce(new ApiSessionNotFound('missing'))+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'missing' })).toEqual({ ok: false, error: '宿主无法读取目标会话', code: 'session_unavailable' })expect(storage.setItem).not.toHaveBeenCalled()+ expect(host.resolveAgent).not.toHaveBeenCalled()})- it('does not replace an explicitly null required field with a default', async () => {- await expect(task.update(current.id, { name: null } as never)).resolves.toEqual({ ok: false, error: '任务名称不能为空' })+ it('rejects archived, missing, and delegated session targets without activation', async () => {+ host.workspaceRegistry.archivedSessionIds.push('archived')+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'archived' })).toMatchObject({ ok: false, code: 'session_archived' })+ host.inspect.mockRejectedValueOnce({ code: 'session/not-found' })+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'missing' })).toMatchObject({ ok: false, code: 'session_not_found' })+ host.inspect.mockResolvedValueOnce({ meta: { id: 'child', origin: 'subagent', delegationDepth: 1 }, events: [] } as never)+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'child' })).toMatchObject({ ok: false, code: 'session_mismatch' })expect(storage.setItem).not.toHaveBeenCalled()+ expect(host.resolveAgent).not.toHaveBeenCalled()+ })++ it.each(['workspaceId', 'permission', 'provider', 'model', 'reasoningEffort'] as const)('rejects this-session override %s', async (field) => {+ expect(await task.create({ ...input, delivery: 'this-session', sessionId: 'owner', [field]: 'override' })).toMatchObject({ ok: false, code: 'task_invalid' })+ expect(host.inspect).not.toHaveBeenCalled()+ })++ it('retains per-task resources for new-session and forbids a bound id', async () => {+ const resources = { workspaceId: 'ws', permission: 'read-only', provider: 'provider', model: 'model', reasoningEffort: 'high' }+ expect(await task.create({ ...input, ...resources })).toMatchObject({ ok: true, task: resources })+ expect(await task.create({ ...input, sessionId: 'owner' })).toMatchObject({ ok: false, code: 'task_invalid' })+ })++ it('switches modes only after explicitly clearing incompatible overrides', async () => {+ expect(await task.update(current.id, { delivery: 'this-session', sessionId: 'owner' })).toMatchObject({ ok: false, code: 'task_invalid' })+ const result = await task.update(current.id, { delivery: 'this-session', sessionId: 'owner', permission: '' })+ expect(result).toMatchObject({ ok: true, task: { delivery: 'this-session', sessionId: 'owner', nextRunAt: current.nextRunAt } })+ if (!result.ok)+ throw new Error(result.error)+ expect(result.task).not.toHaveProperty('permission')+ expect(await task.update(current.id, { delivery: 'new-session' })).toMatchObject({ ok: true, task: { delivery: 'new-session' } })+ expect(await task.get(current.id)).not.toHaveProperty('sessionId')+ })++ it('session stop terminates only matching bound tasks and preserves records', async () => {+ state.set('tasks', { version: 2, tasks: [current, { ...current, id: 'bound', delivery: 'this-session', sessionId: 'owner', permission: undefined }] })+ await task.stopSession('owner')+ expect(await task.get('bound')).toMatchObject({ status: 'inactive', enabled: false })+ expect(await task.get(current.id)).toEqual(current)+ expect(await task.toggle('bound', true)).toMatchObject({ ok: false, code: 'task_inactive' })})})diff --git a/packages/dsh-tauri-scheduler/src/host/service/task.ts b/packages/dsh-tauri-scheduler/src/host/service/task.tsindex 72b396ed..e8ff23f0 100644--- a/packages/dsh-tauri-scheduler/src/host/service/task.ts+++ b/packages/dsh-tauri-scheduler/src/host/service/task.ts@@ -1,156 +1,219 @@-import type { OperationResult, SchedulerSchedule, SchedulerTask, TaskInput } from '../types'+import type { SessionController } from '@deepseek-ai/dsh-api-session-controller'+import type { HostContext, OperationResult, SchedulerSchedule, SchedulerTask, TaskInput } from '../types'import { randomUUID } from 'node:crypto'+import { getServerContext } from 'dsh-h3/utils'import { defineService } from 'dsh-tauri'-import { conformsTo, defaults, filter, find, findIndex, isArray, isBoolean, isEmpty, isEqual, isNil, isObject, isString, omitBy, pick, reject } from 'lodash-es'-import { withWriteQueue } from '../config/runtime'+import { isEqual } from 'lodash-es'+import { runtime, withTaskQueue, withWriteQueue } from '../config/runtime'+import { server } from '../server'import { storage } from '../storage'+import { isSchedulerSessionNotFound } from '../utils/agent-runtime'import { localTimeZone, nextOccurrence, validateSchedule } from '../utils/schedule'+import { SessionOperationTimeout, withSessionDeadline } from '../utils/session-deadline'+import { sameTaskRecord } from '../utils/task-record'const SCHEDULER_TASKS_KEY = 'tasks'-const SCHEDULER_PROMPT_MAX_LENGTH = 64_000-const SCHEDULER_NAME_MAX_LENGTH = 120+const RESOURCE_FIELDS = ['workspaceId', 'permission', 'provider', 'model', 'reasoningEffort'] as const+const TEXT_FIELDS = ['recommendationId', ...RESOURCE_FIELDS] as constexport const task = defineService({async list(search?: string): Promise<SchedulerTask[]> {const all = await readAll()const needle = search?.trim().toLowerCase() ?? ''- return needle === '' ? all : filter(all, item => item.name.toLowerCase().includes(needle))+ return needle === '' ? all : all.filter(item => item.name.toLowerCase().includes(needle))},async get(id: string): Promise<SchedulerTask | null> {- return find(await readAll(), { id }) ?? null+ return (await readAll()).find(item => item.id === id) ?? null},async create(input: TaskInput): Promise<OperationResult<{ task: SchedulerTask }>> {- const invalid = validateInput(input)- if (invalid !== null)- return { ok: false, error: invalid }- const created = build(input)- await saveTask(created)- return { ok: true, task: created }+ const initiator = input?.delivery === 'this-session' ? currentInitiator() : undefined+ return withTaskQueue(() => withWriteQueue(async () => {+ if (runtime.stopping)+ return unavailable()+ const invalid = validateInput(input)+ if (invalid !== null)+ return { ok: false, error: invalid, code: 'task_invalid' }+ const sessionId = input.delivery === 'this-session' ? input.sessionId || initiator?.session.id : undefined+ const bound = await validateBinding(input, sessionId, initiator?.session.id)+ if (!bound.ok)+ return bound+ const created = build({ ...input, sessionId })+ const all = await readAll()+ all.push(created)+ await writeTasks(all)+ return { ok: true, task: created }+ }))},- async update(id: string, patch: Partial<TaskInput>): Promise<OperationResult<{ task: SchedulerTask }>> {- const current = await findTask(id)- if (current === null)- return { ok: false, error: '任务不存在' }- const merged: TaskInput = defaults({}, patch, current)- const invalid = validateInput(merged)- if (invalid !== null)- return { ok: false, error: invalid }- const rebuilt = build(merged)- const updated: SchedulerTask = {- ...rebuilt,- id: current.id,- createdAt: current.createdAt,- updatedAt: new Date().toISOString(),- lastRunAt: current.lastRunAt,- nextRunAt: !isEqual(rebuilt.schedule, current.schedule) || (rebuilt.enabled && isNil(current.nextRunAt))- ? rebuilt.nextRunAt- : current.nextRunAt,- }- await saveTask(updated)- return { ok: true, task: updated }+ async update(id: string, patch: Partial<TaskInput>, expected?: SchedulerTask): Promise<OperationResult<{ task: SchedulerTask }>> {+ const initiator = currentInitiator()+ return withTaskQueue(() => withWriteQueue(async () => {+ if (runtime.stopping)+ return unavailable()+ const all = await readAll()+ const at = all.findIndex(item => item.id === id)+ if (at === -1)+ return notFound()+ const current = all[at]!+ if (expected !== undefined && !sameTaskRecord(current, expected))+ return { ok: false, error: '任务已发生变化,请刷新后重试', code: 'task_conflict' }+ if (current.status === 'inactive')+ return inactive()+ if (runtime.running.has(id))+ return { ok: false, error: '任务正在执行中,暂不能修改任务', code: 'task_busy' }+ if (runtime.pending.has(id))+ return { ok: false, error: '投递正在等待会话持久化,暂不能修改任务', code: 'task_pending' }+ const definedPatch = Object.fromEntries(Object.entries(patch ?? {}).filter(([, value]) => value !== undefined))+ const merged = { ...current, ...definedPatch } as TaskInput+ if (merged.delivery === 'this-session' && !merged.sessionId)+ merged.sessionId = initiator?.session.id+ if (merged.delivery === 'new-session') {+ if (patch.sessionId !== undefined && patch.sessionId !== '')+ return { ok: false, error: '新会话投递不能绑定 sessionId', code: 'task_invalid' }+ delete merged.sessionId+ }+ const invalid = validateInput(merged)+ if (invalid !== null)+ return { ok: false, error: invalid, code: 'task_invalid' }+ const bindingChanged = merged.delivery !== current.delivery || merged.sessionId !== current.sessionId+ const bound = await validateBinding(merged, merged.sessionId, initiator?.session.id, bindingChanged)+ if (!bound.ok)+ return bound+ const rebuilt = build(merged)+ runtime.failed.delete(id)+ const updated: SchedulerTask = {+ ...current,+ ...rebuilt,+ id: current.id,+ status: current.status,+ createdAt: current.createdAt,+ lastRunAt: current.lastRunAt,+ nextRunAt: isEqual(rebuilt.schedule, current.schedule) ? current.nextRunAt : rebuilt.nextRunAt,+ }+ for (const field of TEXT_FIELDS) {+ if (!merged[field])+ delete updated[field]+ }+ if (updated.delivery === 'new-session')+ delete updated.sessionId+ delete updated.waiting+ all[at] = updated+ await writeTasks(all)+ return { ok: true, task: updated }+ }))},async remove(id: string): Promise<OperationResult> {- return await removeTask(id) ? { ok: true } : { ok: false, error: '任务不存在' }+ return withTaskQueue(() => withWriteQueue(async () => {+ const all = await readAll()+ const remaining = all.filter(item => item.id !== id)+ if (remaining.length === all.length)+ return notFound()+ await writeTasks(remaining)+ return { ok: true }+ }))},async toggle(id: string, enabled: boolean): Promise<OperationResult<{ task: SchedulerTask }>> {- const current = await findTask(id)- if (current === null)- return { ok: false, error: '任务不存在' }- const next: SchedulerTask = { ...current, enabled, updatedAt: new Date().toISOString() }- if (enabled && isNil(next.nextRunAt)) {- const occurrence = nextOccurrence(next.schedule, Date.now())- if (occurrence !== undefined)- next.nextRunAt = new Date(occurrence).toISOString()- }- await saveTask(next)- return { ok: true, task: next }+ if (typeof enabled !== 'boolean')+ return { ok: false, error: 'enabled 必须是布尔值', code: 'task_invalid' }+ return task.update(id, { enabled })},- async advance(id: string, lastRunAt?: string, nextRunAt?: string): Promise<void> {- const current = await findTask(id)- if (current === null)- return- await saveTask({- ...current,- lastRunAt,- nextRunAt,- updatedAt: new Date().toISOString(),+ async complete(expected: SchedulerTask, lastRunAt: string, nextRunAt?: string, consume = true): Promise<boolean> {+ return withWriteQueue(async () => {+ const all = await readAll()+ const at = all.findIndex(item => item.id === expected.id)+ if (at === -1 || !sameTaskRecord(all[at]!, expected))+ return false+ all[at] = {+ ...all[at]!,+ lastRunAt,+ nextRunAt: consume ? nextRunAt : all[at]!.nextRunAt,+ status: consume && nextRunAt === undefined ? 'inactive' : all[at]!.status,+ updatedAt: new Date().toISOString(),+ }+ await writeTasks(all)+ return true})},-})-// --- internal -----async function readAll(): Promise<SchedulerTask[]> {- const raw = await storage.getItem<{ tasks?: unknown[] }>(SCHEDULER_TASKS_KEY)- return filter(isArray(raw?.tasks) ? raw.tasks : [], isTask)-}+ async ensureTarget(expected: SchedulerTask): Promise<void> {+ await withWriteQueue(async () => {+ const all = await readAll()+ const at = all.findIndex(item => item.id === expected.id)+ if (at === -1 || !sameTaskRecord(all[at]!, expected) || expected.status !== 'active' || expected.nextRunAt)+ return+ const next = expected.schedule.kind === 'once' ? Date.parse(expected.schedule.at) : nextOccurrence(expected.schedule, Date.now())+ all[at] = { ...all[at]!, nextRunAt: next === undefined ? undefined : new Date(next).toISOString(), status: next === undefined ? 'inactive' : 'active' }+ await writeTasks(all)+ })+ },-async function findTask(id: string): Promise<SchedulerTask | null> {- return find(await readAll(), { id }) ?? null-}+ async stopSession(sessionId: string): Promise<void> {+ await withTaskQueue(() => withWriteQueue(async () => {+ const all = await readAll()+ const next = all.map(item => item.delivery === 'this-session' && item.sessionId === sessionId && item.status === 'active'+ ? { ...item, status: 'inactive' as const, enabled: false, nextRunAt: undefined, updatedAt: new Date().toISOString() }+ : item)+ if (!isEqual(next, all))+ await writeTasks(next)+ }))+ },-async function saveTask(next: SchedulerTask): Promise<void> {- await withWriteQueue(async () => {- const all = await readAll()- const at = findIndex(all, { id: next.id })- if (at === -1)- all.push(next)- else- all[at] = next- await writeTasks(all)- })-}+ async validateTarget(item: SchedulerTask): Promise<OperationResult> {+ return validateBinding(item, item.sessionId)+ },+})-async function removeTask(id: string): Promise<boolean> {- return withWriteQueue(async () => {- const all = await readAll()- const remaining = reject(all, { id })- if (remaining.length === all.length)- return false- await writeTasks(remaining)- return true+async function readAll(): Promise<SchedulerTask[]> {+ const raw = await storage.getItem<{ tasks?: unknown[] }>(SCHEDULER_TASKS_KEY)+ return (Array.isArray(raw?.tasks) ? raw.tasks : []).flatMap((value) => {+ if (!isStoredTask(value))+ return []+ const next = { ...value, delivery: value.delivery ?? 'new-session', status: value.status ?? 'active' } as SchedulerTask+ delete next.waiting+ if (next.delivery === 'new-session')+ delete next.sessionId+ return [next]})}-function isTask(value: unknown): value is SchedulerTask {- return conformsTo(value, {- id: isString,- name: isString,- prompt: isString,- enabled: isBoolean,- schedule: validateSchedule,- })+function isStoredTask(value: unknown): value is SchedulerTask {+ if (value === null || typeof value !== 'object' || Array.isArray(value))+ return false+ const item = value as Partial<SchedulerTask>+ return typeof item.id === 'string' && typeof item.name === 'string' && typeof item.prompt === 'string'+ && typeof item.enabled === 'boolean' && validateSchedule(item.schedule)+ && (item.delivery === undefined || item.delivery === 'new-session' || (item.delivery === 'this-session' && typeof item.sessionId === 'string' && item.sessionId.length > 0))+ && (item.status === undefined || item.status === 'active' || item.status === 'inactive')}async function writeTasks(all: SchedulerTask[]): Promise<void> {- await storage.setItem(SCHEDULER_TASKS_KEY, `${JSON.stringify({ version: 1, tasks: all }, null, 2)}\n`)+ await storage.setItem(SCHEDULER_TASKS_KEY, `${JSON.stringify({ version: 2, tasks: all }, null, 2)}\n`)}-const OPTIONAL_FIELDS = ['recommendationId', 'workspaceId', 'permission', 'provider', 'model', 'reasoningEffort'] as const-function build(input: TaskInput): SchedulerTask {const now = new Date()const schedule = input.schedule- const anchored = (schedule.kind === 'interval' || schedule.kind === 'custom') && isEmpty(schedule.anchor)+ const anchor = (schedule.kind === 'interval' || schedule.kind === 'custom') && !schedule.anchor? { ...schedule, anchor: now.toISOString() }: schedule- const timeZone = isEmpty(anchored.timeZone) ? localTimeZone() : anchored.timeZone- const normalized = { ...anchored, timeZone } as SchedulerSchedule+ const normalized = { ...anchor, timeZone: anchor.timeZone || localTimeZone() } as SchedulerScheduleconst next = nextOccurrence(normalized, now.getTime())return {id: `task-${randomUUID()}`,+ delivery: input.delivery,+ status: 'active',+ ...(input.delivery === 'this-session' ? { sessionId: input.sessionId } : {}),name: input.name.trim(),schedule: normalized,prompt: input.prompt,- ...omitBy(pick(input, ...OPTIONAL_FIELDS), isEmpty),+ ...Object.fromEntries(TEXT_FIELDS.filter(field => input[field]).map(field => [field, input[field]])),enabled: input.enabled ?? true,createdAt: now.toISOString(),updatedAt: now.toISOString(),@@ -159,9 +222,11 @@ function build(input: TaskInput): SchedulerTask {}function validateInput(input: unknown): string | null {- if (!isObject(input))+ if (input === null || typeof input !== 'object' || Array.isArray(input))return '请求体必须是对象'const value = input as Partial<TaskInput>+ if (value.delivery !== 'this-session' && value.delivery !== 'new-session')+ return '必须明确选择 delivery:this-session 或 new-session'if (typeof value.name !== 'string' || value.name.trim() === '')return '任务名称不能为空'if (value.name.trim().length > SCHEDULER_NAME_MAX_LENGTH)@@ -170,7 +235,65 @@ function validateInput(input: unknown): string | null {return '任务指令不能为空'if (value.prompt.length > SCHEDULER_PROMPT_MAX_LENGTH)return `任务指令不能超过 ${SCHEDULER_PROMPT_MAX_LENGTH} 个字符`- if (!validateSchedule(value.schedule))+ const schedule = value.schedule?.kind === 'custom' && !value.schedule.anchor ? { ...value.schedule, anchor: new Date().toISOString() } : value.schedule+ if (!validateSchedule(schedule))return '计划配置无效'+ if (value.enabled !== undefined && typeof value.enabled !== 'boolean')+ return 'enabled 必须是布尔值'+ if (TEXT_FIELDS.some(field => value[field] !== undefined && typeof value[field] !== 'string'))+ return '资源配置必须是字符串'+ if (value.sessionId !== undefined && typeof value.sessionId !== 'string')+ return 'sessionId 必须是字符串'return null}++function currentInitiator(): { session: { id: string } } | undefined {+ return getServerContext<HostContext>(server).agents?.currentInitiator?.()+}++async function validateBinding(input: Pick<TaskInput, 'delivery' | 'sessionId' | 'workspaceId' | 'permission' | 'provider' | 'model' | 'reasoningEffort'>, sessionId?: string, initiatorId?: string, verifySession = true): Promise<OperationResult> {+ if (input.delivery === 'new-session')+ return input.sessionId ? { ok: false, error: '新会话投递不能绑定 sessionId', code: 'task_invalid' } : { ok: true }+ if (!sessionId)+ return { ok: false, error: '原会话投递缺少可确认的 sessionId', code: 'session_unavailable' }+ if (initiatorId && sessionId !== initiatorId)+ return { ok: false, error: '不能代表另一个会话创建原会话任务', code: 'session_mismatch' }+ if (RESOURCE_FIELDS.some(field => input[field]))+ return { ok: false, error: '原会话投递继承会话资源,不能覆盖工作区、权限或模型', code: 'task_invalid' }+ if (!verifySession)+ return { ok: true }+ const ctx = getServerContext<HostContext>(server)+ if (typeof ctx.sessionController?.inspect !== 'function' || !Array.isArray(ctx.workspaceRegistry?.archivedSessionIds))+ return { ok: false, error: '宿主无法验证目标会话', code: 'session_unavailable' }+ if (ctx.workspaceRegistry.archivedSessionIds.includes(sessionId))+ return { ok: false, error: '目标会话已归档', code: 'session_archived' }+ try {+ const inspected = await withSessionDeadline<Awaited<ReturnType<SessionController['inspect']>>>(ctx.sessionController.inspect(sessionId))+ if (inspected?.meta?.id !== sessionId)+ return { ok: false, error: '目标会话不存在', code: 'session_not_found' }+ if (inspected.meta.origin === 'subagent' || (inspected.meta.delegationDepth ?? 0) > 0)+ return { ok: false, error: '不能为子代理会话创建原会话任务', code: 'session_mismatch' }+ if (ctx.workspaceRegistry.archivedSessionIds.includes(sessionId))+ return { ok: false, error: '目标会话已归档', code: 'session_archived' }+ return { ok: true }+ }+ catch (error) {+ if (error instanceof SessionOperationTimeout)+ return { ok: false, error: error.message, code: 'session_unavailable' }+ return await isSchedulerSessionNotFound(ctx.loader, error)+ ? { ok: false, error: '目标会话不存在', code: 'session_not_found' }+ : { ok: false, error: '宿主无法读取目标会话', code: 'session_unavailable' }+ }+}++function notFound(): OperationResult<never> {+ return { ok: false, error: '任务不存在', code: 'task_not_found' }+}++function inactive(): OperationResult<never> {+ return { ok: false, error: '任务已结束,不能重新启用或运行', code: 'task_inactive' }+}++function unavailable(): OperationResult<never> {+ return { ok: false, error: '调度器正在卸载', code: 'scheduler_stopping' }+}diff --git a/packages/dsh-tauri-scheduler/src/host/tools/create-task.ts b/packages/dsh-tauri-scheduler/src/host/tools/create-task.tsindex 378e0ff4..b8701746 100644--- a/packages/dsh-tauri-scheduler/src/host/tools/create-task.ts+++ b/packages/dsh-tauri-scheduler/src/host/tools/create-task.ts@@ -8,7 +8,9 @@ const outputSchema = {ok: { type: 'boolean' },taskId: { type: 'string' },nextRunAt: nullableText,+ task: { type: 'object', additionalProperties: true },error: { type: 'string' },+ code: { type: 'string' },},required: ['ok'],}@@ -19,10 +21,14 @@ export function createTaskTool(): any {description:'Create a scheduled task that runs a prompt automatically on a schedule. '+ 'Use when the user asks to set up a daily, weekly, workday, or interval automation '- + '(e.g. "write a daily report every weekday at 9am"). The task runs in a fresh session.',+ + '(e.g. "write a daily report every weekday at 9am"). Explicitly choose delivery: '+ + 'this-session queues a reminder in the originating session using its existing resources; '+ + 'new-session starts a separate agent run with its own workspace/permission/model. Do not impersonate another session.',parameters: {type: 'object',properties: {+ delivery: { type: 'string', enum: ['this-session', 'new-session'], description: 'Required explicit delivery mode.' },+ sessionId: { type: 'string', description: 'this-session only; omit to bind to the owning current initiator.' },name: { type: 'string', description: 'Task name, e.g. "Daily report".' },prompt: { type: 'string', description: 'The task instruction run in the scheduled session.' },schedule: scheduleParameters,@@ -32,16 +38,16 @@ export function createTaskTool(): any {model: { type: 'string', description: 'Optional pinned model id (pair with provider).' },reasoningEffort: { type: 'string', description: 'Optional pinned reasoning effort id for the selected model.' },},- required: ['name', 'prompt', 'schedule'],+ required: ['delivery', 'name', 'prompt', 'schedule'],},output: {schema: outputSchema,- render: (_args: unknown, value: any) => value.ok- ? textBlock(`✅ 定时任务已创建:${value.taskId}(下次运行 ${value.nextRunAt ?? '待计算'})`)- : textBlock(`❌ 创建定时任务失败:${value.error}`),+ render: (_args: unknown, value: unknown) => textBlock(JSON.stringify(value)),},async execute(args: any) {const result = await task.create({+ delivery: args.delivery,+ sessionId: args.sessionId,name: String(args.name ?? ''),prompt: String(args.prompt ?? ''),schedule: args.schedule,@@ -52,8 +58,8 @@ export function createTaskTool(): any {reasoningEffort: args.reasoningEffort === undefined ? undefined : String(args.reasoningEffort),})if (!result.ok)- return { ok: false, error: result.error }- return { ok: true, taskId: result.task.id, nextRunAt: result.task.nextRunAt ?? null }+ return result+ return { ok: true, taskId: result.task.id, nextRunAt: result.task.nextRunAt ?? null, task: result.task }},}}diff --git a/packages/dsh-tauri-scheduler/src/host/tools/list-tasks.ts b/packages/dsh-tauri-scheduler/src/host/tools/list-tasks.tsindex e28121f8..eba1a503 100644--- a/packages/dsh-tauri-scheduler/src/host/tools/list-tasks.ts+++ b/packages/dsh-tauri-scheduler/src/host/tools/list-tasks.ts@@ -4,17 +4,11 @@ import { textBlock } from '../utils/tool'export function listTasksTool(): any {return {name: 'scheduler_list',- description: 'List all scheduled tasks with their next run time and enabled state.',+ description: 'List the unified scheduler tasks with delivery mode, bound session, terminal status, next occurrence, and reversible enabled state.',parameters: { type: 'object', properties: {} },output: {schema: { type: 'object', additionalProperties: true, properties: { ok: { type: 'boolean' }, tasks: { type: 'array' } }, required: ['ok'] },- render: (_args: unknown, value: any) => {- if (!value.ok)- return textBlock(`❌ 获取定时任务失败:${value.error}`)- const rows = (value.tasks as any[] ?? []).map((task: any) =>- `- ${task.enabled ? '🟢' : '⏸️'} ${task.name} (${task.id}) next=${task.nextRunAt ?? '-'}`)- return textBlock(rows.length ? `当前定时任务:\n${rows.join('\n')}` : '当前没有定时任务。')- },+ render: (_args: unknown, value: unknown) => textBlock(JSON.stringify(value)),},async execute() {return { ok: true, tasks: await task.list() }diff --git a/packages/dsh-tauri-scheduler/src/host/tools/update-task.test.ts b/packages/dsh-tauri-scheduler/src/host/tools/update-task.test.tsindex f0e4ad83..4f5c2f2c 100644--- a/packages/dsh-tauri-scheduler/src/host/tools/update-task.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/tools/update-task.test.ts@@ -10,6 +10,8 @@ vi.mock('../service/scheduler', () => ({ scheduler: { trigger: vi.fn() } }))const taskFixture: SchedulerTask = {id: 'task-1',+ delivery: 'new-session',+ status: 'active',name: 'nightly',schedule: { kind: 'interval', everyMinutes: 30, timeZone: 'UTC' },prompt: 'run the nightly job',@@ -33,7 +35,9 @@ describe('scheduler_update', () => {it('task_id 是唯一必填参数,其余字段均可选', () => {expect(tool.parameters.required).toEqual(['task_id'])expect(Object.keys(tool.parameters.properties).sort()).toEqual([+ 'delivery','enabled',+ 'expected','model','name','permission',@@ -42,6 +46,7 @@ describe('scheduler_update', () => {'reasoningEffort','run_now','schedule',+ 'sessionId','task_id','workspaceId',])diff --git a/packages/dsh-tauri-scheduler/src/host/tools/update-task.ts b/packages/dsh-tauri-scheduler/src/host/tools/update-task.tsindex e2dd3a82..564bc296 100644--- a/packages/dsh-tauri-scheduler/src/host/tools/update-task.ts+++ b/packages/dsh-tauri-scheduler/src/host/tools/update-task.ts@@ -24,10 +24,15 @@ export function updateTaskTool(): any {description:'Update a scheduled task by id: rename it, rewrite its instruction, replace its schedule, '+ 'pause or resume it (enabled), or change the workspace/permission/model used by its runs. '- + 'Omitted fields keep their current value. Set run_now to also trigger an immediate manual run.',+ + 'Omitted fields keep their current value; inactive tasks cannot be restarted and live runs cannot be edited. '+ + 'this-session inherits the bound session resources and rejects overrides. '+ + 'Set run_now to also trigger an immediate manual run without consuming the next scheduled occurrence.',parameters: {type: 'object',properties: {+ expected: { type: 'object', additionalProperties: true, description: 'Optional complete task snapshot for optimistic concurrency; obtain from scheduler_list.' },+ delivery: { type: 'string', enum: ['this-session', 'new-session'], description: 'New delivery mode; resources cannot override this-session.' },+ sessionId: { type: 'string', description: 'Bound session for this-session only.' },task_id: { type: 'string', description: 'Task id.' },name: { type: 'string', description: 'New task name.' },prompt: { type: 'string', description: 'New task instruction.' },@@ -44,15 +49,15 @@ export function updateTaskTool(): any {},output: {schema: outputSchema,- render: (_args: unknown, value: any) => value.ok- ? textBlock(`✅ 定时任务已更新:${value.taskId}(下次运行 ${value.nextRunAt ?? '待计算'})${value.ran === true ? ',已触发立即运行' : ''}`)- : textBlock(`❌ ${value.error}`),+ render: (_args: unknown, value: unknown) => textBlock(JSON.stringify(value)),},async execute(args: any) {const id = String(args.task_id ?? '')- const result = await task.update(id, patchOf(args))+ const result = args.expected === undefined+ ? await task.update(id, patchOf(args))+ : await task.update(id, patchOf(args), args.expected)if (!result.ok)- return { ok: false, error: result.error }+ return { ok: false, error: result.error, ...(result.code ? { code: result.code } : {}) }const updated = { ok: true, taskId: result.task.id, nextRunAt: result.task.nextRunAt ?? null }if (args.run_now !== true)return updated@@ -72,6 +77,10 @@ function patchOf(args: any): Partial<TaskInput> {if (args[field] !== undefined)patch[field] = String(args[field])}+ if (args.delivery !== undefined)+ patch.delivery = args.delivery+ if (args.sessionId !== undefined)+ patch.sessionId = args.sessionIdif (args.schedule !== undefined)patch.schedule = args.scheduleif (args.enabled !== undefined)diff --git a/packages/dsh-tauri-scheduler/src/host/types/index.ts b/packages/dsh-tauri-scheduler/src/host/types/index.tsindex f247a08c..7878979e 100644--- a/packages/dsh-tauri-scheduler/src/host/types/index.ts+++ b/packages/dsh-tauri-scheduler/src/host/types/index.ts@@ -1,5 +1,19 @@+import type { ContextFormed, UserMessage } from '@deepseek-ai/dsh-llm'import type { SCHEDULE_KINDS } from '../../shared/constants'+declare module '@deepseek-ai/dsh-llm' {+ interface MessageSourceMap {+ schedule: { kind: 'schedule' } & ContextFormed+ scheduler: { kind: 'scheduler', taskId: string, runId: string, scheduledFor: string }+ }+}++declare module '@deepseek-ai/dsh-workspace' {+ interface SessionActivityKindMap {+ schedule: true+ }+}+export type HostContext = anyexport type ScheduleKind = (typeof SCHEDULE_KINDS)[number]@@ -75,8 +89,15 @@ export type SchedulerScheduleInput| { kind: 'monthly', day: number, time: string, timeZone?: string }| { kind: 'custom', everyDays: number, anchor?: string, time: string, timeZone?: string }+export type TaskDelivery = 'this-session' | 'new-session'++export type TaskStatus = 'active' | 'inactive'+export interface SchedulerTask {id: string+ delivery: TaskDelivery+ status: TaskStatus+ sessionId?: stringname: stringschedule: SchedulerScheduleprompt: string@@ -93,7 +114,6 @@ export interface SchedulerTask {updatedAt: stringlastRunAt?: stringnextRunAt?: string- /** 派生视图字段:已到点但受并发上限压住未启动;不落盘,读取路径每次重算。 */waiting?: boolean}@@ -101,6 +121,7 @@ export interface SchedulerRun {id: stringtaskId: stringtaskName: string+ prompt?: stringtrigger: RunTriggerstatus: RunStatusscheduledFor: string@@ -111,6 +132,8 @@ export interface SchedulerRun {}export interface TaskInput {+ delivery: TaskDelivery+ sessionId?: stringname: stringschedule: SchedulerScheduleInputprompt: string@@ -123,6 +146,58 @@ export interface TaskInput {enabled?: boolean}+export interface DeliveryRecord {+ id: string+ taskId: string+ taskName: string+ delivery: 'this-session'+ occurrence: string+ trigger: RunTrigger+ sessionId: string+ scheduledAt: string+ deliveredAt: string+ messageId: string+ prompt: string+}++export type HistoryRecord = DeliveryRecord | (SchedulerRun & {+ delivery: 'new-session'+ occurrence: string+})++export interface HistoryPage {+ records: HistoryRecord[]+ runs: SchedulerRun[]+ nextBefore?: string+ earlierRecordsUnavailable: boolean+ earlierRecordsPruned: boolean+ retention: { days: number, records: number }+}++export interface HistoryQuery {+ taskId?: string+ limit: number+ before?: string+}++export interface OccurrenceJournal {+ id: string+ task: SchedulerTask+ trigger: RunTrigger+ scheduledAt: string+ completedAt?: string+ run?: SchedulerRun+}++export interface PendingDelivery {+ task: SchedulerTask+ trigger: RunTrigger+ scheduledAt: string+ nextRunAt?: string+ deliveredAt: string+ message: UserMessage+}+export interface PermissionOption {value: stringname: string@@ -166,4 +241,4 @@ export interface SchedulerOptions {export type OperationResult<T extends object = object>= | ({ ok: true } & T)- | { ok: false, error: string }+ | { ok: false, error: string, code?: string }diff --git a/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.ts b/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.tsindex 164918b1..3c19feb5 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.ts@@ -1,5 +1,6 @@import type { PlatformModuleLoader, SchedulerRuntimeModules, SetupAgentLike } from './agent-runtime.types'import { isFunction } from 'lodash-es'+import { withSessionDeadline } from './session-deadline'type RuntimeModuleExports = Partial<SchedulerRuntimeModules>@@ -16,6 +17,29 @@ export async function loadSchedulerRuntimeModules(loader: PlatformModuleLoader):}}+export async function loadSchedulerMessageFactory(loader: PlatformModuleLoader): Promise<SchedulerRuntimeModules['createUserMessage']> {+ const llm = await loader.import('@deepseek-ai/dsh-llm')+ return resolveRuntimeExport(loader, llm, 'createUserMessage')+}++export async function isSchedulerSessionNotFound(loader: PlatformModuleLoader | undefined, error: unknown): Promise<boolean> {+ if (typeof error !== 'object' || error === null)+ return false+ if ((error as { code?: unknown }).code === 'session/not-found')+ return true+ if (typeof loader?.import !== 'function')+ return false+ try {+ const exports = await withSessionDeadline(loader.import('@deepseek-ai/dsh-api-session-controller'))+ const direct = (exports as { ApiSessionNotFound?: unknown } | null)?.ApiSessionNotFound+ const constructor = typeof direct === 'function' ? direct : (loader.unwrapExports(exports) as { ApiSessionNotFound?: unknown } | null)?.ApiSessionNotFound+ return typeof constructor === 'function' && error instanceof constructor+ }+ catch {+ return false+ }+}+export function resolveSetupAgent(agentCtx: unknown,createdAgent?: SetupAgentLike,diff --git a/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.types.ts b/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.types.tsindex afc66d05..a8811e47 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.types.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/agent-runtime.types.ts@@ -1,4 +1,5 @@import type { ModelSelection } from '@deepseek-ai/dsh-agent'+import type { UserMessage } from '@deepseek-ai/dsh-llm'export interface PlatformModuleLoader {import: (name: string) => Promise<unknown>@@ -13,7 +14,7 @@ export interface SchedulerRuntimeModules {createUserMessage: (value: {content: readonly { type: 'text', text: string }[]source: unknown- }) => unknown+ }) => UserMessagesetApprovalPolicy: (session: unknown, policy: 'ask' | 'never') => void}diff --git a/packages/dsh-tauri-scheduler/src/host/utils/occurrence.test.ts b/packages/dsh-tauri-scheduler/src/host/utils/occurrence.test.tsnew file mode 100644index 00000000..71d7131c--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/utils/occurrence.test.ts@@ -0,0 +1,35 @@+import type { SchedulerSchedule } from '../types'+import { describe, expect, it } from 'vitest'+import { nextFutureOccurrence } from './occurrence'++const instant = (value: string): number => Date.parse(value)++describe('durable occurrence advancement', () => {+ it('keeps a durable interval phase instead of reapplying the configured anchor', () => {+ const rule: SchedulerSchedule = { kind: 'interval', everyMinutes: 15, anchor: '2026-06-01T00:00:00.000Z', timeZone: 'UTC' }+ expect(nextFutureOccurrence(rule, instant('2026-06-01T00:47:17.000Z'), instant('2026-06-01T00:59:00.000Z'))).toBe(instant('2026-06-01T01:02:17.000Z'))+ })++ it('skips intervals that elapsed while the accepted occurrence was completing', () => {+ const rule: SchedulerSchedule = { kind: 'interval', everyMinutes: 15, anchor: '2026-06-01T00:00:00.000Z', timeZone: 'UTC' }+ expect(nextFutureOccurrence(rule, instant('2026-06-01T00:47:17.000Z'), instant('2026-06-01T01:32:17.000Z'))).toBe(instant('2026-06-01T01:47:17.000Z'))+ })++ it('cannot repeat a committed occurrence after the wall clock rolls back', () => {+ expect(nextFutureOccurrence({ kind: 'daily', time: '12:00', timeZone: 'UTC' }, instant('2026-06-01T12:00:00.000Z'), instant('2026-05-31T12:00:00.000Z'))).toBe(instant('2026-06-02T12:00:00.000Z'))+ })++ it('folds elapsed calendar slots before selecting the strictly future target', () => {+ expect(nextFutureOccurrence({ kind: 'daily', time: '12:00', timeZone: 'UTC' }, instant('2026-06-01T12:00:00.000Z'), instant('2026-06-05T12:00:00.000Z'))).toBe(instant('2026-06-06T12:00:00.000Z'))+ })++ it('leaves a consumed one-off terminal even if its configured time is later', () => {+ expect(nextFutureOccurrence({ kind: 'once', at: '2026-07-01T12:00:00.000Z', timeZone: 'UTC' }, instant('2026-06-01T12:00:00.000Z'), instant('2026-06-01T12:15:00.000Z'))).toBeUndefined()+ })++ it.each([Number.NaN, Number.POSITIVE_INFINITY, 8_640_000_000_000_001, 1.5])('rejects an invalid epoch without throwing: %s', (invalid) => {+ const rule: SchedulerSchedule = { kind: 'interval', everyMinutes: 15, timeZone: 'UTC' }+ expect(nextFutureOccurrence(rule, invalid, 0)).toBeUndefined()+ expect(nextFutureOccurrence(rule, 0, invalid)).toBeUndefined()+ })+})diff --git a/packages/dsh-tauri-scheduler/src/host/utils/occurrence.ts b/packages/dsh-tauri-scheduler/src/host/utils/occurrence.tsnew file mode 100644index 00000000..8fc5fea0--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/utils/occurrence.ts@@ -0,0 +1,12 @@+import type { SchedulerSchedule } from '../types'+import { nextOccurrence } from './schedule'++export function nextFutureOccurrence(schedule: SchedulerSchedule, scheduledAt: number, now: number): number | undefined {+ if (!Number.isSafeInteger(scheduledAt) || !Number.isFinite(new Date(scheduledAt).getTime())+ || !Number.isSafeInteger(now) || !Number.isFinite(new Date(now).getTime()) || schedule.kind === 'once') {+ return undefined+ }+ const from = Math.max(scheduledAt, now)+ const rule = schedule.kind === 'interval' ? { ...schedule, anchor: new Date(scheduledAt).toISOString() } : schedule+ return nextOccurrence(rule, from)+}diff --git a/packages/dsh-tauri-scheduler/src/host/utils/schedule.test.ts b/packages/dsh-tauri-scheduler/src/host/utils/schedule.test.tsindex 943b80a8..8384849c 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/schedule.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/schedule.test.ts@@ -1,209 +1,343 @@-import { afterAll, beforeEach, describe, expect, it } from 'vitest'-import { nextOccurrence, parseTimeToMinutes, validateSchedule } from './schedule'--// cron-schedule 无 timezone 形参:`timeZone` 字段只被校验、不被使用,计算走进程本地时区。-// 因此每个用例前都把进程钉回 UTC(用例级改 TZ 的 DST 组必须能被下一个用例复位),-// 期望值一律用 `Date.UTC` 基准,宿主时区不影响结果。-const HOST_TZ = process.env.TZ+import type { SchedulerSchedule as Schedule } from '../types'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { latestDueOccurrence, nextOccurrence, parseTimeToMinutes, validateSchedule } from './schedule'beforeEach(() => {- process.env.TZ = 'UTC'+ vi.stubEnv('TZ', 'UTC')})-afterAll(() => {- if (HOST_TZ === undefined)- delete process.env.TZ- else- process.env.TZ = HOST_TZ+afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllEnvs()})+const timestamp = (value: string): number => Date.parse(value)++const CALENDAR_CASES: Array<[Schedule, string, string]> = [+ [{ kind: 'daily', time: '08:00', timeZone: 'UTC' }, '2026-01-01T07:00:00Z', '2026-01-01T08:00:00Z'],+ [{ kind: 'daily', time: '08:00', timeZone: 'UTC' }, '2026-01-01T08:00:00Z', '2026-01-02T08:00:00Z'],+ [{ kind: 'workdays', time: '08:00', timeZone: 'UTC' }, '2026-01-03T09:00:00Z', '2026-01-05T08:00:00Z'],+ [{ kind: 'weekly', weekdays: ['MO', 'WE', 'MO'], time: '08:00', timeZone: 'UTC' }, '2026-01-01T09:00:00Z', '2026-01-05T08:00:00Z'],+ [{ kind: 'monthly', day: 15, time: '08:00', timeZone: 'UTC' }, '2026-01-10T00:00:00Z', '2026-01-15T08:00:00Z'],+ [{ kind: 'monthly', day: 15, time: '08:00', timeZone: 'UTC' }, '2026-01-20T00:00:00Z', '2026-02-15T08:00:00Z'],+ [{ kind: 'monthly', day: 31, time: '08:00', timeZone: 'UTC' }, '2026-02-01T00:00:00Z', '2026-03-31T08:00:00Z'],+ [{ kind: 'monthly', day: 29, time: '08:00', timeZone: 'UTC' }, '2028-02-01T00:00:00Z', '2028-02-29T08:00:00Z'],+]++const ZONED_CASES: Array<[Schedule, string, string]> = [+ [{ kind: 'daily', time: '08:00', timeZone: 'Asia/Shanghai' }, '2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z'],+ [{ kind: 'daily', time: '08:00', timeZone: 'America/New_York' }, '2026-01-01T07:00:00Z', '2026-01-01T13:00:00Z'],+ [{ kind: 'daily', time: '08:00', timeZone: 'Asia/Tokyo' }, '2026-01-01T01:00:00Z', '2026-01-01T23:00:00Z'],+ [{ kind: 'hourly', minute: 30, timeZone: 'Asia/Kathmandu' }, '2026-01-01T04:55:00Z', '2026-01-01T05:45:00Z'],+ [{ kind: 'workdays', time: '08:00', timeZone: 'Asia/Tokyo' }, '2026-01-04T22:30:00Z', '2026-01-04T23:00:00Z'],+ [{ kind: 'weekly', weekdays: ['SU'], time: '22:00', timeZone: 'America/New_York' }, '2026-01-05T02:00:00Z', '2026-01-05T03:00:00Z'],+ [{ kind: 'monthly', day: 1, time: '08:00', timeZone: 'Asia/Tokyo' }, '2026-01-31T16:00:00Z', '2026-01-31T23:00:00Z'],+ [{ kind: 'custom', everyDays: 2, anchor: '2026-01-01T23:30:00Z', time: '09:00', timeZone: 'Asia/Tokyo' }, '2026-01-01T23:30:00Z', '2026-01-02T00:00:00Z'],+]++const DST_CASES: Array<[Schedule, string, string]> = [+ [{ kind: 'daily', time: '08:00', timeZone: 'America/New_York' }, '2026-03-07T14:00:00Z', '2026-03-08T12:00:00Z'],+ [{ kind: 'daily', time: '08:00', timeZone: 'America/New_York' }, '2026-10-31T13:00:00Z', '2026-11-01T13:00:00Z'],+ [{ kind: 'daily', time: '02:30', timeZone: 'America/New_York' }, '2026-03-07T07:30:00Z', '2026-03-09T06:30:00Z'],+ [{ kind: 'daily', time: '02:30', timeZone: 'America/New_York' }, '2026-03-08T05:00:00Z', '2026-03-09T06:30:00Z'],+ [{ kind: 'daily', time: '01:30', timeZone: 'America/New_York' }, '2026-11-01T04:00:00Z', '2026-11-01T05:30:00Z'],+ [{ kind: 'daily', time: '01:30', timeZone: 'America/New_York' }, '2026-11-01T05:30:00Z', '2026-11-02T06:30:00Z'],+ [{ kind: 'daily', time: '01:30', timeZone: 'America/New_York' }, '2026-11-01T06:00:00Z', '2026-11-02T06:30:00Z'],+ [{ kind: 'workdays', time: '08:00', timeZone: 'America/New_York' }, '2026-03-06T15:00:00Z', '2026-03-09T12:00:00Z'],+ [{ kind: 'weekly', weekdays: ['SU'], time: '02:30', timeZone: 'America/New_York' }, '2026-03-01T07:30:00Z', '2026-03-15T06:30:00Z'],+ [{ kind: 'monthly', day: 8, time: '02:30', timeZone: 'America/New_York' }, '2026-03-01T00:00:00Z', '2026-04-08T06:30:00Z'],+ [{ kind: 'custom', everyDays: 1, anchor: '2026-03-07T05:00:00Z', time: '02:30', timeZone: 'America/New_York' }, '2026-03-07T07:30:00Z', '2026-03-09T06:30:00Z'],+ [{ kind: 'custom', everyDays: 2, anchor: '2026-03-07T05:00:00Z', time: '08:00', timeZone: 'America/New_York' }, '2026-03-07T13:00:00Z', '2026-03-09T12:00:00Z'],+ [{ kind: 'custom', everyDays: 1, anchor: '2026-10-31T04:00:00Z', time: '08:00', timeZone: 'America/New_York' }, '2026-10-31T12:00:00Z', '2026-11-01T13:00:00Z'],+ [{ kind: 'hourly', minute: 30, timeZone: 'America/New_York' }, '2026-03-08T06:45:00Z', '2026-03-08T07:30:00Z'],+ [{ kind: 'hourly', minute: 30, timeZone: 'America/New_York' }, '2026-11-01T05:40:00Z', '2026-11-01T07:30:00Z'],+ [{ kind: 'hourly', minute: 30, timeZone: 'America/New_York' }, '2026-11-01T06:10:00Z', '2026-11-01T07:30:00Z'],+ [{ kind: 'daily', time: '02:15', timeZone: 'Australia/Lord_Howe' }, '2026-10-03T15:00:00Z', '2026-10-04T15:15:00Z'],+ [{ kind: 'daily', time: '01:45', timeZone: 'Australia/Lord_Howe' }, '2026-04-04T13:00:00Z', '2026-04-04T14:45:00Z'],+ [{ kind: 'daily', time: '12:00', timeZone: 'Pacific/Apia' }, '2011-12-29T22:00:00Z', '2011-12-30T22:00:00Z'],+ [{ kind: 'custom', everyDays: 2, anchor: '2011-12-29T10:00:00Z', time: '12:00', timeZone: 'Pacific/Apia' }, '2011-12-29T22:00:00Z', '2011-12-30T22:00:00Z'],+]++const INVALID_SCHEDULES = [+ { kind: 'once', at: 'not-a-date', timeZone: 'UTC' },+ { kind: 'hourly', minute: -1, timeZone: 'UTC' },+ { kind: 'hourly', minute: 60, timeZone: 'UTC' },+ { kind: 'hourly', minute: 1.5, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 0, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 1e9, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 30, anchor: 'bad', timeZone: 'UTC' },+ { kind: 'daily', time: 'bad', timeZone: 'UTC' },+ { kind: 'workdays', time: '24:00', timeZone: 'UTC' },+ { kind: 'weekly', weekdays: [], time: '08:00', timeZone: 'UTC' },+ { kind: 'weekly', weekdays: ['XX'], time: '08:00', timeZone: 'UTC' },+ { kind: 'monthly', day: 0, time: '08:00', timeZone: 'UTC' },+ { kind: 'monthly', day: 32, time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 0, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 367, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 1.5, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 2, anchor: 'bad', time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 2, anchor: '2026-01-01T00:00:00Z', time: 'bad', timeZone: 'UTC' },+ { kind: 'daily', time: '08:00', timeZone: 'Unknown/Zone' },+]+describe('parseTimeToMinutes', () => {- it('parses "HH:mm" into minutes since midnight', () => {- expect(parseTimeToMinutes('00:00')).toBe(0)- expect(parseTimeToMinutes('08:30')).toBe(510)- expect(parseTimeToMinutes('23:59')).toBe(1439)+ it.each([+ ['00:00', 0],+ ['08:30', 510],+ ['23:59', 1439],+ [' 8:30 ', 510],+ ])('parses %s into %i minutes since midnight', (input, expected) => {+ expect(parseTimeToMinutes(input)).toBe(expected)})- it('rejects invalid formats and out-of-range values', () => {- expect(parseTimeToMinutes('')).toBeUndefined()- expect(parseTimeToMinutes('8')).toBeUndefined()- expect(parseTimeToMinutes('24:00')).toBeUndefined()- expect(parseTimeToMinutes('08:60')).toBeUndefined()- expect(parseTimeToMinutes('ab:cd')).toBeUndefined()+ it.each(['', '8', '24:00', '08:60', 'ab:cd'])('rejects invalid clock input %s', (input) => {+ expect(parseTimeToMinutes(input)).toBeUndefined()})})describe('nextOccurrence', () => {- it('interval returns from + everyMinutes', () => {- const from = Date.UTC(2026, 0, 1, 0, 0, 0)- const next = nextOccurrence({ kind: 'interval', everyMinutes: 30, timeZone: 'UTC' }, from)- expect(next).toBe(from + 30 * 60 * 1000)+ it('starts an unanchored interval one full interval after from', () => {+ expect(nextOccurrence({ kind: 'interval', everyMinutes: 30, timeZone: 'UTC' }, timestamp('2026-01-01T08:11:00Z')))+ .toBe(timestamp('2026-01-01T08:41:00Z'))+ })++ it('treats a null optional interval anchor as unanchored input', () => {+ const schedule = { kind: 'interval', everyMinutes: 30, anchor: null, timeZone: 'UTC' }+ expect(nextOccurrence(schedule as unknown as Schedule, timestamp('2026-01-01T08:11:00Z')))+ .toBe(timestamp('2026-01-01T08:41:00Z'))})- it('interval rejects oversized everyMinutes (would overflow Date)', () => {- expect(nextOccurrence({ kind: 'interval', everyMinutes: Number.MAX_SAFE_INTEGER, timeZone: 'UTC' }, Date.now())).toBeUndefined()- expect(nextOccurrence({ kind: 'interval', everyMinutes: 1e9, timeZone: 'UTC' }, Date.now())).toBeUndefined()- expect(validateSchedule({ kind: 'interval', everyMinutes: 1e9, timeZone: 'UTC' })).toBe(false)+ it.each([+ ['2025-12-31T00:00:00Z', '2026-01-01T00:00:00Z'],+ ['2026-01-01T00:00:00Z', '2026-01-01T00:30:00Z'],+ ['2026-01-01T00:46:00Z', '2026-01-01T01:00:00Z'],+ ])('keeps interval anchor phase when from is %s', (from, expected) => {+ expect(nextOccurrence({ kind: 'interval', everyMinutes: 30, anchor: '2026-01-01T00:00:00Z', timeZone: 'UTC' }, timestamp(from)))+ .toBe(timestamp(expected))})- it('once returns the anchored instant only while it is still in the future', () => {- const at = '2026-03-01T12:30:00.000Z'- expect(nextOccurrence({ kind: 'once', at, timeZone: 'UTC' }, Date.UTC(2026, 2, 1, 12, 29, 59)))- .toBe(Date.UTC(2026, 2, 1, 12, 30, 0))- expect(nextOccurrence({ kind: 'once', at, timeZone: 'UTC' }, Date.UTC(2026, 2, 1, 12, 30, 0))).toBeUndefined()- expect(nextOccurrence({ kind: 'once', at, timeZone: 'UTC' }, Date.UTC(2027, 0, 1))).toBeUndefined()- expect(nextOccurrence({ kind: 'once', at: 'not-a-date', timeZone: 'UTC' }, Date.UTC(2026, 0, 1))).toBeUndefined()+ it('returns a future instant for a valid interval with a sub-millisecond step fraction', () => {+ const schedule: Schedule = { kind: 'interval', everyMinutes: 1.00001, timeZone: 'UTC' }+ expect(validateSchedule(schedule)).toBe(true)+ expect(nextOccurrence(schedule, timestamp('2026-01-01T00:00:00Z')))+ .toBe(timestamp('2026-01-01T00:00:00Z') + 60_000.6)})- it('hourly lands on the next occurrence of that minute', () => {- expect(nextOccurrence({ kind: 'hourly', minute: 30, timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 8, 10, 0)))- .toBe(Date.UTC(2026, 0, 1, 8, 30, 0))- expect(nextOccurrence({ kind: 'hourly', minute: 30, timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 8, 45, 0)))- .toBe(Date.UTC(2026, 0, 1, 9, 30, 0))- expect(nextOccurrence({ kind: 'hourly', minute: 0, timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 8, 0, 0)))- .toBe(Date.UTC(2026, 0, 1, 9, 0, 0))+ it('retains a supported fractional-minute interval and its millisecond anchor', () => {+ expect(nextOccurrence({ kind: 'interval', everyMinutes: 1.5, anchor: '2026-01-01T00:00:00.123Z', timeZone: 'America/New_York' }, timestamp('2026-01-01T00:01:00Z')))+ .toBe(timestamp('2026-01-01T00:01:30.123Z'))})- it('hourly rejects an out-of-range minute instead of returning a bogus instant', () => {- expect(nextOccurrence({ kind: 'hourly', minute: 60, timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 8, 0, 0))).toBeUndefined()- expect(nextOccurrence({ kind: 'hourly', minute: -1, timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 8, 0, 0))).toBeUndefined()+ it('finds an anchored interval target without losing a millisecond across the full date range', () => {+ expect(nextOccurrence({ kind: 'interval', everyMinutes: 1, anchor: '-271821-04-20T00:00:00.000Z', timeZone: 'UTC' }, 8_639_999_999_999_999))+ .toBe(8_640_000_000_000_000)})- it('custom steps whole days from the anchor, strictly after `from`', () => {- const anchor = '2026-01-01T00:00:00.000Z'- expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 1, 9, 0, 0)))- .toBe(Date.UTC(2026, 0, 3, 0, 0, 0))- expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 3, 0, 0, 0)))- .toBe(Date.UTC(2026, 0, 5, 0, 0, 0))- expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor, time: '08:00', timeZone: 'UTC' }, Date.UTC(2025, 11, 20, 0, 0, 0)))- .toBe(Date.UTC(2026, 0, 1, 0, 0, 0))+ it('keeps once as an absolute instant regardless of its zone', () => {+ const schedule: Schedule = { kind: 'once', at: '2026-03-01T12:30:00Z', timeZone: 'Asia/Tokyo' }+ expect(nextOccurrence(schedule, timestamp('2026-03-01T12:29:59.999Z'))).toBe(timestamp('2026-03-01T12:30:00Z'))+ expect(nextOccurrence(schedule, timestamp('2026-03-01T12:30:00Z'))).toBeUndefined()+ expect(nextOccurrence(schedule, timestamp('2027-01-01T00:00:00Z'))).toBeUndefined()})- it('custom rejects invalid everyDays / anchor / time', () => {- const anchor = '2026-01-01T00:00:00.000Z'- expect(nextOccurrence({ kind: 'custom', everyDays: 0, anchor, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 1))).toBeUndefined()- expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor: 'nope', time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 1))).toBeUndefined()- expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor, time: 'bad', timeZone: 'UTC' }, Date.UTC(2026, 0, 1))).toBeUndefined()+ it.each([+ [30, '2026-01-01T08:10:00Z', '2026-01-01T08:30:00Z'],+ [30, '2026-01-01T08:45:00Z', '2026-01-01T09:30:00Z'],+ [30, '2026-01-01T08:29:59.999Z', '2026-01-01T08:30:00Z'],+ [0, '2026-01-01T08:00:00Z', '2026-01-01T09:00:00Z'],+ [0, '2026-01-01T08:59:59.999Z', '2026-01-01T09:00:00Z'],+ ])('selects the next local minute %i after %s', (minute, from, expected) => {+ expect(nextOccurrence({ kind: 'hourly', minute, timeZone: 'UTC' }, timestamp(from))).toBe(timestamp(expected))})- it('daily returns today at time when still in the future', () => {- const from = Date.UTC(2026, 0, 1, 7, 0, 0)- const next = nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, from)- expect(next).toBe(Date.UTC(2026, 0, 1, 8, 0, 0))+ it.each(CALENDAR_CASES)('selects %j strictly after %s', (schedule, from, expected) => {+ expect(nextOccurrence(schedule, timestamp(from))).toBe(timestamp(expected))})- it('daily rolls to tomorrow when the time already passed', () => {- const from = Date.UTC(2026, 0, 1, 9, 0, 0)- const next = nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, from)- expect(next).toBe(Date.UTC(2026, 0, 2, 8, 0, 0))+ it.each(ZONED_CASES)('uses the rule zone for %j after %s despite the host zone', (schedule, from, expected) => {+ vi.stubEnv('TZ', 'Pacific/Honolulu')+ expect(nextOccurrence(schedule, timestamp(from))).toBe(timestamp(expected))})- it('workdays skips weekends', () => {- // 2026-01-03 是周六- const saturday = Date.UTC(2026, 0, 3, 9, 0, 0)- const next = nextOccurrence({ kind: 'workdays', time: '08:00', timeZone: 'UTC' }, saturday)- // 下一个工作日是周一 2026-01-05- expect(next).toBe(Date.UTC(2026, 0, 5, 8, 0, 0))+ it.each([+ ['2025-12-20T00:00:00Z', '2026-01-01T08:00:00Z'],+ ['2026-01-01T07:00:00Z', '2026-01-01T08:00:00Z'],+ ['2026-01-01T09:00:00Z', '2026-01-03T08:00:00Z'],+ ['2026-01-03T08:00:00Z', '2026-01-05T08:00:00Z'],+ ])('applies custom time to anchor-aligned dates after %s', (from, expected) => {+ expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' }, timestamp(from)))+ .toBe(timestamp(expected))})- it('weekly picks the next selected weekday', () => {- // 2026-01-01 是周四;选 MO/WE → 下一个选中的是周一 2026-01-05- const thursday = Date.UTC(2026, 0, 1, 9, 0, 0)- const next = nextOccurrence({ kind: 'weekly', weekdays: ['MO', 'WE'], time: '08:00', timeZone: 'UTC' }, thursday)- expect(next).toBe(Date.UTC(2026, 0, 5, 8, 0, 0))+ it('includes an anchor-aligned custom time when the decision precedes the exact anchor instant', () => {+ expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor: '2026-01-01T08:00:00Z', time: '08:00', timeZone: 'UTC' }, timestamp('2026-01-01T07:59:59.999Z')))+ .toBe(timestamp('2026-01-01T08:00:00Z'))})- it('monthly lands on the requested day and skips short months', () => {- expect(nextOccurrence({ kind: 'monthly', day: 15, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 10, 0, 0, 0)))- .toBe(Date.UTC(2026, 0, 15, 8, 0, 0))- expect(nextOccurrence({ kind: 'monthly', day: 15, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 0, 20, 0, 0, 0)))- .toBe(Date.UTC(2026, 1, 15, 8, 0, 0))- // 2026-02 没有 31 日 → 下一次是 03-31- expect(nextOccurrence({ kind: 'monthly', day: 31, time: '08:00', timeZone: 'UTC' }, Date.UTC(2026, 1, 1, 0, 0, 0)))- .toBe(Date.UTC(2026, 2, 31, 8, 0, 0))+ it('bases custom phase on the anchor local date even when it is behind the UTC date', () => {+ expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor: '2026-01-02T01:00:00Z', time: '18:00', timeZone: 'America/Los_Angeles' }, timestamp('2026-01-02T01:00:00Z')))+ .toBe(timestamp('2026-01-02T02:00:00Z'))})- it('returns undefined for invalid schedules', () => {- expect(nextOccurrence({ kind: 'interval', everyMinutes: 0, timeZone: 'UTC' }, Date.now())).toBeUndefined()- expect(nextOccurrence({ kind: 'daily', time: 'bad', timeZone: 'UTC' }, Date.now())).toBeUndefined()- expect(nextOccurrence({ kind: 'weekly', weekdays: [], time: '08:00', timeZone: 'UTC' }, Date.now())).toBeUndefined()- expect(nextOccurrence({ kind: 'workdays', time: '24:00', timeZone: 'UTC' }, Date.now())).toBeUndefined()+ it('never places the first custom occurrence before the anchor instant', () => {+ expect(nextOccurrence({ kind: 'custom', everyDays: 2, anchor: '2026-01-01T10:00:00Z', time: '08:00', timeZone: 'UTC' }, timestamp('2025-12-20T00:00:00Z')))+ .toBe(timestamp('2026-01-03T08:00:00Z'))})- // monthly day 超出 cron 的 1-31 时会从 parseCronExpression 抛出,而不是按契约返回 undefined;- // store 侧经 validateSchedule 挡掉了该输入,故此处不断言该不可达行为。+ it('advances a maximal 366-day custom cadence without walking every intervening date', () => {+ expect(nextOccurrence({ kind: 'custom', everyDays: 366, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' }, timestamp('2026-01-01T08:00:00Z')))+ .toBe(timestamp('2027-01-02T08:00:00Z'))+ })++ it.each(DST_CASES)('keeps wall-clock and earlier-overlap semantics for %j after %s', (schedule, from, expected) => {+ expect(nextOccurrence(schedule, timestamp(from))).toBe(timestamp(expected))+ })++ it('does not reinterpret calendar years below 100 as 1900-based years', () => {+ expect(nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, timestamp('0099-12-31T09:00:00Z')))+ .toBe(timestamp('0100-01-01T08:00:00Z'))+ })++ it.each(INVALID_SCHEDULES)('returns undefined instead of throwing for invalid rule %j', (schedule) => {+ expect(nextOccurrence(schedule as Schedule, timestamp('2026-01-01T00:00:00Z'))).toBeUndefined()+ })++ it('selects a UTC daily target after the earliest representable decision', () => {+ expect(nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, -8_640_000_000_000_000))+ .toBe(-8_639_999_971_200_000)+ })++ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER])('rejects unrepresentable from %s', (from) => {+ expect(nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, from)).toBeUndefined()+ })})-describe('validateSchedule', () => {- it('accepts all four valid kinds', () => {- expect(validateSchedule({ kind: 'daily', time: '08:00', timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'interval', everyMinutes: 30, timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'workdays', time: '09:30', timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'weekly', weekdays: ['MO', 'FR'], time: '10:00', timeZone: 'UTC' })).toBe(true)- })-- it('accepts the once / hourly / monthly / custom kinds', () => {- expect(validateSchedule({ kind: 'once', at: '2026-01-01T08:00:00.000Z', timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'hourly', minute: 0, timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'hourly', minute: 59, timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'monthly', day: 31, time: '08:00', timeZone: 'UTC' })).toBe(true)- expect(validateSchedule({ kind: 'custom', everyDays: 7, anchor: '2026-01-01T00:00:00.000Z', time: '08:00', timeZone: 'UTC' })).toBe(true)- })-- it('rejects invalid shapes', () => {- expect(validateSchedule({ kind: 'daily', time: '25:00' })).toBe(false)- expect(validateSchedule({ kind: 'interval', everyMinutes: -1 })).toBe(false)- expect(validateSchedule({ kind: 'weekly', weekdays: ['XX'], time: '08:00' })).toBe(false)- expect(validateSchedule(null)).toBe(false)- expect(validateSchedule('nope')).toBe(false)- })-- it('rejects out-of-range fields per kind', () => {- expect(validateSchedule({ kind: 'once', at: 'not-a-date' })).toBe(false)- expect(validateSchedule({ kind: 'once', at: 1735689600000 })).toBe(false)- expect(validateSchedule({ kind: 'hourly', minute: 60 })).toBe(false)- expect(validateSchedule({ kind: 'hourly', minute: 1.5 })).toBe(false)- expect(validateSchedule({ kind: 'monthly', day: 32, time: '08:00' })).toBe(false)- expect(validateSchedule({ kind: 'monthly', day: 0, time: '08:00' })).toBe(false)- expect(validateSchedule({ kind: 'custom', everyDays: 0, anchor: '2026-01-01T00:00:00.000Z', time: '08:00' })).toBe(false)- expect(validateSchedule({ kind: 'custom', everyDays: 7, anchor: 'nope', time: '08:00' })).toBe(false)- expect(validateSchedule({ kind: 'custom', everyDays: 7, anchor: '2026-01-01T00:00:00.000Z', time: 'bad' })).toBe(false)- expect(validateSchedule({ kind: 'unknown' })).toBe(false)- expect(validateSchedule([])).toBe(false)+describe('latestDueOccurrence', () => {+ it('does not invent a due occurrence before the durable target', () => {+ expect(latestDueOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, timestamp('2026-01-01T08:00:00Z'), timestamp('2026-01-01T07:59:59.999Z')))+ .toBeUndefined()+ })++ it('retains the single one-shot target after a long missed gap', () => {+ const schedule: Schedule = { kind: 'once', at: '2000-01-01T08:00:00Z', timeZone: 'Asia/Tokyo' }+ const due = latestDueOccurrence(schedule, timestamp('2000-01-01T08:00:00Z'), timestamp('2099-12-31T23:59:59Z'))+ expect(due).toBe(timestamp('2000-01-01T08:00:00Z'))+ expect(nextOccurrence(schedule, timestamp('2000-01-01T08:00:00Z'))).toBeUndefined()+ })++ it('folds centuries of interval misses while preserving durable millisecond phase', () => {+ expect(latestDueOccurrence({ kind: 'interval', everyMinutes: 5, timeZone: 'UTC' }, timestamp('1800-01-01T00:00:00.123Z'), timestamp('2026-01-01T00:17:34.456Z')))+ .toBe(timestamp('2026-01-01T00:15:00.123Z'))+ })++ it('uses durable nextRunAt rather than a recomputed interval anchor', () => {+ expect(latestDueOccurrence({ kind: 'interval', everyMinutes: 15, anchor: '2026-01-01T00:00:00Z', timeZone: 'UTC' }, timestamp('2026-01-01T00:02:17Z'), timestamp('2026-01-01T00:59:00Z')))+ .toBe(timestamp('2026-01-01T00:47:17Z'))+ })++ it('folds fractional-minute misses from the committed millisecond target', () => {+ expect(latestDueOccurrence({ kind: 'interval', everyMinutes: 1.5, timeZone: 'UTC' }, timestamp('2026-01-01T00:00:00.123Z'), timestamp('2026-01-01T00:05:00Z')))+ .toBe(timestamp('2026-01-01T00:04:30.123Z'))+ })++ it('retains interval phase across the full date range without rounding the decision forward', () => {+ expect(latestDueOccurrence({ kind: 'interval', everyMinutes: 1, timeZone: 'UTC' }, -8_640_000_000_000_000, 8_639_999_999_999_999))+ .toBe(8_639_999_999_940_000)+ })++ it.each<[Schedule, string, string, string]>([+ [{ kind: 'hourly', minute: 30, timeZone: 'Asia/Kathmandu' }, '1800-01-01T00:00:00Z', '2026-01-01T04:55:00Z', '2026-01-01T04:45:00Z'],+ [{ kind: 'daily', time: '09:00', timeZone: 'Asia/Shanghai' }, '1800-01-01T00:00:00Z', '2026-09-16T00:59:59Z', '2026-09-15T01:00:00Z'],+ [{ kind: 'daily', time: '09:00', timeZone: 'Asia/Shanghai' }, '1800-01-01T00:00:00Z', '2026-09-16T01:00:00Z', '2026-09-16T01:00:00Z'],+ [{ kind: 'workdays', time: '09:00', timeZone: 'UTC' }, '1800-01-01T00:00:00Z', '2026-01-03T12:00:00Z', '2026-01-02T09:00:00Z'],+ [{ kind: 'weekly', weekdays: ['MO', 'FR'], time: '09:00', timeZone: 'America/New_York' }, '1800-01-01T00:00:00Z', '2026-01-08T12:00:00Z', '2026-01-05T14:00:00Z'],+ [{ kind: 'monthly', day: 31, time: '08:00', timeZone: 'Asia/Tokyo' }, '1800-01-01T00:00:00Z', '2026-03-01T02:00:00Z', '2026-01-30T23:00:00Z'],+ [{ kind: 'custom', everyDays: 7, anchor: '2000-01-03T00:00:00Z', time: '08:00', timeZone: 'UTC' }, '2000-01-03T08:00:00Z', '2026-01-09T09:00:00Z', '2026-01-05T08:00:00Z'],+ [{ kind: 'custom', everyDays: 2, anchor: '1970-01-01T06:00:00Z', time: '08:00', timeZone: 'UTC' }, '1970-01-01T08:00:00Z', '2026-01-01T09:00:00Z', '2026-01-01T08:00:00Z'],+ ])('selects only the latest missed target for %j at %s', (schedule, nextRunAt, now, expected) => {+ expect(latestDueOccurrence(schedule, timestamp(nextRunAt), timestamp(now))).toBe(timestamp(expected))+ })++ it.each<[Schedule, string, string, string]>([+ [{ kind: 'daily', time: '02:30', timeZone: 'America/New_York' }, '2026-03-07T07:30:00Z', '2026-03-08T12:00:00Z', '2026-03-07T07:30:00Z'],+ [{ kind: 'daily', time: '02:30', timeZone: 'America/New_York' }, '2026-03-07T07:30:00Z', '2026-03-09T07:00:00Z', '2026-03-09T06:30:00Z'],+ [{ kind: 'daily', time: '01:30', timeZone: 'America/New_York' }, '2026-10-31T05:30:00Z', '2026-11-01T06:45:00Z', '2026-11-01T05:30:00Z'],+ [{ kind: 'hourly', minute: 30, timeZone: 'America/New_York' }, '2026-10-31T04:30:00Z', '2026-11-01T06:15:00Z', '2026-11-01T05:30:00Z'],+ [{ kind: 'custom', everyDays: 2, anchor: '2011-12-29T10:00:00Z', time: '12:00', timeZone: 'Pacific/Apia' }, '2011-12-29T22:00:00Z', '2011-12-30T23:00:00Z', '2011-12-30T22:00:00Z'],+ [{ kind: 'daily', time: '12:00', timeZone: 'America/Anchorage' }, '1867-10-17T21:59:36Z', '1867-10-19T06:00:00Z', '1867-10-18T21:59:36Z'],+ ])('folds missed DST/date-line targets for %j at %s', (schedule, nextRunAt, now, expected) => {+ expect(latestDueOccurrence(schedule, timestamp(nextRunAt), timestamp(now))).toBe(timestamp(expected))+ })++ it('honors a committed later-overlap target instead of rewinding it under current rules', () => {+ expect(latestDueOccurrence({ kind: 'daily', time: '01:30', timeZone: 'US/Eastern' }, timestamp('2026-11-01T06:30:00Z'), timestamp('2026-11-01T06:45:00Z')))+ .toBe(timestamp('2026-11-01T06:30:00Z'))+ })++ it('retains the committed custom target when the next phase has not arrived', () => {+ expect(latestDueOccurrence({ kind: 'custom', everyDays: 366, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' }, timestamp('2026-01-01T08:00:00Z'), timestamp('2026-12-31T23:00:00Z')))+ .toBe(timestamp('2026-01-01T08:00:00Z'))+ })++ it('finds the UTC calendar target at the final representable decision', () => {+ expect(latestDueOccurrence({ kind: 'daily', time: '08:00', timeZone: 'UTC' }, timestamp('2000-01-01T08:00:00Z'), 8_640_000_000_000_000))+ .toBe(8_639_999_942_400_000)+ })++ it('bounds calendar projection work independently of the missed history length', () => {+ const projection = vi.spyOn(Intl.DateTimeFormat.prototype, 'formatToParts')+ expect(latestDueOccurrence({ kind: 'daily', time: '09:00', timeZone: 'Asia/Shanghai' }, timestamp('0001-01-01T00:00:00Z'), timestamp('9999-12-31T02:00:00Z')))+ .toBe(timestamp('9999-12-31T01:00:00Z'))+ expect(projection.mock.calls.length).toBeLessThan(100)+ })++ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.MAX_SAFE_INTEGER])('rejects an unrepresentable durable target or decision %s', (invalid) => {+ const schedule: Schedule = { kind: 'daily', time: '08:00', timeZone: 'UTC' }+ expect(latestDueOccurrence(schedule, invalid, timestamp('2026-01-01T09:00:00Z'))).toBeUndefined()+ expect(latestDueOccurrence(schedule, timestamp('2026-01-01T08:00:00Z'), invalid)).toBeUndefined()+ })++ it('rejects an invalid recurrence instead of replaying its durable target', () => {+ expect(latestDueOccurrence({ kind: 'interval', everyMinutes: 0, timeZone: 'UTC' }, timestamp('2026-01-01T00:00:00Z'), timestamp('2026-01-02T00:00:00Z')))+ .toBeUndefined()})})-describe('nextOccurrence across DST (America/New_York)', () => {- // 本组需要非 UTC 的进程时区:顶层 `beforeEach` 先把 TZ 钉到 UTC,描述块级 hook 在其后执行,- // 这里再覆盖一次即可;用例结束后由下一个用例的顶层 `beforeEach` 复位,故无需自行还原。- beforeEach(() => {- process.env.TZ = 'America/New_York'- })-- it('daily keeps the same wall-clock time across spring-forward', () => {- // 2026-03-08 02:00 EST → 03:00 EDT(春季前拨,当天只有 23 小时)。- // 从 03-07 09:00 之后找 08:00 → 应为 03-08 08:00 EDT。- const from = new Date(2026, 2, 7, 9, 0, 0).getTime()- const next = nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'America/New_York' }, from)- const expected = new Date(2026, 2, 8, 8, 0, 0).getTime()- expect(next).toBe(expected)- // 与「日历日 +1」一致:加 24h 毫秒会得到 23 小时的钟面错位。- expect(new Date(next as number).getHours()).toBe(8)- })-- it('daily keeps the same wall-clock time across fall-back', () => {- // 2026-11-01 02:00 EDT → 01:00 EST(秋季回拨,当天 25 小时)。- const from = new Date(2026, 9, 31, 9, 0, 0).getTime()- const next = nextOccurrence({ kind: 'daily', time: '08:00', timeZone: 'America/New_York' }, from)- const expected = new Date(2026, 10, 1, 8, 0, 0).getTime()- expect(next).toBe(expected)- expect(new Date(next as number).getHours()).toBe(8)- })-- it('workdays keeps wall-clock time across a DST boundary', () => {- // 2026-03-06(周五)之后的工作日 08:00:跨 03-08 春季前拨 → 03-09(周一)08:00。- const friday = new Date(2026, 2, 6, 12, 0, 0).getTime()- const next = nextOccurrence({ kind: 'workdays', time: '08:00', timeZone: 'America/New_York' }, friday)- expect(next).toBe(new Date(2026, 2, 9, 8, 0, 0).getTime())+describe('validateSchedule', () => {+ it.each<Schedule>([+ { kind: 'once', at: '2026-01-01T08:00:00Z', timeZone: 'UTC' },+ { kind: 'hourly', minute: 0, timeZone: 'UTC' },+ { kind: 'hourly', minute: 59, timeZone: 'UTC' },+ { kind: 'daily', time: '08:00', timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 30, timeZone: 'UTC' },+ { kind: 'interval', everyMinutes: 1.5, anchor: '2026-01-01T00:00:00Z', timeZone: 'UTC' },+ { kind: 'workdays', time: '09:30', timeZone: 'UTC' },+ { kind: 'weekly', weekdays: ['MO', 'FR'], time: '10:00', timeZone: 'UTC' },+ { kind: 'monthly', day: 31, time: '08:00', timeZone: 'UTC' },+ { kind: 'custom', everyDays: 366, anchor: '2026-01-01T00:00:00Z', time: '08:00', timeZone: 'UTC' },+ ])('accepts a valid %j schedule', (schedule) => {+ expect(validateSchedule(schedule)).toBe(true)+ })++ it('allows an omitted input zone before host normalization', () => {+ expect(validateSchedule({ kind: 'daily', time: '08:00' })).toBe(true)+ })++ it('accepts a recognized IANA alias without rewriting the schedule', () => {+ const schedule = { kind: 'daily', time: '08:00', timeZone: 'US/Eastern' }+ expect(validateSchedule(schedule)).toBe(true)+ expect(schedule.timeZone).toBe('US/Eastern')+ })++ it.each(INVALID_SCHEDULES)('rejects invalid rule %j', (schedule) => {+ expect(validateSchedule(schedule)).toBe(false)+ })++ it.each([null, 'nope', [], { kind: 'unknown' }, { kind: 'once', at: 1735689600000 }])('rejects invalid shape %j', (value) => {+ expect(validateSchedule(value)).toBe(false)+ })++ it.each(['', 'UTC ', ' Asia/Shanghai', 7, null])('rejects invalid explicit zone %j', (timeZone) => {+ expect(validateSchedule({ kind: 'daily', time: '08:00', timeZone })).toBe(false)})})diff --git a/packages/dsh-tauri-scheduler/src/host/utils/schedule.ts b/packages/dsh-tauri-scheduler/src/host/utils/schedule.tsindex 7daf0cd8..ea921626 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/schedule.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/schedule.ts@@ -1,89 +1,71 @@-import type { SchedulerSchedule, Weekday } from '../types'-import { parseCronExpression } from 'cron-schedule'-import { inRange, isArray, isEmpty, isFinite, isInteger, isNil, isNumber, isObject, isString, sortBy, uniq } from 'lodash-es'+import type { SchedulerSchedule as Schedule, Weekday } from '../types'+import { inRange, isArray, isEmpty, isFinite, isInteger, isNil, isNumber, isObject, isString } from 'lodash-es'import { WEEKDAYS } from '../../shared/constants'const MINUTE_MS = 60 * 1000-const DAY_MS = 24 * 60 * MINUTE_MS+const HOUR_MS = 60 * MINUTE_MS+const DAY_MS = 24 * HOUR_MS+const MAX_EPOCH = 8_640_000_000_000_000const MAX_EVERY_MINUTES = 525_600const MAX_EVERY_DAYS = 366+const MAX_CALENDAR_ATTEMPTS = 400+const WEEKDAY_NUMBER: Record<Weekday, number> = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 0 }-export function parseTimeToMinutes(time: string): number | undefined {- const match = /^(\d{1,2}):(\d{2})$/.exec(time.trim())- if (!match)- return undefined- const hours = Number(match[1])- const minutes = Number(match[2])- return inRange(hours, 0, 24) && inRange(minutes, 0, 60) ? hours * 60 + minutes : undefined-}--const WEEKDAY_TO_CRON_DAY: Record<Weekday, number> = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 0 }-type TimeSchedule = Extract<SchedulerSchedule, { kind: 'daily' | 'workdays' | 'weekly' | 'monthly' }>+type CalendarSchedule = Exclude<Schedule, { kind: 'once' | 'interval' }>const isInstant = (value: unknown): boolean => isString(value) && isFinite(new Date(value).getTime())const isTimeValue = (value: unknown): boolean => isString(value) && parseTimeToMinutes(value) !== undefinedconst isMinuteValue = (value: unknown): boolean => isNumber(value) && isInteger(value) && inRange(value, 0, 60)const isFiniteInRange = (value: unknown, end: number): boolean => isNumber(value) && isFinite(value) && inRange(value, 1, end)const isIntegerInRange = (value: unknown, end: number): boolean => isNumber(value) && isInteger(value) && inRange(value, 1, end)+const isEpoch = (value: number): boolean => Number.isSafeInteger(value) && isFinite(new Date(value).getTime())-function toCronExpression(schedule: TimeSchedule): string | undefined {- const minutes = parseTimeToMinutes(schedule.time)- if (minutes === undefined)+export function parseTimeToMinutes(time: string): number | undefined {+ const match = /^(\d{1,2}):(\d{2})$/.exec(time.trim())+ if (!match)return undefined- const hour = Math.floor(minutes / 60)- const minute = minutes % 60- if (schedule.kind === 'daily')- return `${minute} ${hour} * * *`- if (schedule.kind === 'workdays')- return `${minute} ${hour} * * 1-5`- if (schedule.kind === 'monthly')- return `${minute} ${hour} ${schedule.day} * *`- const days = sortBy(uniq(schedule.weekdays.map(day => WEEKDAY_TO_CRON_DAY[day])))- return isEmpty(days) ? undefined : `${minute} ${hour} * * ${days.join(',')}`+ const hours = Number(match[1])+ const minutes = Number(match[2])+ return inRange(hours, 0, 24) && inRange(minutes, 0, 60) ? hours * 60 + minutes : undefined}-function anchoredOccurrence(anchor: string, step: number, from: number): number | undefined {- const base = new Date(anchor).getTime()- if (!isFinite(base) || step <= 0)+export function nextOccurrence(schedule: Schedule, from: number): number | undefined {+ if (!isEpoch(from) || !validateSchedule(schedule))return undefined- const index = Math.max(0, Math.floor((from - base) / step) + 1)- return base + index * step-}--export function nextOccurrence(schedule: SchedulerSchedule, from: number): number | undefined {switch (schedule.kind) {case 'once': {const at = new Date(schedule.at).getTime()- return isFinite(at) && at > from ? at : undefined+ return at > from ? at : undefined}- case 'hourly': {- if (!isMinuteValue(schedule.minute))- return undefined- const next = new Date(from + MINUTE_MS)- next.setMinutes(schedule.minute, 0, 0)- if (next.getTime() <= from)- next.setHours(next.getHours() + 1)- return next.getTime()- }- case 'interval':- if (!isFiniteInRange(schedule.everyMinutes, MAX_EVERY_MINUTES + 1))- return undefined- return schedule.anchor ? anchoredOccurrence(schedule.anchor, schedule.everyMinutes * MINUTE_MS, from) : from + schedule.everyMinutes * MINUTE_MS- case 'custom':- if (!isIntegerInRange(schedule.everyDays, MAX_EVERY_DAYS + 1) || !isTimeValue(schedule.time))- return undefined- return anchoredOccurrence(schedule.anchor, schedule.everyDays * DAY_MS, from)- case 'daily': case 'workdays': case 'weekly': case 'monthly': {- const expression = toCronExpression(schedule)- return expression === undefined ? undefined : parseCronExpression(expression).getNextDate(new Date(from)).getTime()+ case 'interval': {+ const step = schedule.everyMinutes * MINUTE_MS+ const base = isNil(schedule.anchor) ? from : new Date(schedule.anchor).getTime()+ const next = from < base ? base : from + step - intervalRemainder(from, base, step)+ return isFinite(next) && Math.abs(next) <= MAX_EPOCH && next > from ? next : undefined}+ default:+ return calendarOccurrence(schedule, from, 1)+ }+}++export function latestDueOccurrence(schedule: Schedule, nextRunAt: number, now: number): number | undefined {+ if (!isEpoch(nextRunAt) || !isEpoch(now) || nextRunAt > now || !validateSchedule(schedule))+ return undefined+ if (schedule.kind === 'once')+ return nextRunAt+ if (schedule.kind === 'interval') {+ const step = schedule.everyMinutes * MINUTE_MS+ return now - intervalRemainder(now, nextRunAt, step)}+ return Math.max(nextRunAt, calendarOccurrence(schedule, now, -1) ?? nextRunAt)}-export function validateSchedule(schedule: unknown): schedule is SchedulerSchedule {- if (!isObject(schedule))+export function validateSchedule(schedule: unknown): schedule is Schedule {+ if (!isObject(schedule) || isArray(schedule))+ return false+ const value = schedule as Partial<Schedule>+ if (calendarFormatter(value.timeZone) === undefined)return false- const value = schedule as Partial<SchedulerSchedule>switch (value.kind) {case 'once':return isInstant(value.at)@@ -112,3 +94,108 @@ export function localTimeZone(): string {return 'UTC'}}++function intervalRemainder(epoch: number, base: number, step: number): number {+ return ((epoch % step - base % step) % step + step) % step+}++function calendarFormatter(timeZone: unknown): Intl.DateTimeFormat | undefined {+ if (timeZone !== undefined && (!isString(timeZone) || timeZone === '' || timeZone.trim() !== timeZone))+ return undefined+ try {+ return new Intl.DateTimeFormat('en-US', {+ timeZone,+ calendar: 'gregory',+ numberingSystem: 'latn',+ era: 'short',+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ second: '2-digit',+ hourCycle: 'h23',+ })+ }+ catch {+ return undefined+ }+}++function calendarEpoch(year: number, month: number, day: number, minutes = 0, seconds = 0): number {+ const date = new Date(0)+ date.setUTCFullYear(year, month, day)+ date.setUTCHours(0, minutes, seconds, 0)+ return date.getTime()+}++function zonedEpoch(formatter: Intl.DateTimeFormat, epoch: number): number {+ const parts = Object.fromEntries(formatter.formatToParts(epoch).map(part => [part.type, part.value]))+ const year = parts.era === 'BC' ? 1 - Number(parts.year) : Number(parts.year)+ return calendarEpoch(year, Number(parts.month) - 1, Number(parts.day), Number(parts.hour) * 60 + Number(parts.minute), Number(parts.second))+}++function localInstant(formatter: Intl.DateTimeFormat, local: number): number | undefined {+ const offsets = new Set<number>()+ for (const delta of [-DAY_MS, 0, DAY_MS]) {+ const sample = local + delta+ if (isEpoch(sample))+ offsets.add(zonedEpoch(formatter, sample) - sample)+ }+ let earliest: number | undefined+ // issue #987: gaps fail the wall-clock round trip; overlaps use only their earlier instant.+ for (const offset of offsets) {+ const target = local - offset+ if (isEpoch(target) && zonedEpoch(formatter, target) === local && (earliest === undefined || target < earliest))+ earliest = target+ }+ return earliest+}++function calendarOccurrence(schedule: CalendarSchedule, from: number, direction: 1 | -1): number | undefined {+ const formatter = calendarFormatter(schedule.timeZone)+ if (formatter === undefined)+ return undefined+ const minutes = schedule.kind === 'hourly' ? schedule.minute : parseTimeToMinutes(schedule.time)+ if (minutes === undefined)+ return undefined+ let cursor = Math.max(-MAX_EPOCH, Math.min(MAX_EPOCH, Math.floor(from / DAY_MS) * DAY_MS - direction * DAY_MS))+ let step = schedule.kind === 'hourly' ? HOUR_MS : DAY_MS+ let anchor: number | undefined+ if (schedule.kind === 'custom') {+ anchor = new Date(schedule.anchor).getTime()+ const anchorDay = Math.floor(zonedEpoch(formatter, anchor) / DAY_MS) * DAY_MS+ step = schedule.everyDays * DAY_MS+ const index = direction === 1 ? Math.max(0, Math.ceil((cursor - anchorDay) / step)) : Math.floor((cursor - anchorDay) / step)+ if (index < 0)+ return undefined+ cursor = anchorDay + index * step+ }+ if (schedule.kind === 'monthly') {+ const date = new Date(cursor)+ cursor = calendarEpoch(date.getUTCFullYear(), date.getUTCMonth(), 1)+ }+ for (let attempt = 0; attempt < MAX_CALENDAR_ATTEMPTS && isEpoch(cursor); attempt++) {+ const date = new Date(cursor)+ const weekday = date.getUTCDay()+ const local = schedule.kind === 'monthly'+ ? calendarEpoch(date.getUTCFullYear(), date.getUTCMonth(), schedule.day, minutes)+ : cursor + minutes * MINUTE_MS+ const matches = schedule.kind === 'workdays'+ ? inRange(weekday, 1, 6)+ : schedule.kind === 'weekly'+ ? schedule.weekdays.some(day => WEEKDAY_NUMBER[day] === weekday)+ : schedule.kind === 'monthly'+ ? new Date(local).getUTCMonth() === date.getUTCMonth()+ : true+ if (matches) {+ const target = localInstant(formatter, local)+ if (target !== undefined && (anchor === undefined || target >= anchor) && (direction === 1 ? target > from : target <= from))+ return target+ }+ cursor = schedule.kind === 'monthly'+ ? calendarEpoch(date.getUTCFullYear(), date.getUTCMonth() + direction, 1)+ : cursor + direction * step+ }+ return undefined+}diff --git a/packages/dsh-tauri-scheduler/src/host/utils/session-deadline.ts b/packages/dsh-tauri-scheduler/src/host/utils/session-deadline.tsnew file mode 100644index 00000000..916345bf--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/utils/session-deadline.ts@@ -0,0 +1,22 @@+const SESSION_OPERATION_TIMEOUT_MS = 10_000++export class SessionOperationTimeout extends Error {+ constructor() {+ super('等待宿主会话操作超时')+ }+}++export async function withSessionDeadline<T>(operation: Promise<T>): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined+ try {+ return await Promise.race([+ operation,+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new SessionOperationTimeout()), SESSION_OPERATION_TIMEOUT_MS)+ }),+ ])+ }+ finally {+ clearTimeout(timer)+ }+}diff --git a/packages/dsh-tauri-scheduler/src/host/utils/task-record.ts b/packages/dsh-tauri-scheduler/src/host/utils/task-record.tsnew file mode 100644index 00000000..2caf310e--- /dev/null+++ b/packages/dsh-tauri-scheduler/src/host/utils/task-record.ts@@ -0,0 +1,11 @@+import type { SchedulerTask } from '../types'+import { isEqual, omit } from 'lodash-es'++export function sameTaskRecord(current: SchedulerTask | null, expected: SchedulerTask): boolean {+ try {+ return current !== null && isEqual(JSON.parse(JSON.stringify(omit(current, 'waiting'))), JSON.parse(JSON.stringify(omit(expected, 'waiting'))))+ }+ catch {+ return false+ }+}diff --git a/packages/dsh-tauri-scheduler/src/host/utils/tool.ts b/packages/dsh-tauri-scheduler/src/host/utils/tool.tsindex af118e12..57272510 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/tool.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/tool.ts@@ -5,6 +5,7 @@ export const scheduleParameters = {description: 'Schedule spec: once/hourly/daily/interval/workdays/weekly/monthly/custom.',properties: {kind: { type: 'string', enum: [...SCHEDULE_KINDS] },+ timeZone: { type: 'string', description: 'IANA time zone for the calendar schedule; defaults to the host zone.' },time: { type: 'string', description: '"HH:mm" for daily/workdays/weekly/monthly/custom.' },everyMinutes: { type: 'number', description: 'Interval minutes for kind=interval.' },everyDays: { type: 'number', description: 'Interval days for kind=custom.' },diff --git a/packages/dsh-tauri-scheduler/src/host/utils/waiting.test.ts b/packages/dsh-tauri-scheduler/src/host/utils/waiting.test.tsindex e8d094d5..12a5b7dd 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/waiting.test.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/waiting.test.ts@@ -6,30 +6,50 @@ const NOW = Date.parse('2026-09-16T10:00:00.000Z')const DUE = '2026-09-16T09:59:00.000Z'const FUTURE = '2026-09-16T11:00:00.000Z'-function makeTask(id: string, nextRunAt?: string, enabled = true): SchedulerTask {+function makeTask(id: string, nextRunAt?: string, overrides: Partial<SchedulerTask> = {}): SchedulerTask {return {id,+ delivery: 'new-session',+ status: 'active',name: id,prompt: 'prompt',schedule: { kind: 'daily', time: '09:00', timeZone: 'UTC' },- enabled,+ enabled: true,createdAt: '2026-09-16T00:00:00.000Z',updatedAt: '2026-09-16T00:00:00.000Z',nextRunAt,+ ...overrides,}}describe('isTaskDue', () => {- it('treats an enabled task whose nextRunAt has passed as due', () => {+ it('treats an enabled active new-session task with a past target as due', () => {expect(isTaskDue(makeTask('a', DUE), NOW)).toBe(true)- expect(isTaskDue(makeTask('a', DUE, false), NOW)).toBe(false)- expect(isTaskDue(makeTask('a', FUTURE), NOW)).toBe(false)- expect(isTaskDue(makeTask('a'), NOW)).toBe(false)+ })++ it('includes a new-session target exactly at the decision time', () => {+ expect(isTaskDue(makeTask('a', '2026-09-16T10:00:00.000Z'), NOW)).toBe(true)+ })++ it.each<Partial<SchedulerTask>>([+ { enabled: false },+ { status: 'inactive' },+ { delivery: 'this-session', sessionId: 'session-a' },+ ])('excludes a past target when task eligibility is %j', (overrides) => {+ expect(isTaskDue(makeTask('a', DUE, overrides), NOW)).toBe(false)+ })++ it.each([FUTURE, undefined, 'not-a-date', ''])('excludes a missing, invalid or future target %j', (nextRunAt) => {+ expect(isTaskDue(makeTask('a', nextRunAt), NOW)).toBe(false)+ })++ it.each([Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY])('rejects a non-finite decision %s', (now) => {+ expect(isTaskDue(makeTask('a', DUE), now)).toBe(false)})})describe('selectWaitingTaskIds', () => {- it('marks every due task as waiting when no capacity is left', () => {+ it('marks every eligible due task as waiting when no capacity is left', () => {const tasks = [makeTask('a', DUE), makeTask('b', DUE)]expect([...selectWaitingTaskIds(tasks, new Set(), 0, NOW)]).toEqual(['a', 'b'])})@@ -39,13 +59,50 @@ describe('selectWaitingTaskIds', () => {expect([...selectWaitingTaskIds(tasks, new Set(), 1, NOW)]).toEqual(['b', 'c'])})- it('counts in-flight runs against the capacity', () => {+ it('uses already-available capacity without subtracting unrelated in-flight runs again', () => {const tasks = [makeTask('a', DUE), makeTask('b', DUE)]expect([...selectWaitingTaskIds(tasks, new Set(['z']), 1, NOW)]).toEqual(['b'])})- it('never marks a running, paused or future task as waiting', () => {- const tasks = [makeTask('a', DUE), makeTask('b', DUE, false), makeTask('c', FUTURE)]- expect([...selectWaitingTaskIds(tasks, new Set(['a']), 0, NOW)]).toEqual([])+ it('never marks running, disabled, inactive, this-session or future tasks as waiting', () => {+ const tasks = [+ makeTask('running', DUE),+ makeTask('disabled', DUE, { enabled: false }),+ makeTask('inactive', DUE, { status: 'inactive' }),+ makeTask('this-session', DUE, { delivery: 'this-session', sessionId: 'session-a' }),+ makeTask('future', FUTURE),+ makeTask('missing'),+ makeTask('invalid', 'not-a-date'),+ ]+ expect([...selectWaitingTaskIds(tasks, new Set(['running']), 0, NOW)]).toEqual([])+ })++ it('does not let this-session or inactive tasks consume new-session capacity', () => {+ const tasks = [+ makeTask('this-session', DUE, { delivery: 'this-session', sessionId: 'session-a' }),+ makeTask('inactive', DUE, { status: 'inactive' }),+ makeTask('a', DUE),+ makeTask('b', DUE),+ ]+ expect([...selectWaitingTaskIds(tasks, new Set(), 1, NOW)]).toEqual(['b'])+ })++ it('removes running tasks before allocating available slots in input order', () => {+ const tasks = [makeTask('running', DUE), makeTask('a', DUE), makeTask('b', DUE)]+ expect([...selectWaitingTaskIds(tasks, new Set(['running']), 1, NOW)]).toEqual(['b'])+ })++ it('treats negative capacity as no available slots', () => {+ const tasks = [makeTask('a', DUE), makeTask('b', DUE)]+ expect([...selectWaitingTaskIds(tasks, new Set(), -1, NOW)]).toEqual(['a', 'b'])+ })++ it('returns no waiting tasks when capacity covers every eligible due task', () => {+ const tasks = [makeTask('a', DUE), makeTask('b', DUE)]+ expect([...selectWaitingTaskIds(tasks, new Set(), 3, NOW)]).toEqual([])+ })++ it('returns an empty waiting set for an empty task list', () => {+ expect([...selectWaitingTaskIds([], new Set(), 0, NOW)]).toEqual([])})})diff --git a/packages/dsh-tauri-scheduler/src/host/utils/waiting.ts b/packages/dsh-tauri-scheduler/src/host/utils/waiting.tsindex 3544eda7..fc741e0a 100644--- a/packages/dsh-tauri-scheduler/src/host/utils/waiting.ts+++ b/packages/dsh-tauri-scheduler/src/host/utils/waiting.ts@@ -1,8 +1,9 @@import type { SchedulerTask } from '../types'import { isNil } from 'lodash-es'-export function isTaskDue(item: Pick<SchedulerTask, 'enabled' | 'nextRunAt'>, now: number): boolean {- return item.enabled && !isNil(item.nextRunAt) && new Date(item.nextRunAt).getTime() <= now+export function isTaskDue(item: Pick<SchedulerTask, 'delivery' | 'status' | 'enabled' | 'nextRunAt'>, now: number): boolean {+ return item.delivery === 'new-session' && item.status === 'active' && item.enabled+ && Number.isFinite(now) && !isNil(item.nextRunAt) && new Date(item.nextRunAt).getTime() <= now}export function selectWaitingTaskIds(diff --git a/packages/dsh-tauri-scheduler/src/index.ts b/packages/dsh-tauri-scheduler/src/index.tsindex 7aa9f337..06a0a355 100644--- a/packages/dsh-tauri-scheduler/src/index.ts+++ b/packages/dsh-tauri-scheduler/src/index.ts@@ -7,6 +7,7 @@ export const inject = ['webServer','agents','sessions',+ 'sessionController','workspaceRegistry','agentDefaultModel','agentPresets',diff --git a/packages/dsh-tauri-scheduler/src/shared/constants.ts b/packages/dsh-tauri-scheduler/src/shared/constants.tsindex 797d3e28..96cb8336 100644--- a/packages/dsh-tauri-scheduler/src/shared/constants.ts+++ b/packages/dsh-tauri-scheduler/src/shared/constants.ts@@ -1,3 +1,5 @@+import type {} from '@deepseek-ai/dsh-api-session-controller/client'+/*** shared/constants.ts — 跨 host/client 的稳定协议常量(dsh-tauri-scheduler)。*@@ -8,6 +10,14 @@/** 插件名(诊断元数据 / registrant / storage key 前缀)。 */export const PLUGIN_ID = 'dsh-tauri-scheduler'+export const SESSION_SCHEDULE_ORIGIN_PROJECTION = 'dsh-tauri-scheduler.origin'++declare module '@deepseek-ai/dsh-api-session-controller/client' {+ interface SessionProjectionMap {+ [SESSION_SCHEDULE_ORIGIN_PROJECTION]: boolean+ }+}+/** 计划类型集合(与 DSH automation 工具的语义一一对应)。 */export const SCHEDULE_KINDS = ['once', 'hourly', 'daily', 'interval', 'workdays', 'weekly', 'monthly', 'custom'] as constdiff --git a/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md b/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.mdindex 604d60c4..e1c593e4 100644--- a/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md+++ b/packages/dsh-tauri-ui/THIRD_PARTY_NOTICES.md@@ -21,6 +21,13 @@ Derived (upstream → this package):- Official settings launcher seat (`ui-settings-general` `SettingsRoot` rendering the account menu) → `src/client/constants/index.ts` (`SETTINGS_TRIGGER_PRIORITY`), `src/client/ui/settings-trigger.tsx`: seat takeover keeping a host for the official account UI, plus the official dictionary strings for the sidebar "new session" button and the ungrouped workspace-group `+` (`new-session.utils.ts`, official `UNGROUPED_KEY`).- Official primitives variants `PermissionRow.selector`, `PermissionSelect`, `AgentPresetSeat` → `src/client/components/chip.tsx`: per-variant wrapping and the official `@container` query that `css-render` can only emit as a top-level raw rule.+## Schedule-detail refork (`0.2.1-alpha.1`)++- Release-matched revision: `ec48669f48ac81bac353fc646e7cf9c57241242f` from <https://github.com/deepseek-ai/deepseek-harness>.+- `packages/client/ui-schedule/src/client/DatePicker.tsx`, `ClockPicker.tsx` and `TaskManagerPage.module.css` → `src/client/components/date-picker.tsx`, `time-picker.tsx`, `picker-popover.tsx`, and the `SegmentedControl` underline variant: calendar/clock geometry, native anchored popovers, keyboard interaction and rule/history strip.+- Date/calendar trigger uses the existing shared `Calendar` glyph because the installed official primitives do not export its calendar glyph; clock and chevrons use the public official exports. Recurring local tasks add minute-only clock precision to preserve the existing `HH:mm` host contract.+- Existing `Checkbox` default geometry remains unchanged; `size="xs"` is a local compact extension for weekday options.+## hongweifei/dsh-chat-content-visibility-auto- Repository: <https://github.com/hongweifei/dsh-chat-content-visibility-auto>diff --git a/packages/dsh-tauri-ui/src/client/components/checkbox.test.tsx b/packages/dsh-tauri-ui/src/client/components/checkbox.test.tsxnew file mode 100644index 00000000..097e6e18--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/checkbox.test.tsx@@ -0,0 +1,24 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'+import { Checkbox } from './checkbox'++vi.mock('dsh-tauri/client', async () => ({ tv: (await import('tailwind-variants')).tv }))+afterEach(cleanup)++it('keeps the default size and provides a compact xs checkbox without changing its accessible interaction', () => {+ const onChange = vi.fn()+ const view = render(+ <>+ <Checkbox checked={false} onChange={onChange}>Default</Checkbox>+ <Checkbox size="xs" checked={false} onChange={onChange}>Monday</Checkbox>+ </>,+ )+ const normal = view.getByRole('checkbox', { name: 'Default' })+ const small = view.getByRole('checkbox', { name: 'Monday' })+ expect(normal.classList.contains('w-[16px]')).toBe(true)+ expect(small.classList.contains('w-[12px]')).toBe(true)+ expect(small.closest('label')!.classList.contains('text-[12px]')).toBe(true)+ fireEvent.click(small)+ expect(onChange).toHaveBeenCalledExactlyOnceWith(true)+})diff --git a/packages/dsh-tauri-ui/src/client/components/checkbox.tsx b/packages/dsh-tauri-ui/src/client/components/checkbox.tsxindex f07aa804..34f682fe 100644--- a/packages/dsh-tauri-ui/src/client/components/checkbox.tsx+++ b/packages/dsh-tauri-ui/src/client/components/checkbox.tsx@@ -1,4 +1,5 @@// 引用源 @deepseek-ai/dsh-client-ui-primitives · packages/client/ui-primitives/src/Checkbox.tsx · 版本 0.1.7-rc.2(≥0.1.7-alpha.1)· hash default=_checkbox_1wz3s_1+import type { VariantProps } from 'dsh-tauri/client'import type { ReactElement, ReactNode } from 'react'import { tv } from 'dsh-tauri/client'@@ -9,18 +10,26 @@ export interface CheckboxProps {'children'?: ReactNode'aria-label'?: string'title'?: string+ 'size'?: NonNullable<VariantProps<typeof checkbox>['size']>}const checkbox = tv({slots: {- base: 'inline-flex items-center gap-[6px] text-primary cursor-pointer [font-family:inherit] text-[14px] leading-[20px] has-[>input:disabled]:cursor-not-allowed has-[>input:disabled]:opacity-50',- input: 'box-border shrink-0 w-[16px] h-[16px] m-0 cursor-[inherit] accent-[var(--dsw-alias-button-primary-fill)] focus-visible:[outline:var(--dsw-focus-ring-width,2px)_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:1px]',+ base: 'inline-flex items-center gap-[6px] text-primary cursor-pointer [font-family:inherit] has-[>input:disabled]:cursor-not-allowed has-[>input:disabled]:opacity-50',+ input: 'box-border shrink-0 m-0 cursor-[inherit] accent-[var(--dsw-alias-button-primary-fill)] focus-visible:[outline:var(--dsw-focus-ring-width,2px)_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:1px]',label: 'min-w-0 text-secondary',},+ variants: {+ size: {+ md: { base: 'text-[14px] leading-[20px]', input: 'w-[16px] h-[16px]' },+ xs: { base: 'text-[12px] leading-[16px]', input: 'w-[12px] h-[12px]' },+ },+ },+ defaultVariants: { size: 'md' },})-export function Checkbox({ checked, disabled, onChange, children, 'aria-label': ariaLabel, title }: CheckboxProps): ReactElement {- const styles = checkbox()+export function Checkbox({ checked, disabled, onChange, children, 'aria-label': ariaLabel, title, size }: CheckboxProps): ReactElement {+ const styles = checkbox({ size })return (<label className={styles.base()} title={title}><inputdiff --git a/packages/dsh-tauri-ui/src/client/components/chip.test.tsx b/packages/dsh-tauri-ui/src/client/components/chip.test.tsxindex 9201b6ca..fc491f2d 100644--- a/packages/dsh-tauri-ui/src/client/components/chip.test.tsx+++ b/packages/dsh-tauri-ui/src/client/components/chip.test.tsx@@ -12,6 +12,15 @@ vi.mock('dsh-tauri/client', async () => {afterEach(cleanup)describe('chip', () => {+ it('applies caller class overrides only to the base slot', () => {+ const view = render(<Chip variant="seat" className="min-h-[32px] rounded-[18px] text-[14px] font-normal">task value</Chip>)+ const button = view.getByRole('button')+ expect(button.classList.contains('min-h-[32px]')).toBe(true)+ expect(button.classList.contains('rounded-[18px]')).toBe(true)+ expect(button.classList.contains('text-[14px]')).toBe(true)+ expect(button.querySelector('span')!.classList.contains('text-[14px]')).toBe(false)+ })+it('把调用方 ref 交给真实 button,供 portal 菜单测量锚点', () => {const ref = createRef<HTMLButtonElement>()const view = render(<Chip ref={ref} variant="seat" aria-label="选择工作区">选择工作区</Chip>)diff --git a/packages/dsh-tauri-ui/src/client/components/chip.tsx b/packages/dsh-tauri-ui/src/client/components/chip.tsxindex 4cd764e4..51b07d23 100644--- a/packages/dsh-tauri-ui/src/client/components/chip.tsx+++ b/packages/dsh-tauri-ui/src/client/components/chip.tsx@@ -61,9 +61,9 @@ export const Chip = forwardRef<HTMLButtonElement, ChipProps>((): ReactElement => {// 官方 PermissionRow.selector 不包 icon/label/badge,其余两个 variant 按 PermissionSelect/AgentPresetSeat 包裹。const wraps = variant !== 'selector'- const styles = chip({ variant, hasIcon: wraps && icon != null, className })+ const styles = chip({ variant, hasIcon: wraps && icon != null })return (- <button type="button" className={styles.base()} {...rest} ref={ref}>+ <button type="button" className={styles.base({ className })} {...rest} ref={ref}>{wraps && icon != null ? <span className={styles.icon()} aria-hidden>{icon}</span> : icon}{wraps && children != null ? <span className={styles.label()}>{children}</span> : children}{wraps && badge != null ? <span className={styles.badge()} aria-hidden>{badge}</span> : badge}diff --git a/packages/dsh-tauri-ui/src/client/components/date-picker.tsx b/packages/dsh-tauri-ui/src/client/components/date-picker.tsxnew file mode 100644index 00000000..03132113--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/date-picker.tsx@@ -0,0 +1,180 @@+import type { ButtonHTMLAttributes, KeyboardEvent } from 'react'+import { IconChevronLeftOutlineRegular, IconChevronRightOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'+import { tv, useWatchImmediate } from 'dsh-tauri/client'+import { useRef, useState } from 'react'+import { Icon } from './icon'+import { Calendar } from './icons'+import { PickerPopover, pickerTrigger } from './picker-popover'++export interface DatePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'value' | 'onChange'> {+ value: string+ onChange: (value: string) => void+ label: string+ locale: string+ previousMonthLabel: string+ nextMonthLabel: string+ weekdayLabels?: readonly [string, string, string, string, string, string, string]+}++interface MonthView {+ year: number+ month: number+ day: number+}++const WEEKDAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']+const calendar = tv({+ slots: {+ panel: 'flex-col gap-[4px] w-[232px] p-[8px]',+ head: 'flex items-center justify-between gap-[4px]',+ title: 'flex-auto text-primary text-[13px] leading-[1.6] text-center',+ nav: 'inline-flex shrink-0 items-center justify-center w-[26px] h-[26px] p-0 border-0 rounded-[8px] bg-transparent text-secondary cursor-pointer hover:not-disabled:bg-hover disabled:cursor-default disabled:text-tertiary focus-visible:[outline:2px_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:-2px]',+ grid: 'flex flex-col gap-[2px]',+ week: 'grid grid-cols-7 gap-[2px]',+ weekday: 'flex items-center justify-center h-[22px] text-tertiary text-[11px] leading-[1.6]',+ day: 'flex items-center justify-center h-[28px] rounded-[8px] text-primary text-[13px] leading-[1.6] tabular-nums cursor-pointer outline-none hover:bg-hover focus-visible:[outline:2px_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:-2px] aria-[current=date]:shadow-[inset_0_0_0_0.5px_var(--dsw-alias-border-l3)] aria-selected:bg-[var(--dsw-alias-button-ghost-active-fill)] aria-selected:shadow-[inset_0_0_0_1px_var(--dsw-alias-button-ghost-active-border)]',+ blank: 'h-[28px]',+ },+})++function utcDate(year: number, month: number, day: number): Date {+ const date = new Date(0)+ date.setUTCFullYear(year, month, day)+ return date+}++function viewOf(value: string): MonthView {+ const date = /^\d{4}-\d{2}-\d{2}$/.test(value) ? new Date(`${value}T00:00:00Z`) : new Date(Number.NaN)+ if (Number.isFinite(date.getTime()) && date.getUTCFullYear() > 0 && date.toISOString().slice(0, 10) === value)+ return { year: date.getUTCFullYear(), month: date.getUTCMonth(), day: date.getUTCDate() }+ const today = new Date()+ return { year: today.getFullYear(), month: today.getMonth(), day: today.getDate() }+}++function daysIn(view: MonthView): number {+ return utcDate(view.year, view.month + 1, 0).getUTCDate()+}++function isoOf(view: MonthView, day: number): string {+ return `${String(view.year).padStart(4, '0')}-${String(view.month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`+}++export function DatePicker({ value, onChange, label, locale, previousMonthLabel, nextMonthLabel, weekdayLabels, disabled, className, onClick, ...rest }: DatePickerProps) {+ const [open, setOpen] = useState(false)+ const [view, setView] = useState(() => viewOf(value))+ const anchorRef = useRef<HTMLButtonElement>(null)+ const daysRef = useRef(new Map<number, HTMLDivElement>())+ const shown = open && !disabled+ const styles = calendar()+ useWatchImmediate([shown, disabled], ([visible, blocked]) => {+ if (blocked)+ setOpen(false)+ if (visible)+ setView(viewOf(value))+ })+ useWatchImmediate([shown, view], () => {+ if (shown)+ daysRef.current.get(view.day)?.focus()+ })+ const total = daysIn(view)+ const offset = (utcDate(view.year, view.month, 1).getUTCDay() + 6) % 7+ const weekCount = Math.ceil((offset + total) / 7)+ const monthTitle = new Intl.DateTimeFormat(locale, { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(utcDate(view.year, view.month, 1))+ const weekdayFormat = new Intl.DateTimeFormat(locale, { weekday: 'narrow', timeZone: 'UTC' })+ const weekdays = weekdayLabels ?? Array.from({ length: 7 }, (_, index) => weekdayFormat.format(utcDate(2024, 0, index + 1)))+ const today = viewOf('')+ const todayIso = isoOf(today, today.day)++ function shiftMonth(step: number): void {+ setView((current) => {+ const months = Math.min(Math.max(current.year * 12 + current.month + step, 12), 9999 * 12 + 11)+ const moved = { ...current, year: Math.floor(months / 12), month: months % 12 }+ return { ...moved, day: Math.min(current.day, daysIn(moved)) }+ })+ }++ function pick(day: number): void {+ setView(current => ({ ...current, day }))+ onChange(isoOf(view, day))+ }++ function onCellKeyDown(event: KeyboardEvent<HTMLDivElement>, day: number): void {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ pick(day)+ return+ }+ const step = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 }[event.key]+ if (step === undefined)+ return+ event.preventDefault()+ setView(current => ({ ...current, day: Math.min(Math.max(day + step, 1), total) }))+ }++ return (+ <>+ <button+ {...rest}+ ref={anchorRef}+ type="button"+ className={pickerTrigger({ className })}+ disabled={disabled}+ aria-label={rest['aria-label'] ?? label}+ aria-haspopup="dialog"+ aria-expanded={shown}+ onClick={(event) => {+ onClick?.(event)+ if (!event.defaultPrevented)+ setOpen(state => !state)+ }}+ >+ <span>{value.replaceAll('-', '/')}</span>+ <Icon as={Calendar} className="shrink-0 text-tertiary" />+ </button>+ <PickerPopover open={shown} anchorRef={anchorRef} label={label} className={styles.panel()} onClose={() => setOpen(false)}>+ <div className={styles.head()}>+ <button type="button" className={styles.nav()} aria-label={previousMonthLabel} disabled={view.year === 1 && view.month === 0} onClick={() => shiftMonth(-1)}>+ <IconChevronLeftOutlineRegular />+ </button>+ <span className={styles.title()} aria-live="polite">{monthTitle}</span>+ <button type="button" className={styles.nav()} aria-label={nextMonthLabel} disabled={view.year === 9999 && view.month === 11} onClick={() => shiftMonth(1)}>+ <IconChevronRightOutlineRegular />+ </button>+ </div>+ <div className={styles.grid()} role="grid" aria-label={monthTitle}>+ <div role="row" className={styles.week()}>+ {weekdays.map((weekday, index) => <div key={WEEKDAYS[index]} role="columnheader" className={styles.weekday()}>{weekday}</div>)}+ </div>+ {Array.from({ length: weekCount }, (_, week) => (+ <div key={week} role="row" className={styles.week()}>+ {Array.from({ length: 7 }, (_, column) => week * 7 + column - offset + 1).map(day => (+ day < 1 || day > total+ ? <div key={day} role="gridcell" aria-hidden="true" className={styles.blank()} />+ : (+ <div+ key={day}+ ref={(element) => {+ if (element)+ daysRef.current.set(day, element)+ else+ daysRef.current.delete(day)+ }}+ role="gridcell"+ aria-selected={isoOf(view, day) === value}+ aria-current={isoOf(view, day) === todayIso ? 'date' : undefined}+ tabIndex={day === view.day ? 0 : -1}+ className={styles.day()}+ onClick={() => pick(day)}+ onKeyDown={event => onCellKeyDown(event, day)}+ >+ {day}+ </div>+ )+ ))}+ </div>+ ))}+ </div>+ </PickerPopover>+ </>+ )+}diff --git a/packages/dsh-tauri-ui/src/client/components/date-time-picker.test.tsx b/packages/dsh-tauri-ui/src/client/components/date-time-picker.test.tsxnew file mode 100644index 00000000..dd40e9d2--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/date-time-picker.test.tsx@@ -0,0 +1,193 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'+import { useState } from 'react'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { DatePicker } from './date-picker'+import { TimePicker } from './time-picker'++vi.mock('@deepseek-ai/dsh-client-store', () => ({+ createSnapshotStore: () => { throw new Error('Settings store is outside the picker test contract') },+}))++vi.mock('dsh-tauri/client', async () => {+ const [{ tv }, { useEventListener, useWatchImmediate }] = await Promise.all([import('tailwind-variants'), import('@reause/core')])+ return { tv, useEventListener, useWatchImmediate }+})++afterEach(() => {+ cleanup()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++const dateLabels = { label: 'Date', locale: 'en-US', previousMonthLabel: 'Previous month', nextMonthLabel: 'Next month' }+const timeLabels = { label: 'Time', hourLabel: 'Hours', minuteLabel: 'Minutes', secondLabel: 'Seconds' }++describe('date and time pickers', () => {+ it('calendar keeps ISO wall dates through leap months and month-end navigation', () => {+ const changed = vi.fn()+ function Field() {+ const [value, setValue] = useState('2024-01-31')+ return (+ <DatePicker+ {...dateLabels}+ value={value}+ onChange={(next) => {+ changed(next)+ setValue(next)+ }}+ />+ )+ }+ render(<Field />)+ const trigger = screen.getByRole('button', { name: 'Date' })+ expect(trigger.textContent).toContain('2024/01/31')+ fireEvent.click(trigger)+ expect(document.activeElement).toBe(screen.getByRole('gridcell', { name: '31' }))+ fireEvent.click(screen.getByRole('button', { name: 'Next month' }))+ const day = screen.getByRole('gridcell', { name: '29' })+ expect(screen.getAllByRole('gridcell').filter(cell => cell.getAttribute('aria-hidden') !== 'true')).toHaveLength(29)+ expect(document.activeElement).toBe(day)+ expect(changed).not.toHaveBeenCalled()+ fireEvent.keyDown(day, { key: 'Enter' })+ expect(changed).toHaveBeenLastCalledWith('2024-02-29')+ expect(trigger.textContent).toContain('2024/02/29')+ expect(day.getAttribute('aria-selected')).toBe('true')+ fireEvent.click(screen.getByRole('button', { name: 'Previous month' }))+ expect(document.activeElement).toBe(screen.getByRole('gridcell', { name: '29' }))+ })++ it('calendar keyboard clamps at month boundaries and reopening follows the controlled value', () => {+ const changed = vi.fn()+ const view = render(<DatePicker {...dateLabels} value="2024-02-01" onChange={changed} />)+ const trigger = screen.getByRole('button', { name: 'Date' })+ fireEvent.click(trigger)+ fireEvent.keyDown(screen.getByRole('gridcell', { name: '1' }), { key: 'ArrowUp' })+ expect(document.activeElement).toBe(screen.getByRole('gridcell', { name: '1' }))+ fireEvent.keyDown(document.activeElement!, { key: 'ArrowDown' })+ expect(document.activeElement).toBe(screen.getByRole('gridcell', { name: '8' }))+ fireEvent.keyDown(document.activeElement!, { key: ' ' })+ expect(changed).toHaveBeenLastCalledWith('2024-02-08')+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' })+ view.rerender(<DatePicker {...dateLabels} value="2024-12-31" onChange={changed} />)+ fireEvent.click(trigger)+ expect(document.activeElement).toBe(screen.getByRole('gridcell', { name: '31' }))+ fireEvent.click(screen.getByRole('button', { name: 'Next month' }))+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' })+ expect(changed).toHaveBeenLastCalledWith('2025-01-31')+ })++ it('clock opens on selected columns and keyboard changes only the picked part', () => {+ const changed = vi.fn()+ function Field() {+ const [value, setValue] = useState('09:58:42.125')+ return (+ <TimePicker+ {...timeLabels}+ value={value}+ onChange={(next) => {+ changed(next)+ setValue(next)+ }}+ />+ )+ }+ render(<Field />)+ fireEvent.click(screen.getByRole('button', { name: 'Time' }))+ const hours = screen.getByRole('listbox', { name: 'Hours' })+ const minutes = screen.getByRole('listbox', { name: 'Minutes' })+ const seconds = screen.getByRole('listbox', { name: 'Seconds' })+ expect(within(hours).getAllByRole('option')).toHaveLength(24)+ expect(within(minutes).getAllByRole('option')).toHaveLength(60)+ expect(within(seconds).getAllByRole('option')).toHaveLength(60)+ expect(document.activeElement).toBe(within(hours).getByRole('option', { name: '09' }))+ expect(within(minutes).getByRole('option', { name: '58' }).tabIndex).toBe(0)+ expect(within(seconds).getByRole('option', { name: '42' }).tabIndex).toBe(0)+ fireEvent.keyDown(document.activeElement!, { key: 'End' })+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' })+ expect(changed).toHaveBeenLastCalledWith('23:58:42')+ fireEvent.keyDown(document.activeElement!, { key: 'ArrowRight' })+ expect(document.activeElement).toBe(within(minutes).getByRole('option', { name: '23' }))+ fireEvent.keyDown(document.activeElement!, { key: 'End' })+ fireEvent.keyDown(document.activeElement!, { key: ' ' })+ expect(changed).toHaveBeenLastCalledWith('23:59:42')+ fireEvent.keyDown(document.activeElement!, { key: 'ArrowRight' })+ fireEvent.keyDown(document.activeElement!, { key: 'Home' })+ fireEvent.keyDown(document.activeElement!, { key: 'Enter' })+ expect(changed).toHaveBeenLastCalledWith('23:59:00')+ expect(screen.getByRole('button', { name: 'Time' }).textContent).toContain('23:59:00')+ })++ it('minute precision omits seconds and returns the host-compatible HH:mm value', () => {+ const changed = vi.fn()+ const view = render(<TimePicker {...timeLabels} value="09:05" seconds={false} onChange={changed} />)+ const trigger = screen.getByRole('button', { name: 'Time' })+ expect(trigger.textContent).toContain('09:05')+ fireEvent.click(trigger)+ expect(screen.queryByRole('listbox', { name: 'Seconds' })).toBeNull()+ fireEvent.click(within(screen.getByRole('listbox', { name: 'Minutes' })).getByRole('option', { name: '06' }))+ expect(changed).toHaveBeenLastCalledWith('09:06')+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' })+ view.rerender(<TimePicker {...timeLabels} value="17:40" onChange={changed} />)+ fireEvent.click(trigger)+ expect(document.activeElement).toBe(within(screen.getByRole('listbox', { name: 'Hours' })).getByRole('option', { name: '17' }))+ fireEvent.click(within(screen.getByRole('listbox', { name: 'Minutes' })).getByRole('option', { name: '41' }))+ expect(changed).toHaveBeenLastCalledWith('17:41:00')+ })++ it.each(['date', 'time'] as const)('%s popover is portaled, anchored, outside-dismissed and Escape returns focus', (kind) => {+ const changed = vi.fn()+ const view = render(kind === 'date'+ ? <DatePicker {...dateLabels} value="2024-02-20" onChange={changed} />+ : <TimePicker {...timeLabels} value="10:20:30" onChange={changed} />)+ const trigger = screen.getByRole('button', { name: kind === 'date' ? 'Date' : 'Time' })+ let left = 100+ vi.spyOn(trigger, 'getBoundingClientRect').mockImplementation(() => ({ left, right: left + 100, top: 50, bottom: 82, width: 100, height: 32, x: left, y: 50, toJSON: () => ({}) }))+ fireEvent.click(trigger)+ const popup = screen.getByRole('dialog')+ expect(popup.parentElement).toBe(document.body)+ expect(view.container.contains(popup)).toBe(false)+ expect(popup.style.left).toBe('100px')+ expect(popup.style.top).toBe('86px')+ expect(document.activeElement?.getAttribute('role')).toBe(kind === 'date' ? 'gridcell' : 'option')+ expect(popup.className).toContain('z-[1100]')+ expect(popup.className).toContain('rounded-[16px]')+ fireEvent.pointerDown(popup)+ expect(screen.getByRole('dialog')).toBe(popup)+ left = 130+ fireEvent.scroll(window)+ expect(popup.style.left).toBe('130px')+ fireEvent.keyDown(document.activeElement!, { key: 'Escape' })+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(document.activeElement).toBe(trigger)+ expect(trigger.getAttribute('aria-expanded')).toBe('false')+ fireEvent.click(trigger)+ fireEvent.pointerDown(document.body)+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(changed).not.toHaveBeenCalled()+ fireEvent.click(trigger)+ view.unmount()+ fireEvent.scroll(window)+ fireEvent.keyDown(document.body, { key: 'Escape' })+ expect(screen.queryByRole('dialog')).toBeNull()+ })++ it('disabled pickers do not open and becoming disabled closes an existing panel', () => {+ const changed = vi.fn()+ const view = render(+ <>+ <DatePicker {...dateLabels} value="2024-02-20" disabled onChange={changed} />+ <TimePicker {...timeLabels} value="09:00" disabled onChange={changed} />+ </>,+ )+ fireEvent.click(screen.getByRole('button', { name: 'Date' }))+ fireEvent.click(screen.getByRole('button', { name: 'Time' }))+ expect(screen.queryByRole('dialog')).toBeNull()+ view.rerender(<TimePicker {...timeLabels} value="09:00" onChange={changed} />)+ fireEvent.click(screen.getByRole('button', { name: 'Time' }))+ expect(screen.getByRole('dialog').getAttribute('aria-label')).toBe('Time')+ view.rerender(<TimePicker {...timeLabels} value="09:00" disabled onChange={changed} />)+ expect(screen.queryByRole('dialog')).toBeNull()+ expect(changed).not.toHaveBeenCalled()+ })+})diff --git a/packages/dsh-tauri-ui/src/client/components/index.ts b/packages/dsh-tauri-ui/src/client/components/index.tsindex f84092e4..1db7286e 100644--- a/packages/dsh-tauri-ui/src/client/components/index.ts+++ b/packages/dsh-tauri-ui/src/client/components/index.ts@@ -4,6 +4,7 @@ export * from './card'export * from './checkbox'export * from './chip'export * from './conversation-bar'+export * from './date-picker'export * from './dot'export * from './field'export * from './icon'@@ -15,3 +16,4 @@ export * from './select'export * from './tag'export * from './text'export * from './textarea'+export * from './time-picker'diff --git a/packages/dsh-tauri-ui/src/client/components/picker-popover.tsx b/packages/dsh-tauri-ui/src/client/components/picker-popover.tsxnew file mode 100644index 00000000..acc87244--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/picker-popover.tsx@@ -0,0 +1,54 @@+import type { CSSProperties, ReactNode, RefObject } from 'react'+import { useAnchoredPosition, useDismissOnOutsidePointer } from '@deepseek-ai/dsh-client-ui-primitives'+import { tv, useEventListener } from 'dsh-tauri/client'+import { useRef } from 'react'+import { createPortal } from 'react-dom'++export const pickerTrigger = tv({+ base: 'inline-flex flex-[0_1_auto] min-w-0 items-center justify-end gap-[6px] px-[8px] py-[5px] border-none rounded-[18px] bg-transparent text-primary [font-family:inherit] text-[14px] leading-[1.6] text-right tabular-nums cursor-pointer transition-colors duration-150 hover:not-disabled:bg-hover disabled:text-tertiary disabled:cursor-default focus-visible:[outline:2px_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:1px]',+})++const panel = tv({+ base: 'fixed box-border z-[1100] flex border-0 rounded-[16px] bg-[var(--dsw-specific-menu)] [backdrop-filter:var(--dsw-menu-backdrop-filter)] [--dsw-elevation-stroke-color:var(--dsw-alias-border-l1)] shadow-[var(--dsw-elevation-prominent)] [--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)] [--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)]',+})++const MEASURE_STYLE: CSSProperties = { visibility: 'hidden', left: 0, top: 0 }++interface PickerPopoverProps {+ open: boolean+ anchorRef: RefObject<HTMLButtonElement | null>+ label: string+ className?: string+ onClose: () => void+ children: ReactNode+}++export function PickerPopover({ open, anchorRef, label, className, onClose, children }: PickerPopoverProps) {+ const panelRef = useRef<HTMLDivElement>(null)+ const documentRef = useRef(typeof document === 'undefined' ? null : document)+ useDismissOnOutsidePointer(anchorRef, open, onClose, panelRef)+ const position = useAnchoredPosition({ open, anchorRef, panelRef, gap: 4, margin: 12 })+ useEventListener(documentRef, 'keydown', (event) => {+ if (!open || event.key !== 'Escape' || (!anchorRef.current?.contains(event.target as Node) && !panelRef.current?.contains(event.target as Node)))+ return+ event.preventDefault()+ event.stopPropagation()+ onClose()+ anchorRef.current?.focus()+ }, { capture: true })+ if (!open)+ return null+ return createPortal(+ <div+ ref={panelRef}+ role="dialog"+ aria-label={label}+ className={panel({ className })}+ style={position ?? MEASURE_STYLE}+ onClick={event => event.stopPropagation()}+ >+ {children}+ </div>,+ document.body,+ )+}diff --git a/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx b/packages/dsh-tauri-ui/src/client/components/segmented-control.tsxindex e9fddfa3..1d9b8b44 100644--- a/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx+++ b/packages/dsh-tauri-ui/src/client/components/segmented-control.tsx@@ -1,3 +1,4 @@+import type { VariantProps } from 'dsh-tauri/client'import type { ReactElement } from 'react'import { tv } from 'dsh-tauri/client'import { useRef } from 'react'@@ -16,19 +17,32 @@ export interface SegmentedControlProps {disabled?: booleanoptions: readonly SegmentedControlOption[]onChange: (next: string) => void+ variant?: NonNullable<VariantProps<typeof segmentedControl>['variant']>}const segmentedControl = tv({slots: {- base: 'box-border inline-flex items-center gap-[2px] p-[2px] border-none rounded-[10px] bg-module-platform',- option: 'box-border inline-flex items-center justify-center gap-[6px] min-h-[28px] px-[12px] border-none rounded-[8px] bg-transparent text-secondary cursor-pointer [font-family:inherit] text-[13px] leading-[20px] whitespace-nowrap hover:not-disabled:bg-hover hover:not-disabled:text-primary focus-visible:shadow-focus-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',+ base: 'box-border inline-flex items-center border-none',+ option: 'box-border inline-flex items-center justify-center border-none bg-transparent cursor-pointer [font-family:inherit] text-[13px] whitespace-nowrap focus-visible:shadow-focus-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50',},variants: {- selected: {- true: { option: 'bg-layer-1 text-primary font-medium shadow-[inset_0_0_0_0.5px_var(--dsw-alias-border-l3)] hover:not-disabled:bg-layer-1 hover:not-disabled:text-primary' },- false: {},+ variant: {+ segmented: {+ base: 'gap-[2px] p-[2px] rounded-[10px] bg-module-platform',+ option: 'gap-[6px] min-h-[28px] px-[12px] rounded-[8px] text-secondary leading-[20px] hover:not-disabled:bg-hover hover:not-disabled:text-primary',+ },+ underline: {+ base: 'flex-1 min-w-0 gap-[36px] self-end overflow-x-auto pb-px mb-[-1px] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden',+ option: 'relative shrink-0 px-0 pt-0 pb-[9px] text-tertiary leading-[16px] font-medium after:absolute after:inset-x-0 after:bottom-[-1px] after:h-[2px] after:rounded-[2px] after:content-[\'\']',+ },},+ selected: { true: {}, false: {} },},+ compoundVariants: [+ { variant: 'segmented', selected: true, class: { option: 'bg-layer-1 text-primary font-medium shadow-[inset_0_0_0_0.5px_var(--dsw-alias-border-l3)] hover:not-disabled:bg-layer-1 hover:not-disabled:text-primary' } },+ { variant: 'underline', selected: true, class: { option: 'text-business after:bg-business' } },+ ],+ defaultVariants: { variant: 'segmented' },})const FORWARD_KEYS = ['ArrowRight', 'ArrowDown']@@ -58,9 +72,9 @@ export function stepSegment<T extends { disabled?: boolean }>(return undefined}-export function SegmentedControl({ id, label, value, disabled, options, onChange }: SegmentedControlProps): ReactElement {+export function SegmentedControl({ id, label, value, disabled, options, onChange, variant }: SegmentedControlProps): ReactElement {const buttonsRef = useRef<(HTMLButtonElement | null)[]>([])- const styles = segmentedControl()+ const styles = segmentedControl({ variant })const tabbed = id !== undefinedconst selected = options.findIndex(option => option.value === value)@@ -103,7 +117,7 @@ export function SegmentedControl({ id, label, value, disabled, options, onChangetype="button"id={segmentId(index)}role={tabbed ? 'tab' : undefined}- className={segmentedControl({ selected: active }).option()}+ className={segmentedControl({ variant, selected: active }).option()}aria-selected={tabbed ? active : undefined}aria-controls={tabbed && id !== undefined ? `${id}-${option.value}-panel` : undefined}aria-pressed={tabbed ? undefined : active}diff --git a/packages/dsh-tauri-ui/src/client/components/select.tsx b/packages/dsh-tauri-ui/src/client/components/select.tsxindex aaa6341c..e036d441 100644--- a/packages/dsh-tauri-ui/src/client/components/select.tsx+++ b/packages/dsh-tauri-ui/src/client/components/select.tsx@@ -2,6 +2,7 @@import type { ButtonHTMLAttributes, ReactElement, ReactNode } from 'react'import type { ChipVariant } from './chip'import { Menu } from '@deepseek-ai/dsh-client-ui-primitives'+import { useWatchImmediate } from 'dsh-tauri/client'import { useState } from 'react'import { Chip } from './chip'import { Icon } from './icon'@@ -36,15 +37,22 @@ export function Select({chevron,label,onClick,+ disabled,...rest}: SelectProps): ReactElement {const [open, setOpen] = useState(false)+ useWatchImmediate(disabled, () => {+ if (disabled)+ setOpen(false)+ })const selected = options.find(option => option.value === value)return (<Menu- open={open}+ open={open && !disabled}onClose={() => setOpen(false)}onSelect={(id) => {+ if (disabled)+ returnsetOpen(false)onChange(id)}}@@ -55,7 +63,8 @@ export function Select({anchor={(<Chipvariant={variant}- open={open}+ disabled={disabled}+ open={open && !disabled}aria-label={label}aria-haspopup="menu"aria-expanded={open}diff --git a/packages/dsh-tauri-ui/src/client/components/time-picker.tsx b/packages/dsh-tauri-ui/src/client/components/time-picker.tsxnew file mode 100644index 00000000..b8dbaa0d--- /dev/null+++ b/packages/dsh-tauri-ui/src/client/components/time-picker.tsx@@ -0,0 +1,136 @@+import type { ButtonHTMLAttributes, KeyboardEvent } from 'react'+import { IconClockOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'+import { tv, useWatchImmediate } from 'dsh-tauri/client'+import { useRef, useState } from 'react'+import { PickerPopover, pickerTrigger } from './picker-popover'++export interface TimePickerProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'value' | 'onChange'> {+ value: string+ onChange: (value: string) => void+ label: string+ hourLabel: string+ minuteLabel: string+ secondLabel: string+ seconds?: boolean+}++const OPTIONS = [24, 60, 60].map(count => Array.from({ length: count }, (_, index) => String(index).padStart(2, '0')))+const clock = tv({+ slots: {+ panel: 'flex-row gap-[2px] p-[3px]',+ column: 'flex flex-col w-[52px] max-h-[216px] overflow-y-auto overscroll-contain',+ option: 'flex shrink-0 items-center justify-center min-h-[32px] rounded-[10px] text-primary text-[13px] leading-[1.6] tabular-nums cursor-pointer outline-none hover:bg-hover focus-visible:[outline:2px_solid_var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))] focus-visible:[outline-offset:-2px] aria-selected:bg-[var(--dsw-alias-button-ghost-active-fill)] aria-selected:shadow-[inset_0_0_0_1px_var(--dsw-alias-button-ghost-active-border)]',+ },+})++function clockBase(value: string): string[] {+ return /^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?$/.test(value) ? `${value}:00`.slice(0, 8).split(':') : ['00', '00', '00']+}++export function TimePicker({ value, onChange, label, hourLabel, minuteLabel, secondLabel, seconds = true, disabled, className, onClick, ...rest }: TimePickerProps) {+ const [open, setOpen] = useState(false)+ const [cursor, setCursor] = useState(() => ({ column: 0, index: Number(clockBase(value)[0]) }))+ const anchorRef = useRef<HTMLButtonElement>(null)+ const optionsRef = useRef(new Map<string, HTMLDivElement>())+ const picked = clockBase(value)+ const count = seconds ? 3 : 2+ const labels = [hourLabel, minuteLabel, secondLabel]+ const shown = open && !disabled+ const styles = clock()+ useWatchImmediate([shown, disabled], ([visible, blocked]) => {+ if (blocked)+ setOpen(false)+ if (!visible)+ return+ setCursor({ column: 0, index: Number(picked[0]) })+ for (let column = 0; column < count; column++)+ optionsRef.current.get(`${column}:${Number(picked[column])}`)?.scrollIntoView?.({ block: 'nearest' })+ })+ useWatchImmediate([shown, cursor], () => {+ if (!shown)+ return+ const element = optionsRef.current.get(`${cursor.column}:${cursor.index}`)+ element?.focus()+ element?.scrollIntoView?.({ block: 'nearest' })+ })++ function pick(column: number, option: string, index: number): void {+ setCursor({ column, index })+ const next = [...picked]+ next[column] = option+ onChange(next.slice(0, count).join(':'))+ }++ function onOptionKeyDown(event: KeyboardEvent<HTMLDivElement>, column: number, index: number, option: string): void {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault()+ pick(column, option, index)+ return+ }+ if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {+ event.preventDefault()+ const next = column + (event.key === 'ArrowRight' ? 1 : -1)+ if (next >= 0 && next < count)+ setCursor({ column: next, index: Math.min(index, OPTIONS[next].length - 1) })+ return+ }+ if (event.key === 'Home' || event.key === 'End') {+ event.preventDefault()+ setCursor({ column, index: event.key === 'Home' ? 0 : OPTIONS[column].length - 1 })+ return+ }+ if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp')+ return+ event.preventDefault()+ setCursor({ column, index: Math.min(Math.max(index + (event.key === 'ArrowDown' ? 1 : -1), 0), OPTIONS[column].length - 1) })+ }++ return (+ <>+ <button+ {...rest}+ ref={anchorRef}+ type="button"+ className={pickerTrigger({ className })}+ disabled={disabled}+ aria-label={rest['aria-label'] ?? label}+ aria-haspopup="dialog"+ aria-expanded={shown}+ onClick={(event) => {+ onClick?.(event)+ if (!event.defaultPrevented)+ setOpen(state => !state)+ }}+ >+ <span>{value ? picked.slice(0, count).join(':') : ''}</span>+ <IconClockOutlineRegular className="shrink-0 text-tertiary" />+ </button>+ <PickerPopover open={shown} anchorRef={anchorRef} label={label} className={styles.panel()} onClose={() => setOpen(false)}>+ {OPTIONS.slice(0, count).map((options, column) => (+ <div key={column === 0 ? 'hours' : column === 1 ? 'minutes' : 'seconds'} role="listbox" aria-label={labels[column]} className={styles.column()}>+ {options.map((option, index) => (+ <div+ key={option}+ ref={(element) => {+ const key = `${column}:${index}`+ if (element)+ optionsRef.current.set(key, element)+ else+ optionsRef.current.delete(key)+ }}+ role="option"+ aria-selected={option === picked[column]}+ tabIndex={(cursor.column === column ? cursor.index : Number(picked[column])) === index ? 0 : -1}+ className={styles.option()}+ onClick={() => pick(column, option, index)}+ onKeyDown={event => onOptionKeyDown(event, column, index, option)}+ >+ {option}+ </div>+ ))}+ </div>+ ))}+ </PickerPopover>+ </>+ )+}diff --git a/packages/dsh-tauri-ui/src/client/styles/index.ts b/packages/dsh-tauri-ui/src/client/styles/index.tsindex bdb971b3..8342ad3d 100644--- a/packages/dsh-tauri-ui/src/client/styles/index.ts+++ b/packages/dsh-tauri-ui/src/client/styles/index.ts@@ -2,7 +2,7 @@ import { cssr } from '../utils/cssr'const TAILWINDCSS_GENERATED = `/*! tailwindcss v4.1.11 | MIT License | https://tailwindcss.com */-@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1)}}@layer base,components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-1\\/2{top:50%}.right-\\[8px\\]{right:8px}.isolate{isolation:isolate}.z-30{z-index:30}.z-\\[1\\]{z-index:1}.z-\\[2\\]{z-index:2}.z-\\[1000\\]{z-index:1000}.order-\\[1\\]{order:1}.order-\\[3\\]{order:3}.col-span-3{grid-column:span 3/span 3}.col-span-4{grid-column:span 4/span 4}.col-span-5{grid-column:span 5/span 5}.col-span-6{grid-column:span 6/span 6}.col-span-8{grid-column:span 8/span 8}.col-span-12{grid-column:span 12/span 12}.col-span-full{grid-column:1/-1}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:calc(var(--spacing)*0)}.-mx-\\[2px\\]{margin-inline:-2px}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-\\[-8px\\]{margin-inline:-8px}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-\\[4px\\]{margin-block:4px}.mt-\\[2px\\]{margin-top:2px}.mt-\\[4px\\]{margin-top:4px}.mt-\\[6px\\]{margin-top:6px}.mt-\\[8px\\]{margin-top:8px}.mt-\\[12px\\]{margin-top:12px}.mt-\\[20px\\]{margin-top:20px}.mr-auto{margin-right:auto}.mb-0{margin-bottom:calc(var(--spacing)*0)}.mb-\\[4px\\]{margin-bottom:4px}.mb-\\[10px\\]{margin-bottom:10px}.mb-\\[12px\\]{margin-bottom:12px}.mb-\\[14px\\]{margin-bottom:14px}.-ml-1{margin-left:calc(var(--spacing)*-1)}.ml-\\[4px\\]{margin-left:4px}.ml-\\[8px\\]{margin-left:8px}.ml-auto{margin-left:auto}.box-border{box-sizing:border-box}.line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-none{-webkit-line-clamp:unset;-webkit-box-orient:horizontal;display:block;overflow:visible}.block{display:block}.block\\!{display:block!important}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.h-\\[4px\\]{height:4px}.h-\\[8px\\]{height:8px}.h-\\[10px\\]{height:10px}.h-\\[14px\\]{height:14px}.h-\\[16px\\]{height:16px}.h-\\[18px\\]{height:18px}.h-\\[20px\\]{height:20px}.h-\\[22px\\]{height:22px}.h-\\[24px\\]{height:24px}.h-\\[28px\\]{height:28px}.h-\\[32px\\]{height:32px}.h-\\[36px\\]{height:36px}.h-\\[38px\\]{height:38px}.h-\\[40px\\]{height:40px}.h-\\[42px\\]{height:42px}.h-\\[44px\\]{height:44px}.h-\\[48px\\]{height:48px}.h-\\[56px\\]{height:56px}.h-\\[60px\\]{height:60px}.h-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{height:calc(28px + var(--dsh-content-font-delta,0px))}.h-full{height:100%}.max-h-\\[60vh\\]{max-height:60vh}.max-h-\\[160px\\]{max-height:160px}.max-h-\\[180px\\]{max-height:180px}.max-h-\\[calc\\(100vh-160px\\)\\]\\!{max-height:calc(100vh - 160px)!important}.max-h-\\[min\\(400px\\,52vh\\)\\]{max-height:min(400px,52vh)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\\[28px\\]{min-height:28px}.min-h-\\[64px\\]{min-height:64px}.min-h-\\[96px\\]{min-height:96px}.min-h-\\[240px\\]{min-height:240px}.min-h-\\[260px\\]{min-height:260px}.min-h-\\[320px\\]{min-height:320px}.min-h-full{min-height:100%}.w-\\[8px\\]{width:8px}.w-\\[10px\\]{width:10px}.w-\\[14px\\]{width:14px}.w-\\[16px\\]{width:16px}.w-\\[20px\\]{width:20px}.w-\\[22px\\]{width:22px}.w-\\[24px\\]{width:24px}.w-\\[28px\\]{width:28px}.w-\\[36px\\]{width:36px}.w-\\[44px\\]{width:44px}.w-\\[48px\\]{width:48px}.w-\\[56px\\]{width:56px}.w-\\[200px\\]{width:200px}.w-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{width:calc(28px + var(--dsh-content-font-delta,0px))}.w-\\[calc\\(100\\%\\+4px\\)\\]{width:calc(100% + 4px)}.w-\\[calc\\(100\\%_-_2_\\*_var\\(--dsh-composer-side-clearance\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{width:calc(100% - 2*var(--dsh-composer-side-clearance) - 4*var(--dsh-composer-dock-inset))}.w-\\[min\\(640px\\,100\\%\\)\\]\\!{width:min(640px,100%)!important}.w-\\[min\\(680px\\,100\\%\\)\\]\\!{width:min(680px,100%)!important}.w-\\[min\\(760px\\,100\\%\\)\\]\\!{width:min(760px,100%)!important}.w-\\[min\\(calc\\(var\\(--dsh-composer-card-max-width\\)_\\+_2_\\*_var\\(--dsh-composer-side-clearance\\)\\)\\,100\\%\\)\\]{width:min(calc(var(--dsh-composer-card-max-width) + 2*var(--dsh-composer-side-clearance)),100%)}.w-\\[var\\(--dsh-settings-rail-width\\)\\]{width:var(--dsh-settings-rail-width)}.w-full{width:100%}.w-full\\!{width:100%!important}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[200px\\]{max-width:200px}.max-w-\\[220px\\]{max-width:220px}.max-w-\\[280px\\]{max-width:280px}.max-w-\\[460px\\]{max-width:460px}.max-w-\\[960px\\]{max-width:960px}.max-w-\\[calc\\(var\\(--dsh-composer-card-max-width\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{max-width:calc(var(--dsh-composer-card-max-width) - 4*var(--dsh-composer-dock-inset))}.max-w-\\[min\\(100\\%\\,240px\\)\\]{max-width:min(100%,240px)}.max-w-\\[min\\(100\\%\\,360px\\)\\]{max-width:min(100%,360px)}.max-w-full{max-width:100%}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\\[72px\\]{min-width:72px}.min-w-\\[220px\\]{min-width:220px}.flex-1{flex:1}.flex-\\[0_1_280px\\]{flex:0 280px}.flex-\\[1_1_100\\%\\]{flex:100%}.flex-\\[1_1_220px\\]{flex:220px}.flex-\\[1_1_auto\\]{flex:auto}.flex-none{flex:none}.shrink-0{flex-shrink:0}.-translate-y-1\\/2{--tw-translate-y:calc(calc(1/2*100%)*-1);translate:var(--tw-translate-x)var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.cursor-\\[inherit\\]{cursor:inherit}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}.grid-cols-\\[repeat\\(2\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-\\[repeat\\(12\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(12,minmax(0,1fr))}.grid-rows-\\[0fr\\]{grid-template-rows:0fr}.grid-rows-\\[1fr\\]{grid-template-rows:1fr}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-end{align-items:flex-end}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.gap-0{gap:calc(var(--spacing)*0)}.gap-8{gap:calc(var(--spacing)*8)}.gap-\\[1px\\]{gap:1px}.gap-\\[2px\\]{gap:2px}.gap-\\[4px\\]{gap:4px}.gap-\\[5px\\]{gap:5px}.gap-\\[6px\\]{gap:6px}.gap-\\[7px\\]{gap:7px}.gap-\\[8px\\]{gap:8px}.gap-\\[10px\\]{gap:10px}.gap-\\[10px_12px\\]{gap:10px 12px}.gap-\\[12px\\]{gap:12px}.gap-\\[14px\\]{gap:14px}.gap-\\[16px\\]{gap:16px}.gap-\\[20px\\]{gap:20px}.gap-\\[24px\\]{gap:24px}.self-center{align-self:center}.self-start{align-self:flex-start}.self-stretch{align-self:stretch}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[3px\\]{border-radius:3px}.rounded-\\[4px\\]{border-radius:4px}.rounded-\\[6px\\]{border-radius:6px}.rounded-\\[8px\\]{border-radius:8px}.rounded-\\[10px\\]{border-radius:10px}.rounded-\\[12px\\]{border-radius:12px}.rounded-\\[14px\\]{border-radius:14px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--dsw-radius-lg)}.rounded-md{border-radius:var(--dsw-radius-md)}.rounded-sm{border-radius:var(--dsw-radius-sm)}.rounded-xl{border-radius:var(--dsw-radius-xl)}.rounded-xs{border-radius:var(--dsw-radius-xs)}.rounded-tl-\\[16px\\]{border-top-left-radius:16px}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-\\[0\\.5px\\]{border-style:var(--tw-border-style);border-width:.5px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-b-\\[0\\.5px\\]{border-bottom-style:var(--tw-border-style);border-bottom-width:.5px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-none{--tw-border-style:none;border-style:none}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)30%,transparent)}}.border-\\[color\\:var\\(--dsw-alias-line-secondary\\,currentColor\\)\\]{border-color:var(--dsw-alias-line-secondary,currentColor)}.border-border-l2{border-color:var(--dsw-alias-border-l2)}.border-border-l3{border-color:var(--dsw-alias-border-l3)}.border-border-l4{border-color:var(--dsw-alias-border-l4)}.border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.border-brand{border-color:var(--dsw-alias-brand-primary)}.border-business\\/35{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-business\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-current{border-color:currentColor}.border-error\\/35{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-error\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)35%,transparent)}}.border-success\\/35{border-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.border-success\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)35%,transparent)}}.border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.border-l-transparent{border-left-color:#0000}.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-\\[color\\:var\\(--swatch-color\\)\\]{background-color:var(--swatch-color)}.bg-\\[var\\(--dsw-alias-bg-base\\)\\]{background-color:var(--dsw-alias-bg-base)}.bg-\\[var\\(--dsw-alias-bg-base\\,var\\(--dsw-alias-bg-module-platform\\)\\)\\]{background-color:var(--dsw-alias-bg-base,var(--dsw-alias-bg-module-platform))}.bg-\\[var\\(--dsw-alias-button-elevated-fill\\)\\]{background-color:var(--dsw-alias-button-elevated-fill)}.bg-\\[var\\(--dsw-alias-surface-tinted\\)\\]{background-color:var(--dsw-alias-surface-tinted)}.bg-\\[var\\(--dsw-specific-sidebar-fill\\)\\]{background-color:var(--dsw-specific-sidebar-fill)}.bg-\\[var\\(--dsw-specific-sidebar-nav-item-active\\)\\]{background-color:var(--dsw-specific-sidebar-nav-item-active)}.bg-border-l2{background-color:var(--dsw-alias-border-l2)}.bg-brand{background-color:var(--dsw-alias-brand-primary)}.bg-business\\/8{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-business\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-current{background-color:currentColor}.bg-error\\/8{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.bg-error\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)8%,transparent)}}.bg-hover{background-color:var(--dsw-alias-interactive-bg-hover)}.bg-layer-1{background-color:var(--dsw-alias-bg-layer-1)}.bg-layer-3{background-color:var(--dsw-alias-bg-layer-3)}.bg-module-platform{background-color:var(--dsw-alias-bg-module-platform)}.bg-primary-fill{background-color:var(--dsw-alias-button-primary-fill)}.bg-success\\/8{background-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.bg-success\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)8%,transparent)}}.bg-transparent{background-color:#0000}.bg-\\[image\\:linear-gradient\\(to_top_right\\,transparent_calc\\(50\\%_-_1px\\)\\,var\\(--dsw-alias-label-tertiary\\)\\,transparent_calc\\(50\\%_\\+_1px\\)\\)\\]{background-image:linear-gradient(to top right,transparent calc(50% - 1px),var(--dsw-alias-label-tertiary),transparent calc(50% + 1px))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-\\[2px\\]{padding:2px}.p-\\[6px\\]{padding:6px}.p-\\[8px\\]{padding:8px}.p-\\[10px\\]{padding:10px}.p-\\[12px\\]{padding:12px}.px-\\[2px\\]{padding-inline:2px}.px-\\[6px\\]{padding-inline:6px}.px-\\[7px\\]{padding-inline:7px}.px-\\[8px\\]{padding-inline:8px}.px-\\[10px\\]{padding-inline:10px}.px-\\[12px\\]{padding-inline:12px}.px-\\[14px\\]{padding-inline:14px}.px-\\[16px\\]{padding-inline:16px}.px-\\[24px\\]{padding-inline:24px}.px-\\[36px\\]{padding-inline:36px}.px-\\[clamp\\(24px\\,4vw\\,48px\\)\\]{padding-inline:clamp(24px,4vw,48px)}.py-\\[1px\\]{padding-block:1px}.py-\\[2px\\]{padding-block:2px}.py-\\[4px\\]{padding-block:4px}.py-\\[5px\\]{padding-block:5px}.py-\\[6px\\]{padding-block:6px}.py-\\[7px\\]{padding-block:7px}.py-\\[8px\\]{padding-block:8px}.py-\\[9px\\]{padding-block:9px}.py-\\[10px\\]{padding-block:10px}.py-\\[12px\\]{padding-block:12px}.py-\\[14px\\]{padding-block:14px}.py-\\[16px\\]{padding-block:16px}.py-\\[24px\\]{padding-block:24px}.py-\\[28px\\]{padding-block:28px}.py-\\[32px\\]{padding-block:32px}.py-\\[40px\\]{padding-block:40px}.py-\\[48px\\]{padding-block:48px}.pt-\\[2px\\]{padding-top:2px}.pt-\\[12px\\]{padding-top:12px}.pt-\\[28px\\]{padding-top:28px}.pr-\\[4px\\]{padding-right:4px}.pr-\\[5px\\]{padding-right:5px}.pr-\\[10px\\]{padding-right:10px}.pb-\\[46px\\]{padding-bottom:46px}.pb-\\[48px\\]{padding-bottom:48px}.pl-\\[2px\\]{padding-left:2px}.pl-\\[8px\\]{padding-left:8px}.pl-\\[12px\\]{padding-left:12px}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.\\[font-family\\:cursive\\]{font-family:cursive}.\\[font-family\\:inherit\\]{font-family:inherit}.\\[font-family\\:monospace\\]{font-family:monospace}.\\[font-family\\:var\\(--ds-font-family-code\\)\\],.font-mono{font-family:var(--ds-font-family-code)}.font-sans{font-family:var(--dsw-font-family)}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.text-\\[12px\\]{font-size:12px}.text-\\[13px\\]{font-size:13px}.text-\\[14px\\]{font-size:14px}.text-\\[16px\\]{font-size:16px}.text-\\[18px\\]{font-size:18px}.text-\\[20px\\]{font-size:20px}.text-\\[22px\\]{font-size:22px}.text-\\[24px\\]{font-size:24px}.text-\\[28px\\]{font-size:28px}.leading-\\[1\\.5\\]{--tw-leading:1.5;line-height:1.5}.leading-\\[1\\.55\\]{--tw-leading:1.55;line-height:1.55}.leading-\\[16px\\]{--tw-leading:16px;line-height:16px}.leading-\\[17px\\]{--tw-leading:17px;line-height:17px}.leading-\\[18px\\]{--tw-leading:18px;line-height:18px}.leading-\\[19px\\]{--tw-leading:19px;line-height:19px}.leading-\\[20px\\]{--tw-leading:20px;line-height:20px}.leading-\\[21px\\]{--tw-leading:21px;line-height:21px}.leading-\\[22px\\]{--tw-leading:22px;line-height:22px}.leading-\\[24px\\]{--tw-leading:24px;line-height:24px}.leading-\\[28px\\]{--tw-leading:28px;line-height:28px}.leading-\\[32px\\]{--tw-leading:32px;line-height:32px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[overflow-wrap\\:anywhere\\]{overflow-wrap:anywhere}.break-all{word-break:break-all}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\\[var\\(--dsw-alias-label-caption\\)\\]{color:var(--dsw-alias-label-caption)}.text-\\[var\\(--dsw-alias-label-primary\\)\\]{color:var(--dsw-alias-label-primary)}.text-\\[var\\(--dsw-alias-label-primary-dimmed\\,var\\(--dsw-alias-label-dimmed\\)\\)\\]{color:var(--dsw-alias-label-primary-dimmed,var(--dsw-alias-label-dimmed))}.text-\\[var\\(--dsw-alias-label-secondary\\,var\\(--dsw-alias-label-primary\\)\\)\\]{color:var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary))}.text-\\[var\\(--dsw-alias-state-warning-primary\\,\\#d48806\\)\\]{color:var(--dsw-alias-state-warning-primary,#d48806)}.text-\\[var\\(--dsw-alias-state-warning-primary\\,var\\(--dsw-alias-label-tertiary\\)\\)\\]{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary))}.text-brand{color:var(--dsw-alias-brand-primary)}.text-business{color:var(--dsw-alias-state-business-primary)}.text-dimmed{color:var(--dsw-alias-label-dimmed)}.text-error{color:var(--dsw-alias-state-error-primary)}.text-idle{color:var(--dsw-alias-state-idle-primary)}.text-inherit{color:inherit}.text-primary{color:var(--dsw-alias-label-primary)}.text-primary-fg{color:var(--dsw-alias-label-primary-foreground)}.text-secondary{color:var(--dsw-alias-label-secondary)}.text-success{color:var(--dsw-alias-state-success-primary)}.text-tertiary{color:var(--dsw-alias-label-tertiary)}.text-warn{color:var(--dsw-alias-state-warn-primary)}.lowercase{text-transform:lowercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.decoration-transparent{text-decoration-color:#0000}.underline-offset-\\[2px\\]{text-underline-offset:2px}.accent-\\[var\\(--dsw-alias-button-primary-fill\\)\\]{accent-color:var(--dsw-alias-button-primary-fill)}.accent-brand{accent-color:var(--dsw-alias-brand-primary)}.opacity-0{opacity:0}.opacity-55{opacity:.55}.opacity-60{opacity:.6}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_1px_rgba\\(0\\,0\\,0\\,0\\.12\\)\\]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,#0000001f);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-panel\\)\\]{--tw-shadow:var(--dsw-elevation-panel);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.outline-2{outline-style:var(--tw-outline-style);outline-width:2px}.outline-offset-2{outline-offset:2px}.outline-brand{outline-color:var(--dsw-alias-brand-primary)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\\[text-decoration-color\\]{transition-property:text-decoration-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-\\[120ms\\]{--tw-duration:.12s;transition-duration:.12s}.ease-\\[ease\\]{--tw-ease:ease;transition-timing-function:ease}.outline-none{--tw-outline-style:none;outline-style:none}.\\[--dsh-chat-content-width\\:748px\\]{--dsh-chat-content-width:748px}.\\[--dsh-composer-card-max-width\\:calc\\(var\\(--dsh-chat-content-width\\)_\\+_32px\\)\\]{--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width) + 32px)}.\\[--dsh-composer-side-clearance\\:16px\\]{--dsh-composer-side-clearance:16px}.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:color-mix(in srgb,var(--dsw-alias-state-error-primary)8%,transparent)}}.\\[--dsw-elevation-stroke-color\\:var\\(--dsw-alias-border-l1\\)\\]{--dsw-elevation-stroke-color:var(--dsw-alias-border-l1)}.\\[corner-shape\\:round\\]{corner-shape:round}.\\[transition\\:grid-template-rows_180ms_cubic-bezier\\(\\.16\\,1\\,\\.3\\,1\\)\\,opacity_140ms_ease\\]{transition:grid-template-rows .18s cubic-bezier(.16,1,.3,1),opacity .14s}.\\[transition\\:width_200ms_ease\\]{transition:width .2s}.before\\:pointer-events-none:before{content:var(--tw-content);pointer-events:none}.before\\:absolute:before{content:var(--tw-content);position:absolute}.before\\:inset-0:before{content:var(--tw-content);inset:calc(var(--spacing)*0)}.before\\:z-\\[-1\\]:before{content:var(--tw-content);z-index:-1}.before\\:rounded-\\[inherit\\]:before{content:var(--tw-content);border-radius:inherit}.before\\:bg-\\[var\\(--dsw-specific-menu\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-specific-menu)}.before\\:\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]:before{content:var(--tw-content);-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.before\\:content-\\[\\"\\"\\]:before{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:inset-\\[20\\%\\]:after{content:var(--tw-content);inset:20%}.after\\:inset-\\[25\\%\\]:after{content:var(--tw-content);inset:25%}.after\\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\\:bg-current:after{content:var(--tw-content);background-color:currentColor}.after\\:content-\\[\\"\\"\\]:after,.after\\:content-\\[\\'\\'\\]:after{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:\\[corner-shape\\:round\\]:after{content:var(--tw-content);corner-shape:round}.last\\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}@media (hover:hover){.hover\\:border-border-l4:hover{border-color:var(--dsw-alias-border-l4)}.hover\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:hover{background-color:var(--dsw-alias-bg-layer-4)}.hover\\:bg-hover:hover{background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:text-secondary:hover{color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:bg-\\[var\\(--dsw-alias-button-floating-hover\\)\\]:hover:not(:disabled){background-color:var(--dsw-alias-button-floating-hover)}.hover\\:not-disabled\\:bg-hover:hover:not(:disabled){background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:not-disabled\\:bg-layer-1:hover:not(:disabled){background-color:var(--dsw-alias-bg-layer-1)}.hover\\:not-disabled\\:bg-primary-hover:hover:not(:disabled){background-color:var(--dsw-alias-button-primary-hover)}.hover\\:not-disabled\\:text-primary:hover:not(:disabled){color:var(--dsw-alias-label-primary)}.hover\\:not-disabled\\:text-secondary:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline:hover:not(:disabled){text-decoration-line:underline}.hover\\:not-disabled\\:decoration-current:hover:not(:disabled){text-decoration-color:currentColor}.hover\\:not-disabled\\:decoration-secondary:hover:not(:disabled){-webkit-text-decoration-color:var(--dsw-alias-label-secondary);-webkit-text-decoration-color:var(--dsw-alias-label-secondary);text-decoration-color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline-offset-2:hover:not(:disabled){text-underline-offset:2px}}.focus-visible\\:border-business:focus-visible{border-color:var(--dsw-alias-state-business-primary)}.focus-visible\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:focus-visible{background-color:var(--dsw-alias-bg-layer-4)}.focus-visible\\:text-secondary:focus-visible{color:var(--dsw-alias-label-secondary)}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-state-business-primary))}@supports (color:color-mix(in lab, red, red)){.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,color-mix(in srgb,var(--dsw-alias-state-business-primary)18%,transparent))}}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:shadow-focus-ring:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:\\[outline\\:var\\(--dsw-focus-ring-width\\,2px\\)_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:var(--dsw-focus-ring-width,2px)solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline-offset\\:1px\\]:focus-visible{outline-offset:1px}.focus-visible\\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\\:not-disabled\\:bg-active:active:not(:disabled){background-color:var(--dsw-alias-interactive-bg-active)}.disabled\\:cursor-default:disabled{cursor:default}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:text-\\[var\\(--dsw-alias-label-quaternary\\)\\]:disabled{color:var(--dsw-alias-label-quaternary)}.disabled\\:text-dimmed:disabled{color:var(--dsw-alias-label-dimmed)}.disabled\\:text-tertiary:disabled{color:var(--dsw-alias-label-tertiary)}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:opacity-60:disabled{opacity:.6}.has-\\[\\>input\\:disabled\\]\\:cursor-not-allowed:has(>input:disabled){cursor:not-allowed}.has-\\[\\>input\\:disabled\\]\\:opacity-50:has(>input:disabled){opacity:.5}.aria-expanded\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\][aria-expanded=true]{background-color:var(--dsw-alias-bg-layer-4)}.aria-expanded\\:bg-hover[aria-expanded=true]{background-color:var(--dsw-alias-interactive-bg-hover)}.aria-expanded\\:text-secondary[aria-expanded=true]{color:var(--dsw-alias-label-secondary)}.data-\\[open\\=true\\]\\:rotate-180[data-open=true]{rotate:180deg}.data-\\[status\\=cancelled\\]\\:text-tertiary[data-status=cancelled]{color:var(--dsw-alias-label-tertiary)}.data-\\[status\\=failed\\]\\:text-error[data-status=failed],.data-\\[status\\=interrupted\\]\\:text-error[data-status=interrupted]{color:var(--dsw-alias-state-error-primary)}.data-\\[status\\=queued\\]\\:text-secondary[data-status=queued],.data-\\[status\\=running\\]\\:text-secondary[data-status=running]{color:var(--dsw-alias-label-secondary)}.data-\\[status\\=skipped\\]\\:text-tertiary[data-status=skipped]{color:var(--dsw-alias-label-tertiary)}.data-\\[status\\=succeeded\\]\\:text-success[data-status=succeeded]{color:var(--dsw-alias-state-success-primary)}.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)10%,transparent)}}.data-\\[tone\\=danger\\]\\:text-error[data-tone=danger]{color:var(--dsw-alias-state-error-primary)}.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)10%,transparent)}}.data-\\[tone\\=info\\]\\:text-business[data-tone=info]{color:var(--dsw-alias-state-business-primary)}.data-\\[tone\\=neutral\\]\\:bg-module-platform[data-tone=neutral]{background-color:var(--dsw-alias-bg-module-platform)}.data-\\[tone\\=neutral\\]\\:text-secondary[data-tone=neutral]{color:var(--dsw-alias-label-secondary)}.data-\\[tone\\=outline\\]\\:border-\\[0\\.5px\\][data-tone=outline]{border-style:var(--tw-border-style);border-width:.5px}.data-\\[tone\\=outline\\]\\:border-border-l4[data-tone=outline]{border-color:var(--dsw-alias-border-l4)}.data-\\[tone\\=outline\\]\\:text-tertiary[data-tone=outline]{color:var(--dsw-alias-label-tertiary)}@media not all and (min-width:760px){.max-\\[760px\\]\\:col-span-3{grid-column:span 3/span 3}.max-\\[760px\\]\\:col-span-6{grid-column:span 6/span 6}.max-\\[760px\\]\\:grid-cols-\\[repeat\\(6\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(6,minmax(0,1fr))}}@media not all and (min-width:680px){.max-\\[680px\\]\\:w-\\[140px\\]{width:140px}.max-\\[680px\\]\\:max-w-\\[160px\\]{max-width:160px}.max-\\[680px\\]\\:grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}}@media not all and (min-width:520px){.max-\\[520px\\]\\:col-span-6\\!{grid-column:span 6/span 6!important}}@container not (min-width:460px){.\\@max-\\[460px\\]\\:hidden{display:none}}.\\[\\&_a\\]\\:text-business a{color:var(--dsw-alias-state-business-primary)}.\\[\\&_code\\]\\:rounded-\\[4px\\] code{border-radius:4px}.\\[\\&_code\\]\\:bg-layer-3 code{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_code\\]\\:px-\\[5px\\] code{padding-inline:5px}.\\[\\&_code\\]\\:py-\\[1px\\] code{padding-block:1px}.\\[\\&_code\\]\\:\\[font-family\\:var\\(--ds-font-family-code\\)\\] code{font-family:var(--ds-font-family-code)}.\\[\\&_code\\]\\:text-\\[12px\\] code{font-size:12px}.\\[\\&_h1\\]\\:mt-\\[14px\\] h1{margin-top:14px}.\\[\\&_h1\\]\\:mb-\\[6px\\] h1{margin-bottom:6px}.\\[\\&_h1\\]\\:text-\\[18px\\] h1{font-size:18px}.\\[\\&_h1\\]\\:leading-\\[1\\.4\\] h1{--tw-leading:1.4;line-height:1.4}.\\[\\&_h1\\]\\:text-primary h1{color:var(--dsw-alias-label-primary)}.\\[\\&_h2\\]\\:mt-\\[14px\\] h2{margin-top:14px}.\\[\\&_h2\\]\\:mb-\\[6px\\] h2{margin-bottom:6px}.\\[\\&_h2\\]\\:text-\\[16px\\] h2{font-size:16px}.\\[\\&_h2\\]\\:leading-\\[1\\.4\\] h2{--tw-leading:1.4;line-height:1.4}.\\[\\&_h2\\]\\:text-primary h2{color:var(--dsw-alias-label-primary)}.\\[\\&_h3\\]\\:m-0 h3{margin:calc(var(--spacing)*0)}.\\[\\&_h3\\]\\:mt-\\[14px\\] h3{margin-top:14px}.\\[\\&_h3\\]\\:mb-\\[6px\\] h3{margin-bottom:6px}.\\[\\&_h3\\]\\:text-\\[13px\\] h3{font-size:13px}.\\[\\&_h3\\]\\:text-\\[14px\\] h3{font-size:14px}.\\[\\&_h3\\]\\:text-\\[16px\\] h3{font-size:16px}.\\[\\&_h3\\]\\:leading-\\[1\\.4\\] h3{--tw-leading:1.4;line-height:1.4}.\\[\\&_h3\\]\\:leading-\\[20px\\] h3{--tw-leading:20px;line-height:20px}.\\[\\&_h3\\]\\:leading-\\[24px\\] h3{--tw-leading:24px;line-height:24px}.\\[\\&_h3\\]\\:font-medium h3{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\\[\\&_h3\\]\\:font-semibold h3{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[\\&_h3\\]\\:text-primary h3{color:var(--dsw-alias-label-primary)}.\\[\\&_h4\\]\\:mt-\\[14px\\] h4{margin-top:14px}.\\[\\&_h4\\]\\:mb-\\[6px\\] h4{margin-bottom:6px}.\\[\\&_h4\\]\\:text-\\[13px\\] h4{font-size:13px}.\\[\\&_h4\\]\\:leading-\\[1\\.4\\] h4{--tw-leading:1.4;line-height:1.4}.\\[\\&_h4\\]\\:text-primary h4{color:var(--dsw-alias-label-primary)}.\\[\\&_input\\]\\:m-0 input{margin:calc(var(--spacing)*0)}.\\[\\&_input\\]\\:h-\\[12px\\] input{height:12px}.\\[\\&_input\\]\\:w-\\[12px\\] input{width:12px}.\\[\\&_input\\]\\:accent-brand input{accent-color:var(--dsw-alias-brand-primary)}.\\[\\&_input\\:focus-visible\\]\\:shadow-focus-ring input:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.\\[\\&_ol\\]\\:my-\\[6px\\] ol{margin-block:6px}.\\[\\&_ol\\]\\:pl-\\[20px\\] ol{padding-left:20px}.\\[\\&_p\\]\\:m-0 p{margin:calc(var(--spacing)*0)}.\\[\\&_p\\]\\:my-\\[6px\\] p{margin-block:6px}.\\[\\&_p\\]\\:leading-\\[20px\\] p{--tw-leading:20px;line-height:20px}.\\[\\&_pre\\]\\:my-\\[8px\\] pre{margin-block:8px}.\\[\\&_pre\\]\\:overflow-x-auto pre{overflow-x:auto}.\\[\\&_pre\\]\\:rounded-\\[8px\\] pre{border-radius:8px}.\\[\\&_pre\\]\\:border pre{border-style:var(--tw-border-style);border-width:1px}.\\[\\&_pre\\]\\:border-border-l2 pre{border-color:var(--dsw-alias-border-l2)}.\\[\\&_pre\\]\\:bg-layer-3 pre{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_pre\\]\\:px-\\[12px\\] pre{padding-inline:12px}.\\[\\&_pre\\]\\:py-\\[10px\\] pre{padding-block:10px}.\\[\\&_svg\\]\\:h-\\[11px\\] svg{height:11px}.\\[\\&_svg\\]\\:h-\\[14px\\] svg{height:14px}.\\[\\&_svg\\]\\:w-\\[11px\\] svg{width:11px}.\\[\\&_svg\\]\\:w-\\[14px\\] svg{width:14px}.\\[\\&_ul\\]\\:my-\\[6px\\] ul{margin-block:6px}.\\[\\&_ul\\]\\:pl-\\[20px\\] ul{padding-left:20px}.\\[\\&\\+\\&\\]\\:border-t+.\\[\\&\\+\\&\\]\\:border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.\\[\\&\\+\\&\\]\\:border-border-weak+.\\[\\&\\+\\&\\]\\:border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.\\[\\&\\+\\&\\]\\:border-t-border-l2+.\\[\\&\\+\\&\\]\\:border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:cursor-default:has(input:disabled){cursor:default}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:opacity-60:has(input:disabled){opacity:.6}.\\[\\&\\>\\*\\]\\:w-full>*{width:100%}.\\[\\&\\>\\*\\]\\:max-w-\\[960px\\]>*{max-width:960px}.\\[\\&\\>img\\]\\:absolute>img{position:absolute}.\\[\\&\\>img\\]\\:top-0>img{top:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:left-0>img{left:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:block>img{display:block}.\\[\\&\\>img\\]\\:h-\\[1100\\%\\]>img{height:1100%}.\\[\\&\\>img\\]\\:h-full>img{height:100%}.\\[\\&\\>img\\]\\:w-\\[800\\%\\]>img{width:800%}.\\[\\&\\>img\\]\\:w-full>img{width:100%}.\\[\\&\\>img\\]\\:max-w-none>img{max-width:none}.\\[\\&\\>img\\]\\:object-fill>img{object-fit:fill}.\\[\\&\\>span\\:first-child\\]\\:text-tertiary>span:first-child{color:var(--dsw-alias-label-tertiary)}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}+@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-border-style:solid;--tw-leading:initial;--tw-font-weight:initial;--tw-ordinal:initial;--tw-slashed-zero:initial;--tw-numeric-figure:initial;--tw-numeric-spacing:initial;--tw-numeric-fraction:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:""}}}@layer theme{:root,:host{--color-white:#fff;--spacing:.25rem;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1)}}@layer base,components;@layer utilities{.collapse{visibility:collapse}.visible{visibility:visible}.sr-only{clip:rect(0,0,0,0);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.fixed{position:fixed}.relative{position:relative}.static{position:static}.sticky{position:sticky}.inset-0{inset:calc(var(--spacing)*0)}.top-0{top:calc(var(--spacing)*0)}.top-1\\/2{top:50%}.right-\\[8px\\]{right:8px}.isolate{isolation:isolate}.z-30{z-index:30}.z-\\[1\\]{z-index:1}.z-\\[2\\]{z-index:2}.z-\\[1000\\]{z-index:1000}.z-\\[1100\\]{z-index:1100}.order-\\[1\\]{order:1}.order-\\[3\\]{order:3}.col-span-3{grid-column:span 3/span 3}.col-span-4{grid-column:span 4/span 4}.col-span-5{grid-column:span 5/span 5}.col-span-6{grid-column:span 6/span 6}.col-span-8{grid-column:span 8/span 8}.col-span-12{grid-column:span 12/span 12}.col-span-full{grid-column:1/-1}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:calc(var(--spacing)*0)}.m-1{margin:calc(var(--spacing)*1)}.m-2{margin:calc(var(--spacing)*2)}.-mx-\\[2px\\]{margin-inline:-2px}.mx-0{margin-inline:calc(var(--spacing)*0)}.mx-\\[-8px\\]{margin-inline:-8px}.mx-\\[4px\\]{margin-inline:4px}.mx-auto{margin-inline:auto}.my-0{margin-block:calc(var(--spacing)*0)}.my-\\[4px\\]{margin-block:4px}.my-\\[6px\\]{margin-block:6px}.my-\\[8px\\]{margin-block:8px}.mt-0{margin-top:calc(var(--spacing)*0)}.mt-\\[2px\\]{margin-top:2px}.mt-\\[4px\\]{margin-top:4px}.mt-\\[6px\\]{margin-top:6px}.mt-\\[8px\\]{margin-top:8px}.mt-\\[12px\\]{margin-top:12px}.mt-\\[20px\\]{margin-top:20px}.mt-\\[28px\\]{margin-top:28px}.mr-0{margin-right:calc(var(--spacing)*0)}.mr-\\[-8px\\]{margin-right:-8px}.mr-\\[calc\\(6px-var\\(--detail-gutter\\)\\)\\]{margin-right:calc(6px - var(--detail-gutter))}.mr-auto{margin-right:auto}.mb-0{margin-bottom:calc(var(--spacing)*0)}.mb-\\[-1px\\]{margin-bottom:-1px}.mb-\\[4px\\]{margin-bottom:4px}.mb-\\[8px\\]{margin-bottom:8px}.mb-\\[10px\\]{margin-bottom:10px}.mb-\\[12px\\]{margin-bottom:12px}.mb-\\[16px\\]{margin-bottom:16px}.mb-\\[20px\\]{margin-bottom:20px}.-ml-1{margin-left:calc(var(--spacing)*-1)}.ml-\\[-6px\\]{margin-left:-6px}.ml-\\[4px\\]{margin-left:4px}.ml-\\[8px\\]{margin-left:8px}.ml-\\[10px\\]{margin-left:10px}.ml-auto{margin-left:auto}.box-border{box-sizing:border-box}.line-clamp-1{-webkit-line-clamp:1;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-2{-webkit-line-clamp:2;-webkit-box-orient:vertical;display:-webkit-box;overflow:hidden}.line-clamp-none{-webkit-line-clamp:unset;-webkit-box-orient:horizontal;display:block;overflow:visible}.block{display:block}.block\\!{display:block!important}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.inline-flex{display:inline-flex}.table{display:table}.\\[field-sizing\\:content\\]{field-sizing:content}.h-\\[0\\.5px\\]{height:.5px}.h-\\[4px\\]{height:4px}.h-\\[8px\\]{height:8px}.h-\\[10px\\]{height:10px}.h-\\[12px\\]{height:12px}.h-\\[14px\\]{height:14px}.h-\\[16px\\]{height:16px}.h-\\[18px\\]{height:18px}.h-\\[20px\\]{height:20px}.h-\\[22px\\]{height:22px}.h-\\[24px\\]{height:24px}.h-\\[26px\\]{height:26px}.h-\\[28px\\]{height:28px}.h-\\[32px\\]{height:32px}.h-\\[36px\\]{height:36px}.h-\\[37px\\]{height:37px}.h-\\[38px\\]{height:38px}.h-\\[40px\\]{height:40px}.h-\\[42px\\]{height:42px}.h-\\[44px\\]{height:44px}.h-\\[48px\\]{height:48px}.h-\\[56px\\]{height:56px}.h-\\[60px\\]{height:60px}.h-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{height:calc(28px + var(--dsh-content-font-delta,0px))}.h-auto{height:auto}.h-full{height:100%}.max-h-\\[60vh\\]{max-height:60vh}.max-h-\\[160px\\]{max-height:160px}.max-h-\\[180px\\]{max-height:180px}.max-h-\\[216px\\]{max-height:216px}.max-h-\\[calc\\(100vh-160px\\)\\]\\!{max-height:calc(100vh - 160px)!important}.max-h-\\[min\\(400px\\,52vh\\)\\]{max-height:min(400px,52vh)}.max-h-\\[min\\(420px\\,calc\\(100dvh-48px\\)\\)\\]{max-height:min(420px,100dvh - 48px)}.min-h-0{min-height:calc(var(--spacing)*0)}.min-h-\\[20px\\]{min-height:20px}.min-h-\\[28px\\]{min-height:28px}.min-h-\\[32px\\]{min-height:32px}.min-h-\\[37px\\]{min-height:37px}.min-h-\\[44px\\]{min-height:44px}.min-h-\\[48px\\]{min-height:48px}.min-h-\\[64px\\]{min-height:64px}.min-h-\\[96px\\]{min-height:96px}.min-h-\\[112px\\]{min-height:112px}.min-h-\\[240px\\]{min-height:240px}.min-h-\\[260px\\]{min-height:260px}.min-h-\\[320px\\]{min-height:320px}.min-h-full{min-height:100%}.w-\\[8px\\]{width:8px}.w-\\[10px\\]{width:10px}.w-\\[12px\\]{width:12px}.w-\\[14px\\]{width:14px}.w-\\[16px\\]{width:16px}.w-\\[20px\\]{width:20px}.w-\\[22px\\]{width:22px}.w-\\[24px\\]{width:24px}.w-\\[26px\\]{width:26px}.w-\\[28px\\]{width:28px}.w-\\[32px\\]{width:32px}.w-\\[36px\\]{width:36px}.w-\\[44px\\]{width:44px}.w-\\[48px\\]{width:48px}.w-\\[52px\\]{width:52px}.w-\\[56px\\]{width:56px}.w-\\[200px\\]{width:200px}.w-\\[232px\\]{width:232px}.w-\\[336px\\]{width:336px}.w-\\[360px\\]{width:360px}.w-\\[calc\\(28px\\+var\\(--dsh-content-font-delta\\,0px\\)\\)\\]{width:calc(28px + var(--dsh-content-font-delta,0px))}.w-\\[calc\\(100\\%\\+4px\\)\\]{width:calc(100% + 4px)}.w-\\[calc\\(100\\%_-_2_\\*_var\\(--dsh-composer-side-clearance\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{width:calc(100% - 2*var(--dsh-composer-side-clearance) - 4*var(--dsh-composer-dock-inset))}.w-\\[min\\(680px\\,100\\%\\)\\]\\!{width:min(680px,100%)!important}.w-\\[min\\(760px\\,100\\%\\)\\]\\!{width:min(760px,100%)!important}.w-\\[min\\(calc\\(var\\(--dsh-composer-card-max-width\\)_\\+_2_\\*_var\\(--dsh-composer-side-clearance\\)\\)\\,100\\%\\)\\]{width:min(calc(var(--dsh-composer-card-max-width) + 2*var(--dsh-composer-side-clearance)),100%)}.w-\\[var\\(--dsh-settings-rail-width\\)\\]{width:var(--dsh-settings-rail-width)}.w-full{width:100%}.w-full\\!{width:100%!important}.max-w-\\[40\\%\\]{max-width:40%}.max-w-\\[200px\\]{max-width:200px}.max-w-\\[220px\\]{max-width:220px}.max-w-\\[280px\\]{max-width:280px}.max-w-\\[460px\\]{max-width:460px}.max-w-\\[520px\\]{max-width:520px}.max-w-\\[960px\\]{max-width:960px}.max-w-\\[calc\\(100vw-32px\\)\\]{max-width:calc(100vw - 32px)}.max-w-\\[calc\\(var\\(--dsh-composer-card-max-width\\)_-_4_\\*_var\\(--dsh-composer-dock-inset\\)\\)\\]{max-width:calc(var(--dsh-composer-card-max-width) - 4*var(--dsh-composer-dock-inset))}.max-w-\\[min\\(100\\%\\,240px\\)\\]{max-width:min(100%,240px)}.max-w-\\[min\\(100\\%\\,360px\\)\\]{max-width:min(100%,360px)}.max-w-full{max-width:100%}.min-w-0{min-width:calc(var(--spacing)*0)}.min-w-\\[72px\\]{min-width:72px}.min-w-\\[220px\\]{min-width:220px}.flex-1{flex:1}.flex-\\[0_0_47\\%\\]{flex:0 0 47%}.flex-\\[0_1_58\\%\\]{flex:0 58%}.flex-\\[0_1_280px\\]{flex:0 280px}.flex-\\[0_1_auto\\]{flex:0 auto}.flex-\\[1_1_100\\%\\]{flex:100%}.flex-\\[1_1_220px\\]{flex:220px}.flex-\\[1_1_auto\\],.flex-auto{flex:auto}.flex-none{flex:none}.shrink-0{flex-shrink:0}.-translate-y-1\\/2{--tw-translate-y:calc(calc(1/2*100%)*-1);translate:var(--tw-translate-x)var(--tw-translate-y)}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.cursor-\\[inherit\\]{cursor:inherit}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.touch-none{touch-action:none}.resize{resize:both}.resize-none{resize:none}.resize-y{resize:vertical}.list-none{list-style-type:none}.grid-cols-7{grid-template-columns:repeat(7,minmax(0,1fr))}.grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}.grid-cols-\\[repeat\\(2\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-\\[repeat\\(12\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(12,minmax(0,1fr))}.grid-rows-\\[0fr\\]{grid-template-rows:0fr}.grid-rows-\\[1fr\\]{grid-template-rows:1fr}.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.items-start{align-items:flex-start}.items-stretch{align-items:stretch}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}.gap-0{gap:calc(var(--spacing)*0)}.gap-8{gap:calc(var(--spacing)*8)}.gap-\\[1px\\]{gap:1px}.gap-\\[2px\\]{gap:2px}.gap-\\[4px\\]{gap:4px}.gap-\\[5px\\]{gap:5px}.gap-\\[6px\\]{gap:6px}.gap-\\[7px\\]{gap:7px}.gap-\\[8px\\]{gap:8px}.gap-\\[10px\\]{gap:10px}.gap-\\[10px_12px\\]{gap:10px 12px}.gap-\\[12px\\]{gap:12px}.gap-\\[14px\\]{gap:14px}.gap-\\[16px\\]{gap:16px}.gap-\\[20px\\]{gap:20px}.gap-\\[24px\\]{gap:24px}.gap-\\[36px\\]{gap:36px}.self-center{align-self:center}.self-end{align-self:flex-end}.self-start{align-self:flex-start}.self-stretch{align-self:stretch}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overscroll-contain{overscroll-behavior:contain}.rounded{border-radius:.25rem}.rounded-\\[2px\\]{border-radius:2px}.rounded-\\[3px\\]{border-radius:3px}.rounded-\\[4px\\]{border-radius:4px}.rounded-\\[6px\\]{border-radius:6px}.rounded-\\[7px\\]{border-radius:7px}.rounded-\\[8px\\]{border-radius:8px}.rounded-\\[10px\\]{border-radius:10px}.rounded-\\[12px\\]{border-radius:12px}.rounded-\\[13px\\]{border-radius:13px}.rounded-\\[14px\\]{border-radius:14px}.rounded-\\[16px\\]{border-radius:16px}.rounded-\\[18px\\]{border-radius:18px}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--dsw-radius-lg)}.rounded-md{border-radius:var(--dsw-radius-md)}.rounded-sm{border-radius:var(--dsw-radius-sm)}.rounded-xl{border-radius:var(--dsw-radius-xl)}.rounded-xs{border-radius:var(--dsw-radius-xs)}.rounded-tl-\\[16px\\]{border-top-left-radius:16px}.border{border-style:var(--tw-border-style);border-width:1px}.border-0{border-style:var(--tw-border-style);border-width:0}.border-\\[0\\.5px\\]{border-style:var(--tw-border-style);border-width:.5px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-t-\\[0\\.5px\\]{border-top-style:var(--tw-border-style);border-top-width:.5px}.border-b-\\[0\\.5px\\]{border-bottom-style:var(--tw-border-style);border-bottom-width:.5px}.border-l-2{border-left-style:var(--tw-border-style);border-left-width:2px}.border-l-\\[0\\.5px\\]{border-left-style:var(--tw-border-style);border-left-width:.5px}.border-dashed{--tw-border-style:dashed;border-style:dashed}.border-none{--tw-border-style:none;border-style:none}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_35\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_30\\%\\,transparent\\)\\]{border-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)30%,transparent)}}.border-\\[color\\:var\\(--dsw-alias-line-secondary\\,currentColor\\)\\]{border-color:var(--dsw-alias-line-secondary,currentColor)}.border-border-l2{border-color:var(--dsw-alias-border-l2)}.border-border-l3{border-color:var(--dsw-alias-border-l3)}.border-border-l4{border-color:var(--dsw-alias-border-l4)}.border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.border-brand{border-color:var(--dsw-alias-brand-primary)}.border-business\\/35{border-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.border-business\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)35%,transparent)}}.border-current{border-color:currentColor}.border-error\\/35{border-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.border-error\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)35%,transparent)}}.border-success\\/35{border-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.border-success\\/35{border-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)35%,transparent)}}.border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.border-l-transparent{border-left-color:#0000}.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_8\\%\\,transparent\\)\\]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-\\[color\\:var\\(--swatch-color\\)\\]{background-color:var(--swatch-color)}.bg-\\[var\\(--dsw-alias-bg-base\\)\\]{background-color:var(--dsw-alias-bg-base)}.bg-\\[var\\(--dsw-alias-bg-base\\,var\\(--dsw-alias-bg-module-platform\\)\\)\\]{background-color:var(--dsw-alias-bg-base,var(--dsw-alias-bg-module-platform))}.bg-\\[var\\(--dsw-alias-border-l3\\)\\]{background-color:var(--dsw-alias-border-l3)}.bg-\\[var\\(--dsw-alias-button-elevated-fill\\)\\]{background-color:var(--dsw-alias-button-elevated-fill)}.bg-\\[var\\(--dsw-alias-surface-tinted\\)\\]{background-color:var(--dsw-alias-surface-tinted)}.bg-\\[var\\(--dsw-specific-menu\\)\\]{background-color:var(--dsw-specific-menu)}.bg-\\[var\\(--dsw-specific-sidebar-fill\\)\\]{background-color:var(--dsw-specific-sidebar-fill)}.bg-\\[var\\(--dsw-specific-sidebar-nav-item-active\\)\\]{background-color:var(--dsw-specific-sidebar-nav-item-active)}.bg-border-l2{background-color:var(--dsw-alias-border-l2)}.bg-brand{background-color:var(--dsw-alias-brand-primary)}.bg-business\\/8{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.bg-business\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-business-primary)8%,transparent)}}.bg-current{background-color:currentColor}.bg-error\\/8{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.bg-error\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-error-primary)8%,transparent)}}.bg-hover{background-color:var(--dsw-alias-interactive-bg-hover)}.bg-layer-1{background-color:var(--dsw-alias-bg-layer-1)}.bg-layer-3{background-color:var(--dsw-alias-bg-layer-3)}.bg-module-platform{background-color:var(--dsw-alias-bg-module-platform)}.bg-primary-fill{background-color:var(--dsw-alias-button-primary-fill)}.bg-success\\/8{background-color:var(--dsw-alias-state-success-primary)}@supports (color:color-mix(in lab, red, red)){.bg-success\\/8{background-color:color-mix(in oklab,var(--dsw-alias-state-success-primary)8%,transparent)}}.bg-transparent{background-color:#0000}.bg-\\[image\\:linear-gradient\\(to_top_right\\,transparent_calc\\(50\\%_-_1px\\)\\,var\\(--dsw-alias-label-tertiary\\)\\,transparent_calc\\(50\\%_\\+_1px\\)\\)\\]{background-image:linear-gradient(to top right,transparent calc(50% - 1px),var(--dsw-alias-label-tertiary),transparent calc(50% + 1px))}.object-cover{object-fit:cover}.p-0{padding:calc(var(--spacing)*0)}.p-1{padding:calc(var(--spacing)*1)}.p-2{padding:calc(var(--spacing)*2)}.p-\\[2px\\]{padding:2px}.p-\\[3px\\]{padding:3px}.p-\\[6px\\]{padding:6px}.p-\\[8px\\]{padding:8px}.p-\\[10px\\]{padding:10px}.p-\\[12px\\]{padding:12px}.p-\\[24px\\]{padding:24px}.px-0{padding-inline:calc(var(--spacing)*0)}.px-\\[2px\\]{padding-inline:2px}.px-\\[4px\\]{padding-inline:4px}.px-\\[6px\\]{padding-inline:6px}.px-\\[7px\\]{padding-inline:7px}.px-\\[8px\\]{padding-inline:8px}.px-\\[10px\\]{padding-inline:10px}.px-\\[12px\\]{padding-inline:12px}.px-\\[14px\\]{padding-inline:14px}.px-\\[16px\\]{padding-inline:16px}.px-\\[24px\\]{padding-inline:24px}.px-\\[36px\\]{padding-inline:36px}.px-\\[clamp\\(24px\\,4vw\\,48px\\)\\]{padding-inline:clamp(24px,4vw,48px)}.px-\\[var\\(--detail-gutter\\)\\]{padding-inline:var(--detail-gutter)}.py-\\[1px\\]{padding-block:1px}.py-\\[2px\\]{padding-block:2px}.py-\\[4px\\]{padding-block:4px}.py-\\[5px\\]{padding-block:5px}.py-\\[6px\\]{padding-block:6px}.py-\\[7px\\]{padding-block:7px}.py-\\[8px\\]{padding-block:8px}.py-\\[9px\\]{padding-block:9px}.py-\\[10px\\]{padding-block:10px}.py-\\[12px\\]{padding-block:12px}.py-\\[14px\\]{padding-block:14px}.py-\\[16px\\]{padding-block:16px}.py-\\[20px\\]{padding-block:20px}.py-\\[24px\\]{padding-block:24px}.py-\\[28px\\]{padding-block:28px}.py-\\[32px\\]{padding-block:32px}.py-\\[40px\\]{padding-block:40px}.py-\\[48px\\]{padding-block:48px}.py-px{padding-block:1px}.pt-0{padding-top:calc(var(--spacing)*0)}.pt-\\[2px\\]{padding-top:2px}.pt-\\[12px\\]{padding-top:12px}.pt-\\[24px\\]{padding-top:24px}.pt-\\[28px\\]{padding-top:28px}.pr-\\[4px\\]{padding-right:4px}.pr-\\[5px\\]{padding-right:5px}.pr-\\[6px\\]{padding-right:6px}.pr-\\[10px\\]{padding-right:10px}.pb-\\[4px\\]{padding-bottom:4px}.pb-\\[6px\\]{padding-bottom:6px}.pb-\\[9px\\]{padding-bottom:9px}.pb-\\[16px\\]{padding-bottom:16px}.pb-\\[28px\\]{padding-bottom:28px}.pb-\\[48px\\]{padding-bottom:48px}.pb-px{padding-bottom:1px}.pl-\\[2px\\]{padding-left:2px}.pl-\\[8px\\]{padding-left:8px}.pl-\\[12px\\]{padding-left:12px}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.align-middle{vertical-align:middle}.\\[font-family\\:cursive\\]{font-family:cursive}.\\[font-family\\:inherit\\]{font-family:inherit}.\\[font-family\\:monospace\\]{font-family:monospace}.\\[font-family\\:var\\(--ds-font-family-code\\)\\],.font-mono{font-family:var(--ds-font-family-code)}.font-sans{font-family:var(--dsw-font-family)}.text-\\[10px\\]{font-size:10px}.text-\\[11px\\]{font-size:11px}.text-\\[12px\\]{font-size:12px}.text-\\[13px\\]{font-size:13px}.text-\\[14px\\]{font-size:14px}.text-\\[16px\\]{font-size:16px}.text-\\[18px\\]{font-size:18px}.text-\\[20px\\]{font-size:20px}.text-\\[22px\\]{font-size:22px}.text-\\[24px\\]{font-size:24px}.text-\\[28px\\]{font-size:28px}.leading-\\[1\\.5\\]{--tw-leading:1.5;line-height:1.5}.leading-\\[1\\.6\\]{--tw-leading:1.6;line-height:1.6}.leading-\\[15px\\]{--tw-leading:15px;line-height:15px}.leading-\\[16px\\]{--tw-leading:16px;line-height:16px}.leading-\\[17px\\]{--tw-leading:17px;line-height:17px}.leading-\\[18px\\]{--tw-leading:18px;line-height:18px}.leading-\\[19px\\]{--tw-leading:19px;line-height:19px}.leading-\\[20px\\]{--tw-leading:20px;line-height:20px}.leading-\\[21px\\]{--tw-leading:21px;line-height:21px}.leading-\\[22px\\]{--tw-leading:22px;line-height:22px}.leading-\\[24px\\]{--tw-leading:24px;line-height:24px}.leading-\\[28px\\]{--tw-leading:28px;line-height:28px}.leading-\\[32px\\]{--tw-leading:32px;line-height:32px}.leading-none{--tw-leading:1;line-height:1}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[overflow-wrap\\:anywhere\\]{overflow-wrap:anywhere}.break-words{overflow-wrap:break-word}.wrap-anywhere{overflow-wrap:anywhere}.break-all{word-break:break-all}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-\\[\\#ADB2B8\\]{color:#adb2b8}.text-\\[\\#CFD3D6\\]{color:#cfd3d6}.text-\\[var\\(--dsw-alias-label-caption\\)\\]{color:var(--dsw-alias-label-caption)}.text-\\[var\\(--dsw-alias-label-primary\\)\\]{color:var(--dsw-alias-label-primary)}.text-\\[var\\(--dsw-alias-label-primary-dimmed\\,var\\(--dsw-alias-label-dimmed\\)\\)\\]{color:var(--dsw-alias-label-primary-dimmed,var(--dsw-alias-label-dimmed))}.text-\\[var\\(--dsw-alias-label-secondary\\,var\\(--dsw-alias-label-primary\\)\\)\\]{color:var(--dsw-alias-label-secondary,var(--dsw-alias-label-primary))}.text-\\[var\\(--dsw-alias-state-warning-primary\\,\\#d48806\\)\\]{color:var(--dsw-alias-state-warning-primary,#d48806)}.text-\\[var\\(--dsw-alias-state-warning-primary\\,var\\(--dsw-alias-label-tertiary\\)\\)\\]{color:var(--dsw-alias-state-warning-primary,var(--dsw-alias-label-tertiary))}.text-brand{color:var(--dsw-alias-brand-primary)}.text-business{color:var(--dsw-alias-state-business-primary)}.text-dimmed{color:var(--dsw-alias-label-dimmed)}.text-error{color:var(--dsw-alias-state-error-primary)}.text-idle{color:var(--dsw-alias-state-idle-primary)}.text-inherit{color:inherit}.text-primary{color:var(--dsw-alias-label-primary)}.text-primary-fg{color:var(--dsw-alias-label-primary-foreground)}.text-secondary{color:var(--dsw-alias-label-secondary)}.text-success{color:var(--dsw-alias-state-success-primary)}.text-tertiary{color:var(--dsw-alias-label-tertiary)}.text-warn{color:var(--dsw-alias-state-warn-primary)}.text-white{color:var(--color-white)}.lowercase{text-transform:lowercase}.tabular-nums{--tw-numeric-spacing:tabular-nums;font-variant-numeric:var(--tw-ordinal,)var(--tw-slashed-zero,)var(--tw-numeric-figure,)var(--tw-numeric-spacing,)var(--tw-numeric-fraction,)}.no-underline{text-decoration-line:none}.underline{text-decoration-line:underline}.decoration-transparent{text-decoration-color:#0000}.underline-offset-\\[2px\\]{text-underline-offset:2px}.accent-\\[var\\(--dsw-alias-button-primary-fill\\)\\]{accent-color:var(--dsw-alias-button-primary-fill)}.accent-brand{accent-color:var(--dsw-alias-brand-primary)}.opacity-0{opacity:0}.opacity-55{opacity:.55}.opacity-60{opacity:.6}.opacity-100{opacity:1}.shadow{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a),0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[inset_0_0_0_1px_rgba\\(0\\,0\\,0\\,0\\.12\\)\\]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,#0000001f);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-panel\\)\\]{--tw-shadow:var(--dsw-elevation-panel);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.shadow-\\[var\\(--dsw-elevation-prominent\\)\\]{--tw-shadow:var(--dsw-elevation-prominent);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.outline{outline-style:var(--tw-outline-style);outline-width:1px}.outline-2{outline-style:var(--tw-outline-style);outline-width:2px}.outline-offset-2{outline-offset:2px}.outline-brand{outline-color:var(--dsw-alias-brand-primary)}.blur{--tw-blur:blur(8px);filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.filter{filter:var(--tw-blur,)var(--tw-brightness,)var(--tw-contrast,)var(--tw-grayscale,)var(--tw-hue-rotate,)var(--tw-invert,)var(--tw-saturate,)var(--tw-sepia,)var(--tw-drop-shadow,)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]{-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,visibility,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-\\[text-decoration-color\\]{transition-property:text-decoration-color;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-150{--tw-duration:.15s;transition-duration:.15s}.duration-\\[120ms\\]{--tw-duration:.12s;transition-duration:.12s}.ease-\\[ease\\]{--tw-ease:ease;transition-timing-function:ease}.outline-none{--tw-outline-style:none;outline-style:none}.\\[--detail-gutter\\:24px\\]{--detail-gutter:24px}.\\[--dsh-chat-content-width\\:748px\\]{--dsh-chat-content-width:748px}.\\[--dsh-composer-card-max-width\\:calc\\(var\\(--dsh-chat-content-width\\)_\\+_32px\\)\\]{--dsh-composer-card-max-width:calc(var(--dsh-chat-content-width) + 32px)}.\\[--dsh-composer-side-clearance\\:16px\\]{--dsh-composer-side-clearance:16px}.\\[--dsh-scrollbar-thumb-border\\:2px\\]{--dsh-scrollbar-thumb-border:2px}.\\[--dsh-scrollbar-thumb-hover\\:var\\(--dsw-alias-scrollbar-hover-l2\\)\\]{--dsh-scrollbar-thumb-hover:var(--dsw-alias-scrollbar-hover-l2)}.\\[--dsh-scrollbar-thumb\\:var\\(--dsw-alias-scrollbar-bg-l2\\)\\]{--dsh-scrollbar-thumb:var(--dsw-alias-scrollbar-bg-l2)}.\\[--dsh-scrollbar-track-margin\\:12px\\]{--dsh-scrollbar-track-margin:12px}.\\[--dsh-scrollbar-width\\:9px\\]{--dsh-scrollbar-width:9px}.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.\\[--dsw-alias-interactive-bg-hover\\:color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_8\\%\\,transparent\\)\\]{--dsw-alias-interactive-bg-hover:color-mix(in srgb,var(--dsw-alias-state-error-primary)8%,transparent)}}.\\[--dsw-elevation-stroke-color\\:var\\(--dsw-alias-border-l1\\)\\]{--dsw-elevation-stroke-color:var(--dsw-alias-border-l1)}.\\[corner-shape\\:round\\]{corner-shape:round}.\\[scrollbar-gutter\\:stable\\]{scrollbar-gutter:stable}.\\[scrollbar-width\\:none\\]{scrollbar-width:none}.\\[transition\\:grid-template-rows_180ms_cubic-bezier\\(\\.16\\,1\\,\\.3\\,1\\)\\,opacity_140ms_ease\\]{transition:grid-template-rows .18s cubic-bezier(.16,1,.3,1),opacity .14s}.\\[transition\\:width_200ms_ease\\]{transition:width .2s}.before\\:pointer-events-none:before{content:var(--tw-content);pointer-events:none}.before\\:absolute:before{content:var(--tw-content);position:absolute}.before\\:inset-0:before{content:var(--tw-content);inset:calc(var(--spacing)*0)}.before\\:top-0:before{content:var(--tw-content);top:calc(var(--spacing)*0)}.before\\:left-\\[15\\.75px\\]:before{content:var(--tw-content);left:15.75px}.before\\:z-\\[-1\\]:before{content:var(--tw-content);z-index:-1}.before\\:h-\\[14px\\]:before{content:var(--tw-content);height:14px}.before\\:w-\\[0\\.5px\\]:before{content:var(--tw-content);width:.5px}.before\\:rounded-\\[inherit\\]:before{content:var(--tw-content);border-radius:inherit}.before\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.before\\:bg-\\[var\\(--dsw-specific-menu\\)\\]:before{content:var(--tw-content);background-color:var(--dsw-specific-menu)}.before\\:\\[backdrop-filter\\:var\\(--dsw-menu-backdrop-filter\\)\\]:before{content:var(--tw-content);-webkit-backdrop-filter:var(--dsw-menu-backdrop-filter);backdrop-filter:var(--dsw-menu-backdrop-filter)}.before\\:content-\\[\\"\\"\\]:before,.before\\:content-\\[\\'\\'\\]:before{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:absolute:after{content:var(--tw-content);position:absolute}.after\\:inset-\\[20\\%\\]:after{content:var(--tw-content);inset:20%}.after\\:inset-\\[25\\%\\]:after{content:var(--tw-content);inset:25%}.after\\:inset-x-0:after{content:var(--tw-content);inset-inline:calc(var(--spacing)*0)}.after\\:top-\\[42px\\]:after{content:var(--tw-content);top:42px}.after\\:bottom-0:after{content:var(--tw-content);bottom:calc(var(--spacing)*0)}.after\\:bottom-\\[-1px\\]:after{content:var(--tw-content);bottom:-1px}.after\\:left-\\[15\\.75px\\]:after{content:var(--tw-content);left:15.75px}.after\\:h-\\[2px\\]:after{content:var(--tw-content);height:2px}.after\\:w-\\[0\\.5px\\]:after{content:var(--tw-content);width:.5px}.after\\:rounded-\\[2px\\]:after{content:var(--tw-content);border-radius:2px}.after\\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\\:bg-\\[var\\(--dsw-alias-border-l3\\)\\]:after{content:var(--tw-content);background-color:var(--dsw-alias-border-l3)}.after\\:bg-business:after{content:var(--tw-content);background-color:var(--dsw-alias-state-business-primary)}.after\\:bg-current:after{content:var(--tw-content);background-color:currentColor}.after\\:content-\\[\\"\\"\\]:after,.after\\:content-\\[\\'\\'\\]:after{content:var(--tw-content);--tw-content:"";content:var(--tw-content)}.after\\:content-\\[\\\\\\'\\\\\\'\\]:after{content:var(--tw-content);--tw-content:\\'\\';content:var(--tw-content)}.after\\:\\[corner-shape\\:round\\]:after{content:var(--tw-content);corner-shape:round}.first\\:pt-0:first-child{padding-top:calc(var(--spacing)*0)}.first\\:before\\:hidden:first-child:before{content:var(--tw-content);display:none}.first\\:after\\:top-\\[28px\\]:first-child:after{content:var(--tw-content);top:28px}.last\\:border-b-0:last-child{border-bottom-style:var(--tw-border-style);border-bottom-width:0}.last\\:after\\:hidden:last-child:after{content:var(--tw-content);display:none}.focus-within\\:bg-hover:focus-within{background-color:var(--dsw-alias-interactive-bg-hover)}@media (hover:hover){.hover\\:border-border-l2:hover{border-color:var(--dsw-alias-border-l2)}.hover\\:border-border-l4:hover{border-color:var(--dsw-alias-border-l4)}.hover\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:hover{background-color:var(--dsw-alias-bg-layer-4)}.hover\\:bg-hover:hover{background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:text-secondary:hover{color:var(--dsw-alias-label-secondary)}.hover\\:no-underline:hover{text-decoration-line:none}.hover\\:shadow-\\[0_1px_var\\(--dsw-alias-border-l3\\)\\]:hover{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.hover\\:not-disabled\\:bg-\\[var\\(--dsw-alias-button-floating-hover\\)\\]:hover:not(:disabled){background-color:var(--dsw-alias-button-floating-hover)}.hover\\:not-disabled\\:bg-hover:hover:not(:disabled){background-color:var(--dsw-alias-interactive-bg-hover)}.hover\\:not-disabled\\:bg-layer-1:hover:not(:disabled){background-color:var(--dsw-alias-bg-layer-1)}.hover\\:not-disabled\\:bg-primary-hover:hover:not(:disabled){background-color:var(--dsw-alias-button-primary-hover)}.hover\\:not-disabled\\:text-primary:hover:not(:disabled){color:var(--dsw-alias-label-primary)}.hover\\:not-disabled\\:text-secondary:hover:not(:disabled){color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline:hover:not(:disabled){text-decoration-line:underline}.hover\\:not-disabled\\:decoration-current:hover:not(:disabled){text-decoration-color:currentColor}.hover\\:not-disabled\\:decoration-secondary:hover:not(:disabled){-webkit-text-decoration-color:var(--dsw-alias-label-secondary);-webkit-text-decoration-color:var(--dsw-alias-label-secondary);text-decoration-color:var(--dsw-alias-label-secondary)}.hover\\:not-disabled\\:underline-offset-2:hover:not(:disabled){text-underline-offset:2px}}.focus\\:border-business:focus{border-color:var(--dsw-alias-state-business-primary)}.focus\\:shadow-\\[0_1px_var\\(--dsw-alias-state-business-primary\\)\\]:focus{--tw-shadow:0 1px var(--tw-shadow-color,var(--dsw-alias-state-business-primary));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:border-business:focus-visible{border-color:var(--dsw-alias-state-business-primary)}.focus-visible\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\]:focus-visible{background-color:var(--dsw-alias-bg-layer-4)}.focus-visible\\:bg-hover:focus-visible{background-color:var(--dsw-alias-interactive-bg-hover)}.focus-visible\\:text-secondary:focus-visible{color:var(--dsw-alias-label-secondary)}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-state-business-primary))}@supports (color:color-mix(in lab, red, red)){.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,color-mix(in srgb,var(--dsw-alias-state-business-primary)18%,transparent))}}.focus-visible\\:shadow-\\[0_0_0_2px_color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_18\\%\\,transparent\\)\\]:focus-visible{box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:shadow-focus-ring:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.focus-visible\\:\\[outline\\:2px_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:2px solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline\\:var\\(--dsw-focus-ring-width\\,2px\\)_solid_var\\(--dsw-focus-ring-color\\,var\\(--dsw-alias-state-business-primary\\)\\)\\]:focus-visible{outline:var(--dsw-focus-ring-width,2px)solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.focus-visible\\:\\[outline-offset\\:-2px\\]:focus-visible{outline-offset:-2px}.focus-visible\\:\\[outline-offset\\:1px\\]:focus-visible{outline-offset:1px}.focus-visible\\:outline-none:focus-visible{--tw-outline-style:none;outline-style:none}.active\\:not-disabled\\:bg-active:active:not(:disabled){background-color:var(--dsw-alias-interactive-bg-active)}.disabled\\:cursor-default:disabled{cursor:default}.disabled\\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\\:text-\\[var\\(--dsw-alias-label-quaternary\\)\\]:disabled{color:var(--dsw-alias-label-quaternary)}.disabled\\:text-dimmed:disabled{color:var(--dsw-alias-label-dimmed)}.disabled\\:text-tertiary:disabled{color:var(--dsw-alias-label-tertiary)}.disabled\\:opacity-40:disabled{opacity:.4}.disabled\\:opacity-50:disabled{opacity:.5}.disabled\\:opacity-60:disabled{opacity:.6}.has-\\[\\>input\\:disabled\\]\\:cursor-not-allowed:has(>input:disabled){cursor:not-allowed}.has-\\[\\>input\\:disabled\\]\\:opacity-50:has(>input:disabled){opacity:.5}.aria-expanded\\:bg-\\[var\\(--dsw-alias-bg-layer-4\\)\\][aria-expanded=true]{background-color:var(--dsw-alias-bg-layer-4)}.aria-expanded\\:bg-hover[aria-expanded=true]{background-color:var(--dsw-alias-interactive-bg-hover)}.aria-expanded\\:text-secondary[aria-expanded=true]{color:var(--dsw-alias-label-secondary)}.aria-selected\\:bg-\\[var\\(--dsw-alias-button-ghost-active-fill\\)\\][aria-selected=true]{background-color:var(--dsw-alias-button-ghost-active-fill)}.aria-selected\\:shadow-\\[inset_0_0_0_1px_var\\(--dsw-alias-button-ghost-active-border\\)\\][aria-selected=true]{--tw-shadow:inset 0 0 0 1px var(--tw-shadow-color,var(--dsw-alias-button-ghost-active-border));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.aria-\\[current\\=date\\]\\:shadow-\\[inset_0_0_0_0\\.5px_var\\(--dsw-alias-border-l3\\)\\][aria-current=date]{--tw-shadow:inset 0 0 0 .5px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.data-\\[open\\=true\\]\\:rotate-180[data-open=true]{rotate:180deg}.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:var(--dsw-alias-state-error-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=danger\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-error-primary\\)_10\\%\\,transparent\\)\\][data-tone=danger]{background-color:color-mix(in srgb,var(--dsw-alias-state-error-primary)10%,transparent)}}.data-\\[tone\\=danger\\]\\:text-error[data-tone=danger]{color:var(--dsw-alias-state-error-primary)}.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:var(--dsw-alias-state-business-primary)}@supports (color:color-mix(in lab, red, red)){.data-\\[tone\\=info\\]\\:bg-\\[color-mix\\(in_srgb\\,var\\(--dsw-alias-state-business-primary\\)_10\\%\\,transparent\\)\\][data-tone=info]{background-color:color-mix(in srgb,var(--dsw-alias-state-business-primary)10%,transparent)}}.data-\\[tone\\=info\\]\\:text-business[data-tone=info]{color:var(--dsw-alias-state-business-primary)}.data-\\[tone\\=neutral\\]\\:bg-module-platform[data-tone=neutral]{background-color:var(--dsw-alias-bg-module-platform)}.data-\\[tone\\=neutral\\]\\:text-secondary[data-tone=neutral]{color:var(--dsw-alias-label-secondary)}.data-\\[tone\\=outline\\]\\:border-\\[0\\.5px\\][data-tone=outline]{border-style:var(--tw-border-style);border-width:.5px}.data-\\[tone\\=outline\\]\\:border-border-l4[data-tone=outline]{border-color:var(--dsw-alias-border-l4)}.data-\\[tone\\=outline\\]\\:text-tertiary[data-tone=outline]{color:var(--dsw-alias-label-tertiary)}@media not all and (min-width:1100px){.max-\\[1100px\\]\\:\\[--detail-gutter\\:20px\\]{--detail-gutter:20px}}@media not all and (min-width:760px){.max-\\[760px\\]\\:col-span-3{grid-column:span 3/span 3}.max-\\[760px\\]\\:col-span-6{grid-column:span 6/span 6}.max-\\[760px\\]\\:hidden{display:none}.max-\\[760px\\]\\:flex-1{flex:1}.max-\\[760px\\]\\:grid-cols-\\[repeat\\(6\\,minmax\\(0\\,1fr\\)\\)\\]{grid-template-columns:repeat(6,minmax(0,1fr))}.max-\\[760px\\]\\:border-l-0{border-left-style:var(--tw-border-style);border-left-width:0}.max-\\[760px\\]\\:pt-\\[20px\\]{padding-top:20px}}@media not all and (min-width:680px){.max-\\[680px\\]\\:w-\\[140px\\]{width:140px}.max-\\[680px\\]\\:max-w-\\[160px\\]{max-width:160px}.max-\\[680px\\]\\:grid-cols-\\[minmax\\(0\\,1fr\\)\\]{grid-template-columns:minmax(0,1fr)}}@media not all and (min-width:520px){.max-\\[520px\\]\\:col-span-6\\!{grid-column:span 6/span 6!important}}@media not all and (min-width:400px){.max-\\[400px\\]\\:gap-0{gap:calc(var(--spacing)*0)}.max-\\[400px\\]\\:\\[--detail-gutter\\:16px\\]{--detail-gutter:16px}}@container not (min-width:460px){.\\@max-\\[460px\\]\\:hidden{display:none}}.\\[\\&_a\\]\\:text-business a{color:var(--dsw-alias-state-business-primary)}.\\[\\&_code\\]\\:rounded-\\[4px\\] code{border-radius:4px}.\\[\\&_code\\]\\:bg-layer-3 code{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_code\\]\\:px-\\[5px\\] code{padding-inline:5px}.\\[\\&_code\\]\\:py-\\[1px\\] code{padding-block:1px}.\\[\\&_code\\]\\:\\[font-family\\:var\\(--ds-font-family-code\\)\\] code{font-family:var(--ds-font-family-code)}.\\[\\&_code\\]\\:text-\\[12px\\] code{font-size:12px}.\\[\\&_h1\\]\\:mt-\\[14px\\] h1{margin-top:14px}.\\[\\&_h1\\]\\:mb-\\[6px\\] h1{margin-bottom:6px}.\\[\\&_h1\\]\\:text-\\[18px\\] h1{font-size:18px}.\\[\\&_h1\\]\\:leading-\\[1\\.4\\] h1{--tw-leading:1.4;line-height:1.4}.\\[\\&_h1\\]\\:text-primary h1{color:var(--dsw-alias-label-primary)}.\\[\\&_h2\\]\\:mt-\\[14px\\] h2{margin-top:14px}.\\[\\&_h2\\]\\:mb-\\[6px\\] h2{margin-bottom:6px}.\\[\\&_h2\\]\\:text-\\[16px\\] h2{font-size:16px}.\\[\\&_h2\\]\\:leading-\\[1\\.4\\] h2{--tw-leading:1.4;line-height:1.4}.\\[\\&_h2\\]\\:text-primary h2{color:var(--dsw-alias-label-primary)}.\\[\\&_h3\\]\\:m-0 h3{margin:calc(var(--spacing)*0)}.\\[\\&_h3\\]\\:mt-\\[14px\\] h3{margin-top:14px}.\\[\\&_h3\\]\\:mb-\\[6px\\] h3{margin-bottom:6px}.\\[\\&_h3\\]\\:text-\\[13px\\] h3{font-size:13px}.\\[\\&_h3\\]\\:text-\\[14px\\] h3{font-size:14px}.\\[\\&_h3\\]\\:text-\\[16px\\] h3{font-size:16px}.\\[\\&_h3\\]\\:leading-\\[1\\.4\\] h3{--tw-leading:1.4;line-height:1.4}.\\[\\&_h3\\]\\:leading-\\[20px\\] h3{--tw-leading:20px;line-height:20px}.\\[\\&_h3\\]\\:leading-\\[24px\\] h3{--tw-leading:24px;line-height:24px}.\\[\\&_h3\\]\\:font-medium h3{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.\\[\\&_h3\\]\\:font-semibold h3{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.\\[\\&_h3\\]\\:text-primary h3{color:var(--dsw-alias-label-primary)}.\\[\\&_h4\\]\\:mt-\\[14px\\] h4{margin-top:14px}.\\[\\&_h4\\]\\:mb-\\[6px\\] h4{margin-bottom:6px}.\\[\\&_h4\\]\\:text-\\[13px\\] h4{font-size:13px}.\\[\\&_h4\\]\\:leading-\\[1\\.4\\] h4{--tw-leading:1.4;line-height:1.4}.\\[\\&_h4\\]\\:text-primary h4{color:var(--dsw-alias-label-primary)}.\\[\\&_input\\]\\:m-0 input{margin:calc(var(--spacing)*0)}.\\[\\&_input\\]\\:h-\\[12px\\] input{height:12px}.\\[\\&_input\\]\\:w-\\[12px\\] input{width:12px}.\\[\\&_input\\]\\:accent-brand input{accent-color:var(--dsw-alias-brand-primary)}.\\[\\&_input\\:focus-visible\\]\\:shadow-focus-ring input:focus-visible{--tw-shadow:0 0 0 2px var(--tw-shadow-color,var(--dsw-alias-border-l3));box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.\\[\\&_ol\\]\\:my-\\[6px\\] ol{margin-block:6px}.\\[\\&_ol\\]\\:pl-\\[20px\\] ol{padding-left:20px}.\\[\\&_p\\]\\:m-0 p{margin:calc(var(--spacing)*0)}.\\[\\&_p\\]\\:my-\\[6px\\] p{margin-block:6px}.\\[\\&_p\\]\\:leading-\\[20px\\] p{--tw-leading:20px;line-height:20px}.\\[\\&_pre\\]\\:my-\\[8px\\] pre{margin-block:8px}.\\[\\&_pre\\]\\:overflow-x-auto pre{overflow-x:auto}.\\[\\&_pre\\]\\:rounded-\\[8px\\] pre{border-radius:8px}.\\[\\&_pre\\]\\:border pre{border-style:var(--tw-border-style);border-width:1px}.\\[\\&_pre\\]\\:border-border-l2 pre{border-color:var(--dsw-alias-border-l2)}.\\[\\&_pre\\]\\:bg-layer-3 pre{background-color:var(--dsw-alias-bg-layer-3)}.\\[\\&_pre\\]\\:px-\\[12px\\] pre{padding-inline:12px}.\\[\\&_pre\\]\\:py-\\[10px\\] pre{padding-block:10px}.\\[\\&_svg\\]\\:h-\\[11px\\] svg{height:11px}.\\[\\&_svg\\]\\:h-\\[14px\\] svg{height:14px}.\\[\\&_svg\\]\\:w-\\[11px\\] svg{width:11px}.\\[\\&_svg\\]\\:w-\\[14px\\] svg{width:14px}.\\[\\&_ul\\]\\:my-\\[6px\\] ul{margin-block:6px}.\\[\\&_ul\\]\\:pl-\\[20px\\] ul{padding-left:20px}.\\[\\&\\+\\&\\]\\:border-t+.\\[\\&\\+\\&\\]\\:border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.\\[\\&\\+\\&\\]\\:border-border-weak+.\\[\\&\\+\\&\\]\\:border-border-weak{border-color:var(--dsw-alias-border-weak,#7f7f7f33)}.\\[\\&\\+\\&\\]\\:border-t-border-l2+.\\[\\&\\+\\&\\]\\:border-t-border-l2{border-top-color:var(--dsw-alias-border-l2)}.\\[\\&\\:\\:-webkit-scrollbar\\]\\:hidden::-webkit-scrollbar{display:none}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:cursor-default:has(input:disabled){cursor:default}.\\[\\&\\:has\\(input\\:disabled\\)\\]\\:opacity-60:has(input:disabled){opacity:.6}.\\[\\&\\>\\*\\]\\:w-full>*{width:100%}.\\[\\&\\>\\*\\]\\:max-w-\\[960px\\]>*{max-width:960px}.\\[\\&\\>button\\]\\:h-\\[32px\\]>button{height:32px}.\\[\\&\\>button\\]\\:text-\\[13px\\]>button{font-size:13px}.\\[\\&\\>button\\:last-child\\]\\:mr-\\[-8px\\]>button:last-child{margin-right:-8px}.\\[\\&\\>img\\]\\:absolute>img{position:absolute}.\\[\\&\\>img\\]\\:top-0>img{top:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:left-0>img{left:calc(var(--spacing)*0)}.\\[\\&\\>img\\]\\:block>img{display:block}.\\[\\&\\>img\\]\\:h-\\[1100\\%\\]>img{height:1100%}.\\[\\&\\>img\\]\\:h-full>img{height:100%}.\\[\\&\\>img\\]\\:w-\\[800\\%\\]>img{width:800%}.\\[\\&\\>img\\]\\:w-full>img{width:100%}.\\[\\&\\>img\\]\\:max-w-none>img{max-width:none}.\\[\\&\\>img\\]\\:object-fill>img{object-fit:fill}.\\[\\&\\>span\\:first-child\\]\\:text-tertiary>span:first-child{color:var(--dsw-alias-label-tertiary)}}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-ordinal{syntax:"*";inherits:false}@property --tw-slashed-zero{syntax:"*";inherits:false}@property --tw-numeric-figure{syntax:"*";inherits:false}@property --tw-numeric-spacing{syntax:"*";inherits:false}@property --tw-numeric-fraction{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"<length>";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-outline-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-blur{syntax:"*";inherits:false}@property --tw-brightness{syntax:"*";inherits:false}@property --tw-contrast{syntax:"*";inherits:false}@property --tw-grayscale{syntax:"*";inherits:false}@property --tw-hue-rotate{syntax:"*";inherits:false}@property --tw-invert{syntax:"*";inherits:false}@property --tw-opacity{syntax:"*";inherits:false}@property --tw-saturate{syntax:"*";inherits:false}@property --tw-sepia{syntax:"*";inherits:false}@property --tw-drop-shadow{syntax:"*";inherits:false}@property --tw-drop-shadow-color{syntax:"*";inherits:false}@property --tw-drop-shadow-alpha{syntax:"<percentage>";inherits:false;initial-value:100%}@property --tw-drop-shadow-size{syntax:"*";inherits:false}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-ease{syntax:"*";inherits:false}@property --tw-content{syntax:"*";inherits:false;initial-value:""}`const tailwindcss = cssr.c([TAILWINDCSS_GENERATED])diff --git a/packages/dsh-tauri/src/client/modules/reause.ts b/packages/dsh-tauri/src/client/modules/reause.tsindex 2dd82e75..97a3562c 100644--- a/packages/dsh-tauri/src/client/modules/reause.ts+++ b/packages/dsh-tauri/src/client/modules/reause.ts@@ -13,4 +13,4 @@* 具名清单只保留真正被消耗的 hook,其余被 tree-shake(941KB → 70KB)。* 新增 hook 在此登记即可(dts 同步收窄,漏登记时插件侧直接类型报错)。*/-export { noop, useEventListener, useTimeoutPoll, useWatchImmediate } from '@reause/core'+export { noop, useEventListener, useMount, useResizeObserver, useTimeoutPoll, useUnmount, useWatchImmediate } from '@reause/core'diff --git a/test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts b/test/e2e/plugins/dsh-tauri-scheduler-client.e2e.tsnew file mode 100644index 00000000..f1348af0--- /dev/null+++ b/test/e2e/plugins/dsh-tauri-scheduler-client.e2e.ts@@ -0,0 +1,652 @@+import type { Locator } from 'playwright'+import type { GetApiTauriSchedulerHistoryResponse, GetApiTauriSchedulerTasksResponse, PostApiTauriSchedulerTasksBody, PostApiTauriSchedulerTasksResponse, PutApiTauriSchedulerTasksBody } from '../../../packages/dsh-tauri-scheduler/src/client/apis/index.type'+import type { DshPage } from '../support/browser'+import { randomUUID } from 'node:crypto'+import { mkdir, readFile, writeFile } from 'node:fs/promises'+import { createRequire } from 'node:module'+import { tmpdir } from 'node:os'+import { basename, dirname, join, resolve } from 'node:path'+import process from 'node:process'+import { describe, expect, inject, it } from 'vitest'+import { describePageState, dismissAppModals, expectNoSyntheticFallbacks, launchDshBrowser, newDshPage, SIDEBAR_PANELLIST } from '../support/browser'+import { resolveDshCommand } from '../support/dsh'++const TASKS_PATH = '/api/tauri/scheduler/tasks'+const HISTORY_PATH = '/api/tauri/scheduler/history'+const MAIN_SLOT = '[data-slot="main"]'+const BODY_SLOT = '[data-slot="sidebar.right.pane.tab"]'+const TITLE_SLOT = '[data-slot="sidebar.right.pane.tab.title"]'++function scratchHome(): string {+ const home = resolve(inject('dshHome'))+ expect(dirname(home), '夹具只能写入系统临时目录的直接子目录').toBe(resolve(tmpdir()))+ expect(basename(home), '夹具只能写入本轮编排创建的 dsh-e2e 隔离目录').toMatch(/^dsh-e2e-.+-[a-z0-9]+$/)+ expect(inject('dshMounted'), '隔离宿主必须实际挂载被测 scheduler').toContain('dsh-tauri-scheduler')+ return home+}++async function api<T>(path: string, method = 'GET', body?: unknown): Promise<T> {+ const response = await fetch(`${inject('dshBaseUrl')}${path}`, {+ method,+ headers: { 'cookie': inject('dshCookie'), 'content-type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ })+ expect(response.status, `${method} ${path} 必须返回 200`).toBe(200)+ return await response.json() as T+}++async function createScratchSession(): Promise<string> {+ const sessionId = `session-${randomUUID()}`+ const rpcId = randomUUID()+ const created = await api<{ type: string, rpcId: string, result: { ok: boolean, value?: { sessionId: string } } }>('/api/session/create', 'POST', {+ type: 'client-request',+ rpcId,+ method: 'session/create',+ payload: { args: { request: { sessionId, cwd: inject('dshHome') } } },+ })+ expect(created, '原生 RPC 只能在 scratch 内创建关联会话且必须回传相同身份').toMatchObject({ type: 'server-response', rpcId, result: { ok: true, value: { sessionId } } })+ return sessionId+}++async function readTasks(): Promise<GetApiTauriSchedulerTasksResponse['tasks']> {+ const payload = await api<GetApiTauriSchedulerTasksResponse>(TASKS_PATH)+ expect(Array.isArray(payload.tasks), '真实任务清单必须带 tasks 数组').toBe(true)+ return payload.tasks+}++async function expectNoExecution(id: string): Promise<void> {+ const history = await api<GetApiTauriSchedulerHistoryResponse>(`${HISTORY_PATH}?taskId=${encodeURIComponent(id)}&limit=100`)+ expect(history.ok, '暂停任务的历史查询必须成功').toBe(true)+ if (!history.ok)+ throw new Error(history.error)+ expect(history.records, '浏览器编辑不得触发模型或产生投递记录').toEqual([])+ expect(history.runs, '暂停的新会话任务不得产生执行记录').toEqual([])+}++async function withScratchPage(run: (app: DshPage, prefix: string) => Promise<void>, expectedErrors: readonly string[] = [], viewport?: { width: number, height: number }): Promise<void> {+ const prefix = `scheduler-client-${randomUUID()}`+ const browser = await launchDshBrowser()+ let app: DshPage | undefined+ const warnings: string[] = []+ try {+ app = await newDshPage(browser, { ready: SIDEBAR_PANELLIST, viewport })+ app.page.on('console', (message) => {+ if (message.type() === 'warning')+ warnings.push(JSON.stringify({ text: message.text(), location: message.location() }))+ })+ expectNoSyntheticFallbacks(app)+ await run(app, prefix)+ expectNoSyntheticFallbacks(app)+ expect(app.errors, '真实交互不得产生未明确断言的浏览器错误').toEqual(expectedErrors)+ }+ catch (error) {+ try {+ const directory = resolve(process.env.DSH_SCHEDULER_DIAGNOSTICS_DIR ?? '.temp/scheduler-diagnostics', prefix)+ const lines = [`case=${prefix}`, error instanceof Error ? error.stack ?? error.message : String(error)]+ const capture = async (label: string, collect: () => Promise<string>): Promise<void> => {+ try {+ const value = await collect()+ lines.push(`${label}\n${value}`)+ process.stderr.write(`[scheduler diagnostics] ${label}\n${value}\n`)+ }+ catch (diagnosticError) {+ const value = `${label}: ${diagnosticError instanceof Error ? diagnosticError.stack ?? diagnosticError.message : String(diagnosticError)}`+ lines.push(`DIAGNOSTIC_FAILED ${value}`)+ process.stderr.write(`[scheduler diagnostics] DIAGNOSTIC_FAILED ${value}\n`)+ }+ }+ await capture('console warnings (after page initialization)', async () => warnings.join('\n') || '(none)')+ await capture('diagnostics directory', async () => {+ await mkdir(directory, { recursive: true })+ return directory+ })+ const page = app?.page ?? browser.contexts().flatMap(context => context.pages())[0]+ const frame = app?.frame ?? page?.frames().find(candidate => candidate !== page.mainFrame()) ?? page?.mainFrame()+ if (page && frame) {+ if (!app) {+ await capture('initial boot diagnostics replay', async () => {+ page.on('console', (message) => {+ if (message.type() === 'warning' || message.type() === 'error')+ warnings.push(JSON.stringify({ text: message.text(), location: message.location() }))+ })+ await frame.goto(`${inject('dshBaseUrl')}/`, { waitUntil: 'domcontentloaded' })+ await frame.waitForFunction(() => document.querySelector('[data-slot]') !== null || document.querySelector('[data-dsh-boot]')?.textContent?.includes('Failed to load plugins'), undefined, { timeout: 15_000 })+ return warnings.join('\n')+ })+ }+ await capture('page state', () => describePageState(page, frame))+ const nodes: readonly [string, Locator][] = [+ ['tabs', frame.getByRole('tab', { includeHidden: true })],+ ['titles', frame.locator(TITLE_SLOT)],+ ['bodies', frame.locator(BODY_SLOT)],+ ['alerts', frame.getByRole('alert', { includeHidden: true })],+ ['slot errors', frame.locator('[data-slot-error]')],+ ]+ for (const [label, locator] of nodes) {+ await capture(label, async () => {+ const count = await locator.count()+ const values: { index: number, text: string | null, slot: string | null, slotError: string | null, dockkitTab: string | null, sidebarRightTab: string | null, selected: string | null }[] = []+ for (let index = 0; index < count; index++) {+ const node = locator.nth(index)+ values.push({+ index,+ text: await node.textContent({ timeout: 2_000 }),+ slot: await node.getAttribute('data-slot', { timeout: 2_000 }),+ slotError: await node.getAttribute('data-slot-error', { timeout: 2_000 }),+ dockkitTab: await node.getAttribute('data-dockkit-tab', { timeout: 2_000 }),+ sidebarRightTab: await node.getAttribute('data-sidebar-right-tab', { timeout: 2_000 }),+ selected: await node.getAttribute('aria-selected', { timeout: 2_000 }),+ })+ }+ return JSON.stringify({ count, nodes: values }, null, 2)+ })+ }+ await capture('screenshot', async () => {+ const path = join(directory, 'page.png')+ await page.screenshot({ path, fullPage: true, timeout: 5_000 })+ return path+ })+ }+ else {+ await capture('page state', async () => 'No public browser page/frame remained at failure')+ }+ await capture('scratch host log', async () => {+ const path = join(inject('dshHome'), 'dsh-web.log')+ const log = await readFile(path, 'utf8')+ await writeFile(join(directory, 'dsh-web.log'), log, 'utf8')+ return `source=${path}\n${log}`+ })+ await capture('report', async () => {+ const path = join(directory, 'report.txt')+ await writeFile(path, lines.join('\n\n'), 'utf8')+ return path+ })+ }+ catch (diagnosticError) {+ try {+ process.stderr.write(`[scheduler diagnostics] ${diagnosticError instanceof Error ? diagnosticError.stack ?? diagnosticError.message : String(diagnosticError)}\n`)+ }+ catch {+ throw error+ }+ }+ throw error+ }+ finally {+ try {+ for (const task of await readTasks()) {+ if (task.name.startsWith(prefix)) {+ const removed = await api<{ ok?: boolean }>(TASKS_PATH, 'DELETE', { id: task.id })+ expect(removed, '清理必须成功删除本用例创建的 scratch 任务').toEqual({ ok: true })+ }+ }+ expect((await readTasks()).filter(task => task.name.startsWith(prefix)), '用例不得留下自己的 scratch 任务').toEqual([])+ }+ finally {+ try {+ await app?.close()+ }+ finally {+ await browser.close()+ }+ }+ }+}++async function openCatalog(app: DshPage): Promise<Locator> {+ await dismissAppModals(app.page, app.frame, app.syntheticFallbacks)+ await app.frame.getByRole('button', { name: '定时任务', exact: true }).click()+ const main = app.frame.locator(MAIN_SLOT)+ await expect.poll(() => main.getByRole('heading', { name: '定时任务', level: 1, exact: true }).isVisible(), {+ timeout: 15_000,+ message: '侧栏的真实指针点击必须打开任务主面板',+ }).toBe(true)+ return main+}++async function inlineDetail(app: DshPage, label: string): Promise<Locator> {+ const main = app.frame.locator(MAIN_SLOT)+ const body = main.getByRole('complementary', { name: label, exact: true })+ await expect.poll(() => body.getByLabel('名称', { exact: true }).isVisible(), { timeout: 15_000, message: `主面板内必须出现「${label}」详情表单` }).toBe(true)+ expect(await body.count(), '同一任务不得重复挂载详情').toBe(1)+ expect(await main.getByRole('heading', { name: '定时任务', level: 1, exact: true }).isVisible(), '打开详情不得离开任务主面板').toBe(true)+ expect(await app.frame.locator(TITLE_SLOT).count(), '主面板编辑不得创建原生会话 Tab 标题').toBe(0)+ expect(await app.frame.locator(BODY_SLOT).count(), '主面板编辑不得挂载原生会话 Tab 内容').toBe(0)+ expect(await app.frame.locator('[data-slot="conversation.session"]').count(), '主面板编辑不得跳转至会话').toBe(0)+ expect(await app.frame.getByRole('dialog', { includeHidden: true }).count(), '详情必须内联,不能回退到 Modal').toBe(0)+ return body+}++async function openTaskDetail(app: DshPage, name: string): Promise<Locator> {+ const main = app.frame.locator(MAIN_SLOT)+ await expect.poll(() => main.getByText(name, { exact: true }).isVisible(), { timeout: 15_000, message: '共享真实 catalog 必须读到保存的任务' }).toBe(true)+ await main.getByText(name, { exact: true }).click()+ return inlineDetail(app, name)+}++async function captureLayout(app: DshPage, prefix: string, label: string): Promise<void> {+ const directory = resolve(process.env.DSH_SCHEDULER_DIAGNOSTICS_DIR ?? '.temp/scheduler-diagnostics', prefix)+ await mkdir(directory, { recursive: true })+ await app.page.screenshot({ path: join(directory, `${label}.png`), fullPage: true })+}++function taskResponse(app: DshPage, method: string) {+ return app.page.waitForResponse(response => new URL(response.url()).pathname === TASKS_PATH && response.request().method() === method, { timeout: 15_000 })+}++describe('C 当前 core 的定时任务主面板内联详情', () => {+ it('手动暂停草稿内联保存与更新提交完整 expected,刷新后重开同一持久任务', async () => {+ await withScratchPage(async (app, prefix) => {+ const main = await openCatalog(app)+ await main.getByRole('button', { name: '手动创建', exact: true }).click()+ const draft = await inlineDetail(app, '新建定时任务')+ const name = `${prefix}-manual`+ const prompt = '仅验证暂停任务的浏览器保存,不执行任何模型请求。'+ const nameInput = draft.getByLabel('名称', { exact: true })+ await expect.poll(() => nameInput.isVisible(), { timeout: 15_000, message: '真实 options 加载后必须出现草稿表单' }).toBe(true)+ expect(await nameInput.inputValue(), '手动入口必须打开空白草稿').toBe('')+ expect(await draft.getByRole('button', { name: '投递方式', exact: true }).textContent(), '新建任务必须明确显示新会话投递').toContain('新会话执行')+ const enabled = draft.getByRole('checkbox', { name: '启用', exact: true })+ expect(await enabled.isChecked(), '新建草稿默认启用,测试保存前必须真实点击暂停').toBe(true)+ await enabled.click()+ expect(await enabled.isChecked(), '保存前必须关闭启用,禁止任务实际执行').toBe(false)+ await nameInput.fill(name)+ await draft.getByPlaceholder('描述我们应该做什么', { exact: true }).fill(prompt)+ await draft.getByRole('button', { name: '时间', exact: true }).click()+ const clock = app.frame.getByRole('dialog', { name: '时间', exact: true })+ await clock.getByRole('listbox', { name: '时', exact: true }).getByRole('option', { name: '13', exact: true }).click()+ await clock.getByRole('listbox', { name: '分', exact: true }).getByRole('option', { name: '17', exact: true }).click()+ await clock.press('Escape')+ expect(await draft.getByRole('button', { name: '时间', exact: true }).textContent(), '官方时钟列选择必须显示完整 HH:mm').toContain('13:17')+ await draft.getByRole('button', { name: '时区', exact: true }).click()+ await app.frame.getByRole('searchbox', { name: '搜索时区', exact: true }).fill('UTC')+ await app.frame.getByRole('menuitem').and(app.frame.getByTitle('UTC', { exact: true })).click()+ expect(await draft.getByRole('button', { name: '时区', exact: true }).getAttribute('title'), '时区菜单必须保存搜索命中的精确 IANA 标识').toBe('UTC')+ const creation = taskResponse(app, 'POST')+ await draft.getByRole('button', { name: '保存', exact: true }).click()+ const createdResponse = await creation+ expect(createdResponse.status(), '手动保存必须调用真实创建路由并成功').toBe(200)+ expect(createdResponse.request().postDataJSON() as PostApiTauriSchedulerTasksBody, '真实创建请求必须保存暂停的新会话任务').toMatchObject({+ name,+ prompt,+ delivery: 'new-session',+ enabled: false,+ schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' },+ })+ const createdPayload = await createdResponse.json() as PostApiTauriSchedulerTasksResponse+ expect(createdPayload.ok, '手动创建必须返回 ok:true').toBe(true)+ if (!createdPayload.task)+ throw new Error('手动创建未返回完整 task 快照')+ const created = createdPayload.task+ expect(created.id, '创建必须返回真实持久化任务 id').toMatch(/^task-[0-9a-f-]{36}$/)+ const saved = await inlineDetail(app, name)+ expect(await main.getByRole('complementary').count(), 'draft→task 必须仅有一个主面板详情').toBe(1)+ expect(await saved.locator('details').getAttribute('open'), '已保存任务的投递与执行设置默认折叠').toBeNull()+ const before = (await readTasks()).find(task => task.id === created.id)+ expect(before, '独立 HTTP 清单必须保存草稿输入').toMatchObject({ id: created.id, name, prompt, enabled: false, delivery: 'new-session', status: 'active', schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' } })+ const updatedName = `${prefix}-updated`+ const updatedPrompt = '暂停任务已更新,仍不执行任何模型请求。'+ await saved.getByLabel('名称', { exact: true }).fill(updatedName)+ await saved.getByPlaceholder('描述我们应该做什么', { exact: true }).fill(updatedPrompt)+ const update = taskResponse(app, 'PUT')+ await saved.getByRole('button', { name: '保存', exact: true }).click()+ const updatedResponse = await update+ expect(updatedResponse.status(), '编辑保存必须调用真实 PUT 路由并成功').toBe(200)+ const sent = updatedResponse.request().postDataJSON() as PutApiTauriSchedulerTasksBody+ expect(sent.expected, 'PUT 必须携带独立 HTTP 清单中的完整编辑前快照').toEqual(before)+ expect(sent, 'PUT 必须保留暂停状态与任务 id').toMatchObject({ id: created.id, name: updatedName, prompt: updatedPrompt, enabled: false, delivery: 'new-session' })+ expect(await updatedResponse.json(), '真实更新响应必须包含更新后的同一任务').toMatchObject({ ok: true, task: { id: created.id, name: updatedName, prompt: updatedPrompt, enabled: false } })+ const updated = await inlineDetail(app, updatedName)+ const firstSaved = (await readTasks()).find(task => task.id === created.id)+ expect(firstSaved, '第二次编辑必须读取第一次 PUT 已持久化的任务').toMatchObject({ id: created.id, name: updatedName, prompt: updatedPrompt, enabled: false })+ const finalPrompt = '第二次保存必须基于第一次保存后的完整快照。'+ await updated.getByPlaceholder('描述我们应该做什么', { exact: true }).fill(finalPrompt)+ const secondUpdate = taskResponse(app, 'PUT')+ await updated.getByRole('button', { name: '保存', exact: true }).click()+ const secondResponse = await secondUpdate+ expect(secondResponse.status(), '同面板第二次保存必须成功,不能错误复用最初快照').toBe(200)+ expect((secondResponse.request().postDataJSON() as PutApiTauriSchedulerTasksBody).expected, '第二次 PUT 必须使用第一次 PUT 后的完整快照').toEqual(firstSaved)+ expect(await secondResponse.json(), '第二次更新必须保存同一任务的新指令').toMatchObject({ ok: true, task: { id: created.id, prompt: finalPrompt, enabled: false } })+ await app.frame.goto(`${inject('dshBaseUrl')}/`, { waitUntil: 'domcontentloaded' })+ await dismissAppModals(app.page, app.frame, app.syntheticFallbacks, 20_000, 3_000)+ expectNoSyntheticFallbacks(app)+ await openCatalog(app)+ const restored = await openTaskDetail(app, updatedName)+ await expect.poll(() => restored.getByLabel('名称', { exact: true }).inputValue(), { timeout: 15_000, message: '刷新后从任务行重开必须读取同一持久化任务' }).toBe(updatedName)+ expect(await restored.getByPlaceholder('描述我们应该做什么', { exact: true }).inputValue(), '重开后的表单必须读取最后一次保存的指令').toBe(finalPrompt)+ expect((await readTasks()).find(task => task.id === created.id), '刷新不得改写已保存任务身份和暂停状态').toMatchObject({ id: created.id, name: updatedName, prompt: finalPrompt, enabled: false })+ await restored.locator('summary').click()+ expect(await restored.getByRole('checkbox', { name: '启用', exact: true }).isChecked(), '刷新不得重新启用任务').toBe(false)+ await captureLayout(app, prefix, 'saved-inline-rule')+ await expectNoExecution(created.id)+ })+ })++ it('两种投递任务行都只开本地详情,规则与记录共享 24px 留白且保存栏不随内容滚动', async () => {+ await withScratchPage(async (app, prefix) => {+ const sessionId = await createScratchSession()+ const names = { 'new-session': `${prefix}-global`, 'this-session': `${prefix}-reminder` }+ const tasks = []+ for (const delivery of ['new-session', 'this-session'] as const) {+ const response = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'POST', {+ name: names[delivery],+ prompt: `暂停的 ${delivery} 任务不得执行模型。`,+ delivery,+ ...(delivery === 'this-session' ? { sessionId } : {}),+ enabled: false,+ schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' },+ } satisfies PostApiTauriSchedulerTasksBody)+ expect(response, '两类暂停任务必须通过真实 API 保存').toMatchObject({ ok: true, task: { name: names[delivery], delivery, enabled: false, status: 'active' } })+ if (!response.task)+ throw new Error('种植任务没有返回持久快照')+ tasks.push(response.task)+ }+ const main = await openCatalog(app)+ for (const task of tasks) {+ const rowTitle = main.getByText(task.name, { exact: true }).locator('..')+ const sessionTag = rowTitle.getByText('会话', { exact: true })+ expect(await sessionTag.count(), '只有会话任务在标题后显示固定小标签,全局任务不能有标签').toBe(task.delivery === 'this-session' ? 1 : 0)+ if (task.delivery === 'this-session') {+ const tagGeometry = await sessionTag.evaluate((element) => {+ const heading = element.parentElement!.querySelector('[title]')!+ const title = heading.getBoundingClientRect()+ const tag = element.getBoundingClientRect()+ return { height: tag.height, left: tag.x, after: title.right, svg: element.querySelectorAll('svg').length }+ })+ expect(tagGeometry, '会话标签必须恰好 18px 高且没有气泡或其他 SVG 图标').toMatchObject({ height: 18, svg: 0 })+ expect(tagGeometry.left, '会话标签必须在标题之后,而不是标题前').toBeGreaterThanOrEqual(tagGeometry.after)+ }+ const detail = await openTaskDetail(app, task.name)+ const tabs = detail.getByRole('tablist', { name: '任务详情', exact: true })+ const rule = detail.getByRole('tabpanel', { name: '规则', exact: true })+ expect(await tabs.getByRole('tab').allTextContents(), '本地详情必须且仅有规则与记录两项').toEqual(['规则', '任务运行记录'])+ const geometry = await rule.evaluate((element) => {+ const style = getComputedStyle(element)+ const aside = element.closest('aside')!+ const strip = aside.querySelector('[role="tablist"]')!.parentElement!+ return { left: style.paddingLeft, right: style.paddingRight, stripHeight: strip.getBoundingClientRect().height, width: aside.getBoundingClientRect().width }+ })+ expect(geometry, '1400px 宿主中详情内容必须有双侧 24px 留白及 44px 标签条').toMatchObject({ left: '24px', right: '24px', stripHeight: 44 })+ const mainBox = await main.locator('section').filter({ has: app.frame.getByRole('heading', { name: '定时任务', level: 1, exact: true }) }).boundingBox()+ if (!mainBox)+ throw new Error('任务主面板必须有可见几何')+ expect(Math.abs(geometry.width / mainBox.width - 0.47), '本地详情必须占主面板宽度的 47%').toBeLessThanOrEqual(0.005)+ const promptGeometry = await detail.getByLabel('任务指令', { exact: true }).evaluate((element) => {+ const style = getComputedStyle(element)+ return { width: element.getBoundingClientRect().width, parentWidth: element.parentElement!.getBoundingClientRect().width, height: element.getBoundingClientRect().height, minimum: style.minHeight, maximum: style.maxHeight, padding: style.padding, boxSizing: style.boxSizing }+ })+ expect(promptGeometry, '任务指令必须使用完整内容宽度与 112..160px 可增长边界').toMatchObject({ minimum: '112px', maximum: '160px', padding: '12px', boxSizing: 'border-box' })+ expect(Math.abs(promptGeometry.width - promptGeometry.parentWidth), '指令输入不得超出详情内容区或只占部分宽度').toBeLessThanOrEqual(1)+ expect(promptGeometry.height, '指令区域不能挤至低于基础高度').toBeGreaterThanOrEqual(112)+ expect(promptGeometry.height, '短指令区域不能高于规定上界').toBeLessThanOrEqual(160)+ const options = detail.locator('details')+ expect(await options.getAttribute('open'), '已保存任务的执行选项必须默认折叠').toBeNull()+ await options.locator('summary').click()+ expect(await options.getAttribute('open'), '本地点击必须真实展开执行选项').toBe('')+ expect(await detail.getByRole('button', { name: '投递方式', exact: true }).textContent(), '展开后必须显示本任务准确的投递方式').toContain(task.delivery === 'this-session' ? '当前会话提醒' : '新会话执行')+ expect(await detail.getByRole('button', { name: /^关联会话:/ }).count(), '只有当前会话任务的规则工具条才有明确跳转按钮').toBe(task.delivery === 'this-session' ? 1 : 0)+ const changedPrompt = `${task.prompt}\n本地未保存的草稿切换记录后仍须保留。`+ await detail.getByLabel('任务指令', { exact: true }).fill(changedPrompt)+ const footer = detail.locator('form > footer')+ const beforeScroll = await footer.boundingBox()+ const scroll = await rule.evaluate(element => ({ total: element.scrollHeight, view: element.clientHeight }))+ expect(scroll.total, '展开选项后的规则内容必须产生独立滚动区').toBeGreaterThan(scroll.view)+ await rule.hover()+ await app.page.mouse.wheel(0, 700)+ await expect.poll(() => rule.evaluate(element => element.scrollTop), { timeout: 5_000, message: '真实鼠标滚轮必须只滚动详情规则内容' }).toBeGreaterThan(0)+ const afterScroll = await footer.boundingBox()+ if (!beforeScroll || !afterScroll)+ throw new Error('未保存修改必须拥有可见固定保存栏')+ expect(Math.abs(afterScroll.y - beforeScroll.y), '保存栏不得随规则内容滚动').toBeLessThanOrEqual(1)+ await captureLayout(app, prefix, `${task.delivery}-inline-rule`)++ const response = app.page.waitForResponse(value => new URL(value.url()).pathname === HISTORY_PATH && new URL(value.url()).searchParams.get('taskId') === task.id && new URL(value.url()).searchParams.get('limit') === '20')+ await tabs.getByRole('tab', { name: '任务运行记录', exact: true }).click()+ const received = await response+ expect(received.status(), '记录视图必须请求当前任务的真实历史').toBe(200)+ expect(await received.json(), '暂停任务的分页历史必须为空且成功').toMatchObject({ ok: true, records: [], runs: [] })+ const records = detail.getByRole('tabpanel', { name: '任务运行记录', exact: true })+ await expect.poll(() => records.getByRole('region', { name: '运行记录', exact: true }).isVisible(), { timeout: 15_000, message: '切记录必须真正显示记录区' }).toBe(true)+ expect(await detail.getByLabel('名称', { exact: true }).isVisible(), '记录页不能继续显示规则名称输入').toBe(false)+ expect(await rule.isVisible(), '记录页必须完整隐藏规则面板').toBe(false)+ await expect.poll(() => records.getByRole('status').textContent(), { timeout: 15_000, message: '记录空态必须显示准确文案' }).toBe('还没有运行记录')+ expect(await footer.isVisible(), '记录页必须保留未保存修改的固定保存栏').toBe(true)+ expect(await records.getByRole('region', { name: '运行记录', exact: true }).evaluate(element => getComputedStyle(element.firstElementChild!).paddingLeft), '记录内容与规则共享 24px 留白').toBe('24px')+ await captureLayout(app, prefix, `${task.delivery}-inline-records`)+ await tabs.getByRole('tab', { name: '规则', exact: true }).click()+ expect(await detail.getByLabel('任务指令', { exact: true }).inputValue(), '切记录再回规则不得丢失草稿').toBe(changedPrompt)+ expect(await options.getAttribute('open'), '规则与记录切换必须保留本地展开状态').toBe('')+ await detail.getByRole('button', { name: '关闭', exact: true }).click()+ const reopened = await openTaskDetail(app, task.name)+ expect(await reopened.locator('details').getAttribute('open'), '关闭重开必须重置本地展开态而非全局记忆').toBeNull()+ expect(await reopened.getByLabel('任务指令', { exact: true }).inputValue(), '关闭未保存草稿不得覆盖持久任务').toBe(task.prompt)+ await reopened.getByRole('button', { name: '关闭', exact: true }).click()+ await expectNoExecution(task.id)+ }+ }, [], { width: 1400, height: 640 })+ })++ it('会话提醒入口保留原生右栏身份与 37px 标签条,隐藏同会话跳转和冗余关闭并在刷新后恢复绑定', async () => {+ await withScratchPage(async (app, prefix) => {+ const coreRequire = createRequire(resolveDshCommand()[0]!)+ const { Context } = coreRequire('@deepseek-ai/cordis')+ const { SessionStore, SessionId } = coreRequire('@deepseek-ai/dsh-session')+ const { createUserMessage } = coreRequire('@deepseek-ai/dsh-llm')+ const { default: JsonlSessionPersistence } = coreRequire('@deepseek-ai/dsh-session-persistence-jsonl')+ const home = scratchHome()+ const context = new Context()+ let sessionId: string+ try {+ const persistence = new JsonlSessionPersistence(context, { root: join(home, 'sessions') })+ const session = new SessionStore(context).create(SessionId(`session-${randomUUID()}`), { meta: { cwd: home } })+ session.append('turn/start', { turn: 1 })+ session.append('step/start', { turn: 1, step: 1 })+ session.append('user/message', createUserMessage({ content: [{ type: 'text', text: '已结束的 UI 夹具消息,没有请求任何模型。' }], source: { kind: 'user', rpcId: randomUUID() } }), { surfaceOp: 'append' })+ session.append('step/end', { turn: 1, step: 1 })+ session.append('turn/end', { turn: 1, reason: { kind: 'completed' } })+ const handle = await persistence.create(session.header)+ try {+ await handle.append(session.snapshotEvents())+ await handle.flush()+ }+ finally {+ await handle.close()+ }+ sessionId = session.id+ }+ finally {+ await context.fiber.dispose()+ }+ const rpcId = randomUUID()+ const adopted = await api<{ type: string, rpcId: string, result: { ok: boolean, value?: { sessionId: string } } }>('/api/session/create', 'POST', { type: 'client-request', rpcId, method: 'session/create', payload: { args: { request: { sessionId, cwd: home } } } })+ expect(adopted, `真实 RPC 必须接管公开持久化夹具而不是创建另一个空白会话:${JSON.stringify(adopted)}`).toMatchObject({ type: 'server-response', rpcId, result: { ok: true, value: { sessionId } } })+ const name = `${prefix}-native`+ const created = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'POST', {+ name,+ prompt: '只验证会话提醒右栏,未来触发不会在本用例内执行。',+ delivery: 'this-session',+ sessionId,+ enabled: true,+ schedule: { kind: 'once', at: new Date(Date.now() + 3_600_000).toISOString(), timeZone: 'UTC' },+ } satisfies PostApiTauriSchedulerTasksBody)+ if (!created.ok || !created.task)+ throw new Error('未来会话提醒必须创建成功')+ await openCatalog(app)+ const detail = await openTaskDetail(app, name)+ const ownerLink = detail.getByRole('button', { name: /^关联会话:/ })+ await expect.poll(() => ownerLink.isEnabled(), { timeout: 15_000, message: '主面板只允许通过明确的关联会话按钮切换会话' }).toBe(true)+ await ownerLink.click()+ const bubble = app.frame.getByRole('button', { name: '查看定时任务', exact: true })+ await expect.poll(() => bubble.isVisible(), { timeout: 15_000, message: '显式跳转后原会话必须显示定时提醒入口' }).toBe(true)+ await bubble.click()+ const chip = app.frame.getByRole('tab').filter({ has: app.frame.locator(TITLE_SLOT).getByText(name, { exact: true }) })+ await expect.poll(() => chip.count(), { timeout: 15_000, message: '提醒入口必须创建且仅创建一个原生任务 Tab' }).toBe(1)+ expect(await chip.getAttribute('aria-selected'), '原生任务 Tab 必须选中').toBe('true')+ expect(await chip.locator(TITLE_SLOT).textContent(), '原生公共标题槽必须渲染准确任务名称').toBe(name)+ const tabId = await chip.getAttribute('data-dockkit-tab')+ if (!tabId)+ throw new Error('原生任务 Tab 缺少公共 data-dockkit-tab 标识')+ const body = app.frame.locator(`[data-sidebar-right-tab=${JSON.stringify(tabId)}] ${BODY_SLOT}`)+ await expect.poll(() => body.getByLabel('名称', { exact: true }).inputValue(), { timeout: 15_000, message: '同一公共 Tab 内容槽必须读取正确提醒任务' }).toBe(name)+ expect(await body.count(), '原生任务 Tab 内容不得重复挂载').toBe(1)+ expect(await chip.locator('[data-sidebar-right-tab]').getAttribute('data-sidebar-right-tab'), '公共标题必须属于同一原生 Tab').toBe(tabId)+ const tabs = body.getByRole('tablist', { name: '任务详情', exact: true })+ expect(await tabs.evaluate(element => element.parentElement!.getBoundingClientRect().height), '会话已有标题栏时本地标签条必须恰好 37px').toBe(37)+ expect(await body.getByRole('button', { name: /^关联会话:/ }).count(), '会话内详情不得重复链接到自身会话').toBe(0)+ expect(await body.getByRole('button', { name: '关闭', exact: true }).count(), '会话内详情不得渲染第二个关闭按钮').toBe(0)+ const historyResponse = app.page.waitForResponse(value => new URL(value.url()).pathname === HISTORY_PATH && new URL(value.url()).searchParams.get('taskId') === created.task!.id && new URL(value.url()).searchParams.get('limit') === '20')+ await tabs.getByRole('tab', { name: '任务运行记录', exact: true }).click()+ expect((await historyResponse).status(), '会话右栏记录必须调用真实的按任务分页').toBe(200)+ await expect.poll(() => body.getByRole('region', { name: '运行记录', exact: true }).getByRole('status').textContent(), { timeout: 15_000, message: '会话右栏记录区必须真正显示正确空态' }).toBe('还没有运行记录')+ expect(await body.getByLabel('名称', { exact: true }).isVisible(), '会话记录页也必须隐藏规则名称输入').toBe(false)+ await captureLayout(app, prefix, 'native-session-records')+ await app.frame.goto(`${inject('dshBaseUrl')}/`, { waitUntil: 'domcontentloaded' })+ await dismissAppModals(app.page, app.frame, app.syntheticFallbacks, 20_000, 3_000)+ await expect.poll(() => chip.count(), { timeout: 15_000, message: '真实刷新后原生 Tab 必须恢复绑定与标题' }).toBe(1)+ expect(await chip.getAttribute('data-dockkit-tab'), '原生 Tab 刷新必须保持稳定身份').toBe(tabId)+ await expect.poll(() => body.getByLabel('名称', { exact: true }).inputValue(), { timeout: 15_000, message: '公共 body 刷新必须读取同一持久任务' }).toBe(name)+ expect(await body.getByRole('tablist', { name: '任务详情', exact: true }).evaluate(element => element.parentElement!.getBoundingClientRect().height), '原生 Tab 刷新后仍必须保持 37px 标签条').toBe(37)+ await expectNoExecution(created.task.id)+ })+ })++ it('scratch 真实历史夹具只渲染分钟日期与已发送指令,正常记录无重复状态或刷新控件', async () => {+ await withScratchPage(async (app, prefix) => {+ const sessionId = await createScratchSession()+ const name = `${prefix}-history`+ const created = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'POST', { name, prompt: '当前任务已编辑后的指令,不应替换历史。', delivery: 'new-session', enabled: false, schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' } } satisfies PostApiTauriSchedulerTasksBody)+ if (!created.ok || !created.task)+ throw new Error('历史夹具的暂停任务必须创建成功')+ const home = scratchHome()+ const path = join(home, 'crons', 'history')+ const previous = await readFile(path, 'utf8').catch((error: NodeJS.ErrnoException) => {+ if (error.code !== 'ENOENT')+ throw error+ return JSON.stringify({ version: 2, records: [], flags: {}, pending: [], journal: [] })+ })+ const state = JSON.parse(previous) as { version: number, records: unknown[], flags: object, pending: unknown[], journal?: unknown[] }+ expect(state, '视觉夹具不能覆盖未知历史格式').toMatchObject({ version: 2, records: [], pending: [] })+ const now = new Date()+ const at = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 12, 34, 56)).toISOString()+ const retainedAt = now.toISOString()+ const receiptId = `message-${randomUUID()}`+ const runId = `run-${randomUUID()}`+ const prompts = ['已经发送的提醒指令。', '已经执行的新会话指令。']+ const fixtures = [+ { id: receiptId, messageId: receiptId, taskId: created.task.id, taskName: name, prompt: prompts[0], delivery: 'this-session', occurrence: at, scheduledAt: at, deliveredAt: retainedAt, sessionId, trigger: 'schedule' },+ { id: runId, taskId: created.task.id, taskName: name, prompt: prompts[1], delivery: 'new-session', occurrence: at, scheduledFor: at, startedAt: retainedAt, finishedAt: retainedAt, sessionId, trigger: 'manual', status: 'succeeded' },+ ]+ try {+ await writeFile(path, JSON.stringify({ ...state, records: fixtures }))+ const history = await api<GetApiTauriSchedulerHistoryResponse>(`${HISTORY_PATH}?taskId=${created.task.id}&limit=20`)+ expect(history, 'HTTP 历史必须实际回读两类持久记录夹具,不得 mock 后端').toMatchObject({ ok: true, records: expect.arrayContaining(fixtures), runs: [expect.objectContaining({ id: runId, status: 'succeeded' })] })+ await openCatalog(app)+ const detail = await openTaskDetail(app, name)+ const response = app.page.waitForResponse(value => new URL(value.url()).pathname === HISTORY_PATH && new URL(value.url()).searchParams.get('taskId') === created.task!.id && new URL(value.url()).searchParams.get('limit') === '20')+ await detail.getByRole('tab', { name: '任务运行记录', exact: true }).click()+ expect((await response).status(), '记录切换必须请求真实任务分页').toBe(200)+ const records = detail.getByRole('region', { name: '运行记录', exact: true })+ await expect.poll(() => records.getByRole('listitem').count(), { timeout: 15_000, message: '实际历史字节必须渲染为两个记录项' }).toBe(2)+ const expectedDate = `${now.getUTCMonth() + 1}月${now.getUTCDate()}日 12:34`+ for (const prompt of prompts) {+ const record = records.getByRole('listitem').filter({ hasText: prompt })+ expect(await record.textContent(), '正常记录必须且仅有日期与独立的已发送指令').toBe(`${expectedDate}${prompt}`)+ expect(await record.locator('time').getAttribute('datetime'), '简洁日期必须保留完整准确 UTC 语义').toBe(at)+ expect(await record.getByRole('button', { name: /^打开会话:/ }).isEnabled(), '日期自身必须提供明确且可用的关联会话入口').toBe(true)+ }+ expect(await detail.getByLabel('名称', { exact: true }).isVisible(), '历史记录必须独占视图,不能继续显示任务名称表单').toBe(false)+ expect(await records.getByRole('button', { name: '刷新', exact: true }).count(), '正常记录不得添加无关刷新操作').toBe(0)+ expect(await records.getByRole('button').count(), '正常记录仅允许两处日期跳转入口').toBe(2)+ await captureLayout(app, prefix, 'compact-history')+ }+ finally {+ await writeFile(path, previous)+ }+ })+ })++ it('外部修改后内联旧草稿返回真实 task_conflict 并保留输入不覆盖新数据', async () => {+ await withScratchPage(async (app, prefix) => {+ const name = `${prefix}-conflict`+ const created = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'POST', { name, prompt: '初始指令。', delivery: 'new-session', enabled: false, schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' } } satisfies PostApiTauriSchedulerTasksBody)+ if (!created.ok || !created.task)+ throw new Error('真实 API 必须成功创建冲突测试的暂停任务')+ await openCatalog(app)+ const detail = await openTaskDetail(app, name)+ const remoteName = `${prefix}-external`+ const external = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'PUT', { id: created.task.id, name: remoteName, prompt: '外部新指令。', expected: created.task })+ expect(external, '独立 API 修改必须成功且保留暂停状态').toMatchObject({ ok: true, task: { id: created.task.id, name: remoteName, prompt: '外部新指令。', enabled: false } })+ const localDraft = '这个旧草稿不能覆盖外部已保存的修改。'+ await detail.getByLabel('任务指令', { exact: true }).fill(localDraft)+ const submission = taskResponse(app, 'PUT')+ await detail.getByRole('button', { name: '保存', exact: true }).click()+ const rejected = await submission+ expect(rejected.status(), '过期表单快照必须真实拒绝而不是绕过 expected').toBe(400)+ expect((rejected.request().postDataJSON() as PutApiTauriSchedulerTasksBody).expected, '过期提交必须带编辑时原始完整快照').toEqual(created.task)+ expect(await rejected.json(), '真实路由必须返回 task_conflict').toEqual({ ok: false, error: '任务已发生变化,请刷新后重试', code: 'task_conflict' })+ await expect.poll(() => detail.getByRole('alert').textContent(), { timeout: 15_000, message: '冲突必须在当前表单显示原始原因和安全重开提示' }).toBe('请求失败 (400): 任务已发生变化,请刷新后重试如任务已被修改,请重新打开后编辑。当前草稿不会覆盖新数据。')+ expect(await detail.getByLabel('任务指令', { exact: true }).inputValue(), '冲突后必须保留本地输入').toBe(localDraft)+ expect((await readTasks()).find(task => task.id === created.task?.id), '旧草稿不得覆盖独立 API 保存的新数据').toEqual(external.task)+ await expectNoExecution(created.task.id)+ }, ['CONSOLE Failed to load resource: the server responded with a status of 400 ()'])+ })++ it('主面板保留顶部创建入口且无主 Tabs,内联编辑与全局确认删除后仍显示成功 banner', async () => {+ await withScratchPage(async (app, prefix) => {+ const name = `${prefix}-seed`+ const seeded = await api<PostApiTauriSchedulerTasksResponse>(TASKS_PATH, 'POST', {+ name,+ prompt: '仅种植暂停的新会话任务供真实浏览器编辑。',+ delivery: 'new-session',+ enabled: false,+ schedule: { kind: 'daily', time: '13:17', timeZone: 'UTC' },+ } satisfies PostApiTauriSchedulerTasksBody)+ expect(seeded.ok, '独立 API 种植暂停任务必须成功').toBe(true)+ if (!seeded.task)+ throw new Error('独立 API 未返回种植任务')+ expect(seeded.task, '种植任务必须暂停且只在新会话执行').toMatchObject({ name, delivery: 'new-session', status: 'active', enabled: false })+ const main = await openCatalog(app)+ const heading = main.getByRole('heading', { name: '定时任务', level: 1, exact: true })+ const viaChat = main.getByRole('button', { name: '通过 Chat 创建', exact: true })+ const manual = main.getByRole('button', { name: '手动创建', exact: true })+ const headingBox = await heading.boundingBox()+ const viaChatBox = await viaChat.boundingBox()+ const manualBox = await manual.boundingBox()+ if (!headingBox || !viaChatBox || !manualBox)+ throw new Error('主面板标题与顶部创建入口必须具备可见几何')+ expect(viaChatBox.x, '通过 Chat 创建必须保留在标题右侧').toBeGreaterThan(headingBox.x)+ expect(manualBox.x, '手动创建必须保留在通过 Chat 创建右侧').toBeGreaterThan(viaChatBox.x + viaChatBox.width)+ expect(Math.abs(viaChatBox.y - manualBox.y), '两个创建入口必须保留在同一顶部行').toBeLessThanOrEqual(1)+ expect(Math.abs(manualBox.y - headingBox.y), '创建入口必须与主面板标题顶部对齐').toBeLessThanOrEqual(2)+ expect(await main.getByRole('tablist').count(), '主面板必须直接显示任务列表,不能残留任何页面 Tabs').toBe(0)+ expect(await main.getByLabel('新会话执行', { exact: true }).count(), '全局任务标题不能带箭头投递标识').toBe(0)+ expect(await main.getByRole('button', { name: '全部标记为已读', exact: true }).count(), '主面板不能重现 markAll 控件').toBe(0)+ const menu = main.getByRole('button', { name, exact: true })+ await expect.poll(() => menu.isVisible(), { timeout: 15_000, message: '共享真实 catalog 必须读到 API 种植的暂停任务' }).toBe(true)+ await menu.click()+ await app.frame.getByRole('menuitem', { name: '编辑', exact: true }).click()+ const opened = await inlineDetail(app, name)+ expect(await main.getByRole('heading', { name: '定时任务', level: 1, exact: true }).count(), '菜单编辑必须留在主面板且标题不重复').toBe(1)+ await expect.poll(() => opened.getByLabel('名称', { exact: true }).inputValue(), { timeout: 15_000, message: '编辑必须读取正确的 API 种植任务' }).toBe(name)+ await expectNoExecution(seeded.task.id)+ await opened.getByRole('button', { name: '更多操作', exact: true }).click()+ await app.frame.getByRole('menuitem', { name: '删除', exact: true }).click()+ const confirm = app.frame.getByRole('dialog', { name: '删除', exact: true })+ await expect.poll(() => confirm.isVisible(), { timeout: 15_000, message: '右栏删除必须打开统一的全局确认' }).toBe(true)+ expect(await confirm.getByText('这将永久删除已安排的任务,并停止今后的运行', { exact: true }).count(), '全局确认必须显示删除后果').toBe(1)+ expect(await confirm.getByText(name, { exact: true }).count(), '全局确认必须绑定正确任务').toBe(1)+ expect(await opened.getByRole('dialog', { includeHidden: true }).count(), '确认弹窗不得归属于内联详情的 DOM').toBe(0)+ const removal = taskResponse(app, 'DELETE')+ await confirm.getByRole('button', { name: '删除已安排的任务', exact: true }).click()+ const deletedResponse = await removal+ expect(deletedResponse.status(), '确认后必须调用真实删除路由').toBe(200)+ expect(await deletedResponse.json(), '真实删除响应必须成功').toEqual({ ok: true })+ await expect.poll(() => opened.count(), { timeout: 15_000, message: '删除成功必须关闭源内联任务详情' }).toBe(0)+ expect(await main.getByRole('heading', { name: '定时任务', level: 1, exact: true }).isVisible(), '删除内联详情后仍须保留主任务面板').toBe(true)+ const banner = app.frame.getByRole('alert').filter({ hasText: `已删除定时任务 ${name}` })+ await expect.poll(() => banner.textContent(), { timeout: 15_000, message: '内联详情已关闭后全局 banner 仍必须显示成功反馈' }).toBe(`已删除定时任务 ${name}`)+ expect(await app.frame.getByRole('dialog', { includeHidden: true }).count(), '删除成功必须关闭全局确认').toBe(0)+ expect((await readTasks()).filter(task => task.id === seeded.task?.id), '真实 HTTP 清单不得再含已删除任务').toEqual([])+ })+ })+})diff --git a/test/e2e/plugins/dsh-tauri-scheduler.e2e.ts b/test/e2e/plugins/dsh-tauri-scheduler.e2e.tsindex 9d8d3340..c501987e 100644--- a/test/e2e/plugins/dsh-tauri-scheduler.e2e.ts+++ b/test/e2e/plugins/dsh-tauri-scheduler.e2e.ts@@ -1,20 +1,7 @@-/**- * 批次 08 · `dsh-tauri-scheduler` 宿主路由(契约见 `docs/specs/plugin.test.md`)。- *- * 本批只覆盖只读清单、缺参与落盘形态,**不触发真实执行**:`run_now` 需要模型与网络,- * 归入后续批次。断言对象一律是外部世界(HTTP 状态码、响应字节、`<DSH_HOME>/crons/tasks`- * 账本文件),不采信插件自报;`error` 文案逐字相等,否则「路由在跑」与「路由换了实现」- * 在测试里不可区分。- *- * 复用 globalSetup 的共享宿主(`also` 默认已挂载本插件),不另起进程。唯一会落盘的- * 用例在 `finally` 里删除自建任务并回读清单,绝不把状态留给后续用例与后续批次。- */-import { existsSync, readFileSync } from 'node:fs'import { join } from 'node:path'import { describe, expect, inject, it } from 'vitest'-/** 与 `packages/dsh-tauri-scheduler/src/shared/constants.ts:9` 的 PLUGIN_ID 对齐。 */const SCHEDULER_ROOT = '/api/tauri/scheduler'const TASKS_PATH = `${SCHEDULER_ROOT}/tasks`@@ -23,15 +10,20 @@ const TASKS_RUN_PATH = `${SCHEDULER_ROOT}/tasks/run`const HISTORY_PATH = `${SCHEDULER_ROOT}/history`const OPTIONS_PATH = `${SCHEDULER_ROOT}/options`const RUNS_RECOVER_PATH = `${SCHEDULER_ROOT}/runs/recover`--/** 与 `packages/dsh-tauri-scheduler/src/host/storage/index.ts:4` 的 `base: 'crons'` 对齐。 */const TASKS_LEDGER = join('crons', 'tasks')+const JSON_HEADERS: Record<string, string> = { 'content-type': 'application/json' }interface TaskRecord {id: stringname: stringprompt: stringenabled: boolean+ delivery: 'this-session' | 'new-session'+ status: 'active' | 'inactive'+ schedule: { kind: string, timeZone: string, at?: string }+ createdAt: string+ updatedAt: string+ sessionId?: stringnextRunAt?: string}@@ -45,29 +37,29 @@ interface TasksPayload {error?: string}-interface CreatedPayload {+interface ActionResultPayload {ok?: boolean- task?: TaskRecorderror?: string+ code?: string}-interface HistoryPayload {- runs?: RunRecord[]- error?: string+interface CreatedPayload extends ActionResultPayload {+ task?: TaskRecord}-interface ActionResultPayload {- ok?: boolean- error?: string+interface HistoryPayload extends ActionResultPayload {+ records?: unknown[]+ runs?: RunRecord[]+ nextBefore?: string+ earlierRecordsUnavailable?: boolean+ earlierRecordsPruned?: boolean+ retention?: { days: number, records: number }}-/** `/api/**` 要求浏览器会话;Cookie 由编排在根路径用一次性 token 换得。 */function apiHeaders(extra: Record<string, string> = {}): Record<string, string> {return { cookie: inject('dshCookie'), ...extra }}-const JSON_HEADERS: Record<string, string> = { 'content-type': 'application/json' }-function url(path: string): string {return `${inject('dshBaseUrl')}${path}`}@@ -81,27 +73,42 @@ async function readTasks(search = ''): Promise<TaskRecord[]> {const body = await response.json() as TasksPayloadexpect(Array.isArray(body.tasks), '清单载荷必须带 tasks 数组').toBe(true)expect(body.error, '成功响应不得带 error 字段').toBeUndefined()- return body.tasks ?? []+ if (!Array.isArray(body.tasks))+ throw new Error('任务清单未返回 tasks 数组')+ return body.tasks}async function readRuns(): Promise<RunRecord[]> {- const response = await fetch(url(HISTORY_PATH), { headers: apiHeaders() })+ const response = await fetch(url(`${HISTORY_PATH}?limit=100`), { headers: apiHeaders() })expect(response.status, '执行记录路由必须存在且返回 200').toBe(200)const body = await response.json() as HistoryPayload+ expect(body.ok, '执行记录成功响应必须带 ok:true').toBe(true)expect(Array.isArray(body.runs), '执行记录载荷必须带 runs 数组').toBe(true)- return body.runs ?? []+ if (!Array.isArray(body.runs))+ throw new Error('执行记录未返回 runs 数组')+ return body.runs+}++async function postTask(input: Record<string, unknown>, createdIds: string[]): Promise<{ response: Response, payload: CreatedPayload }> {+ const response = await fetch(url(TASKS_PATH), {+ method: 'POST',+ headers: apiHeaders(JSON_HEADERS),+ body: JSON.stringify(input),+ })+ const payload = await response.json() as CreatedPayload+ if (typeof payload.task?.id === 'string')+ createdIds.push(payload.task.id)+ return { response, payload }}-/** 落盘账本是独立于 HTTP 的第二条通道:清单说创建成功,账本必须真的多出这条。 */function readTasksLedger(): { version?: unknown, tasks?: unknown } {const path = join(inject('dshHome'), TASKS_LEDGER)expect(existsSync(path), `创建成功后账本必须落盘:${path}`).toBe(true)return JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown, tasks?: unknown }}-/** 清理专用:结果不作断言,避免掩盖 try 块里的首个失败。 */async function dropTask(id: string): Promise<void> {await fetch(url(TASKS_PATH), {method: 'DELETE',@@ -110,7 +117,13 @@ async function dropTask(id: string): Promise<void> {})}-const TASK_INPUT = { name: 'e2e-smoke', prompt: 'say hi', schedule: { kind: 'daily', time: '09:00' } }+const TASK_INPUT = {+ delivery: 'new-session',+ name: 'e2e-smoke',+ prompt: 'say hi',+ schedule: { kind: 'once', at: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' },+ enabled: false,+} as constdescribe('L2 宿主路由', () => {it('验证干净环境下任务清单为空', async () => {@@ -123,39 +136,35 @@ describe('L2 宿主路由', () => {expect(body.tasks, '全新 scratch 里任务清单必须恰好为空数组').toEqual([])})- it('验证创建任务后清单与账本一致', async () => {- const requestedAt = Date.now()+ it('验证暂停的新会话任务创建后清单与账本一致', async () => {const createdIds: string[] = []try {- const response = await fetch(url(TASKS_PATH), {- method: 'POST',- headers: apiHeaders(JSON_HEADERS),- body: JSON.stringify(TASK_INPUT),- })+ const { response, payload } = await postTask(TASK_INPUT, createdIds)expect(response.status, '合法入参必须创建成功').toBe(200)-- const payload = await response.json() as CreatedPayloadexpect(payload.ok, '创建响应必须带 ok:true').toBe(true)const created = payload.taskexpect(typeof created?.id, '创建响应必须回传任务 id').toBe('string')- if (typeof created?.id === 'string')- createdIds.push(created.id)-expect(created?.id, '任务 id 必须是 task-<uuid> 形态').toMatch(/^task-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)- expect(- Date.parse(created?.nextRunAt ?? ''),- '创建必须同时算出未来一次的运行时刻',- ).toBeGreaterThan(requestedAt)+ expect(created, '暂停任务保持 active 且保留计划,不产生绑定会话').toMatchObject({+ delivery: 'new-session',+ status: 'active',+ enabled: false,+ name: 'e2e-smoke',+ prompt: 'say hi',+ schedule: { kind: 'once', at: '2030-01-01T12:00:00.000Z', timeZone: 'UTC' },+ nextRunAt: '2030-01-01T12:00:00.000Z',+ })+ expect(created, '新会话任务不得带 sessionId').not.toHaveProperty('sessionId')const searched = await readTasks(TASK_INPUT.name)expect(searched.length, '按名称搜索必须恰好命中 1 条').toBe(1)expect(searched[0]?.id, '搜到的必须是刚创建的那一条').toBe(created?.id)const ledger = readTasksLedger()- expect(ledger.version, '账本版本必须为 1').toBe(1)+ expect(ledger.version, '统一投递账本版本必须为 2').toBe(2)expect(Array.isArray(ledger.tasks), '账本必须带 tasks 数组').toBe(true)const ledgerIds = (ledger.tasks as TaskRecord[]).map(item => item.id).sort()@@ -178,28 +187,183 @@ describe('L2 宿主路由', () => {expect(await readTasks(), '用例收尾后任务清单必须回到空').toEqual([])})- it('[反向] 验证创建任务缺字段返回 400', async () => {- const cases: Array<[string, Record<string, unknown>, string]> = [- ['空对象', {}, '任务名称不能为空'],- ['缺 prompt', { name: 'e2e-invalid', schedule: { kind: 'daily', time: '09:00' } }, '任务指令不能为空'],- ['非法 schedule.kind', { name: 'e2e-invalid', prompt: 'say hi', schedule: { kind: 'nope' } }, '计划配置无效'],- ]+ it('[反向] 验证更新缺少 expected 时拒绝写入并保留完整原记录', async () => {+ const createdIds: string[] = []- for (const [label, body, expected] of cases) {- const response = await fetch(url(TASKS_PATH), {- method: 'POST',+ try {+ const { response, payload } = await postTask({ ...TASK_INPUT, name: 'e2e-missing-expected' }, createdIds)+ expect(response.status, '更新夹具必须创建成功').toBe(200)+ expect(payload.ok, '更新夹具必须返回 ok:true').toBe(true)+ expect(typeof payload.task?.id, '更新夹具必须返回任务 id').toBe('string')+ if (!payload.task)+ throw new Error('更新夹具未返回任务记录')+ const snapshot = structuredClone(payload.task)+ expect(await readTasks(), '更新前清单必须包含创建的完整快照').toEqual([snapshot])++ const update = await fetch(url(TASKS_PATH), {+ method: 'PUT',headers: apiHeaders(JSON_HEADERS),- body: JSON.stringify(body),+ body: JSON.stringify({ id: snapshot.id, name: 'unsafe-no-expected', prompt: 'must not persist', enabled: false }),+ })+ expect(update.status, '有效 id 缺 expected 必须返回 400').toBe(400)+ expect(await update.json(), '缺 expected 必须返回精确领域错误').toEqual({+ ok: false,+ error: '缺少完整 expected 任务记录',+ code: 'task_expected_required',+ })+ expect(await readTasks(), '拒绝缺 expected 更新后所有字段必须保持不变').toEqual([snapshot])+ }+ finally {+ for (const id of createdIds)+ await dropTask(id)+ }++ expect(await readTasks(), '更新缺 expected 用例清理后清单必须为空').toEqual([])+ })++ it('验证并发完整 expected 更新只接受一次且过期快照不能覆盖新记录', async () => {+ const createdIds: string[] = []++ try {+ const { response, payload } = await postTask({ ...TASK_INPUT, name: 'e2e-concurrent-expected' }, createdIds)+ expect(response.status, '并发更新夹具必须创建成功').toBe(200)+ expect(payload.ok, '并发更新夹具必须返回 ok:true').toBe(true)+ expect(typeof payload.task?.id, '并发更新夹具必须返回任务 id').toBe('string')+ if (!payload.task)+ throw new Error('并发更新夹具未返回任务记录')+ const snapshot = structuredClone(payload.task)+ expect(await readTasks(), '并发更新前清单必须与完整 expected 一致').toEqual([snapshot])++ const edits = [+ { name: 'e2e-concurrent-left', prompt: 'left prompt' },+ { name: 'e2e-concurrent-right', prompt: 'right prompt' },+ ]+ const results = await Promise.all(edits.map(async (edit) => {+ const response = await fetch(url(TASKS_PATH), {+ method: 'PUT',+ headers: apiHeaders(JSON_HEADERS),+ body: JSON.stringify({ id: snapshot.id, ...edit, enabled: false, expected: snapshot }),+ })+ return { response, payload: await response.json() as CreatedPayload, edit }+ }))+ expect(results.map(result => result.response.status).sort((left, right) => left - right), '同一完整 expected 的并发写入必须恰好一次成功、一次冲突').toEqual([200, 400])+ const accepted = results.find(result => result.response.status === 200)+ const rejected = results.find(result => result.response.status === 400)+ if (!accepted || !rejected)+ throw new Error('并发更新未产生一条成功和一条冲突响应')+ expect(rejected.payload, '过期完整快照必须返回 task_conflict').toEqual({+ ok: false,+ error: '任务已发生变化,请刷新后重试',+ code: 'task_conflict',+ })+ expect(accepted.payload, '成功响应必须保留暂停计划并完整应用获胜写入').toMatchObject({+ ok: true,+ task: {+ id: snapshot.id,+ ...TASK_INPUT,+ ...accepted.edit,+ status: 'active',+ createdAt: snapshot.createdAt,+ nextRunAt: '2030-01-01T12:00:00.000Z',+ },+ })+ const committed = accepted.payload.task+ if (!committed)+ throw new Error('并发更新成功响应未返回任务记录')+ expect(await readTasks(), '冲突写入不得覆盖或混入获胜任务的字段').toEqual([committed])++ const stale = await fetch(url(TASKS_PATH), {+ method: 'PUT',+ headers: apiHeaders(JSON_HEADERS),+ body: JSON.stringify({ id: snapshot.id, name: 'e2e-stale-overwrite', prompt: 'must not overwrite', enabled: false, expected: snapshot }),+ })+ expect(stale.status, '再提交原始完整快照必须返回 400').toBe(400)+ expect(await stale.json(), '顺序重放的过期快照也必须返回 task_conflict').toEqual({+ ok: false,+ error: '任务已发生变化,请刷新后重试',+ code: 'task_conflict',})+ expect(await readTasks(), '过期快照被拒绝后完整获胜记录必须仍然可回读').toEqual([committed])+ }+ finally {+ for (const id of createdIds)+ await dropTask(id)+ }++ expect(await readTasks(), '并发 expected 用例清理后清单必须为空').toEqual([])+ })- expect(response.status, `${label} 必须 400`).toBe(400)+ it('[反向] 验证原会话投递缺少绑定时拒绝创建且清单不变', async () => {+ const before = await readTasks()+ const createdIds: string[] = []- const payload = await response.json() as CreatedPayload- expect(payload.error, `${label} 的 error 文案必须逐字相等`).toBe(expected)- expect(JSON.stringify(payload), `${label} 不得走到创建成功分支`).not.toContain('"ok":true')+ try {+ const { response, payload } = await postTask({ ...TASK_INPUT, delivery: 'this-session', name: 'e2e-unbound-reminder' }, createdIds)+ expect(response.status, '原会话投递缺少 sessionId 必须返回 400').toBe(400)+ expect(payload, 'HTTP 创建不能从不存在的 initiator 推断会话绑定').toEqual({+ ok: false,+ error: '原会话投递缺少可确认的 sessionId',+ code: 'session_unavailable',+ })+ expect(await readTasks(), '缺绑定的创建不得产生任务或改动已有记录').toEqual(before)+ }+ finally {+ for (const id of createdIds)+ await dropTask(id)+ }+ })++ it('[反向] 验证原会话投递绑定未知会话时拒绝创建且清单不变', async () => {+ const before = await readTasks()+ const createdIds: string[] = []++ try {+ const { response, payload } = await postTask({+ ...TASK_INPUT,+ delivery: 'this-session',+ name: 'e2e-missing-session-reminder',+ sessionId: 'session-e2e-scheduler-does-not-exist',+ }, createdIds)+ expect(response.status, `原会话投递绑定未知 sessionId 必须返回 400;响应体:${JSON.stringify(payload)}`).toBe(400)+ expect(payload, '当前宿主必须冷读确认目标不存在并返回精确领域错误').toEqual({+ ok: false,+ error: '目标会话不存在',+ code: 'session_not_found',+ })+ expect(await readTasks(), '未知会话的创建不得产生任务或改动已有记录').toEqual(before)+ }+ finally {+ for (const id of createdIds)+ await dropTask(id)}+ })++ it('[反向] 验证创建任务缺字段返回 400', async () => {+ const createdIds: string[] = []+ const cases: Array<[string, Record<string, unknown>, string]> = [+ ['缺投递方式', {}, '必须明确选择 delivery:this-session 或 new-session'],+ ['缺名称', { delivery: 'new-session' }, '任务名称不能为空'],+ ['缺 prompt', { delivery: 'new-session', name: 'e2e-invalid', schedule: { kind: 'daily', time: '09:00' } }, '任务指令不能为空'],+ ['非法 schedule.kind', { delivery: 'new-session', name: 'e2e-invalid', prompt: 'say hi', schedule: { kind: 'nope' } }, '计划配置无效'],+ ]- expect(await readTasks(), '被拒绝的创建不得留下半成品').toEqual([])+ try {+ for (const [label, body, expected] of cases) {+ const { response, payload } = await postTask({ ...body, enabled: false }, createdIds)++ expect(response.status, `${label} 必须 400`).toBe(400)+ expect(payload, `${label} 必须返回精确 task_invalid 错误,不得走到创建成功分支`).toEqual({+ ok: false,+ error: expected,+ code: 'task_invalid',+ })+ }+ expect(await readTasks(), '被拒绝的创建不得留下半成品').toEqual([])+ }+ finally {+ for (const id of createdIds)+ await dropTask(id)+ }})it('[反向] 验证删除任务的两类 400 文案可区分', async () => {@@ -217,7 +381,7 @@ describe('L2 宿主路由', () => {body: JSON.stringify({ id: 'task-missing' }),})expect(notFound.status, '任务不存在必须 400,而不是 500(服务内部抛错)').toBe(400)- expect(await notFound.json() as ActionResultPayload, '不存在文案必须逐字相等且与缺参可区分').toEqual({ error: '任务不存在' })+ expect(await notFound.json() as ActionResultPayload, '不存在文案必须逐字相等且与缺参可区分').toEqual({ ok: false, error: '任务不存在', code: 'task_not_found' })expect(await readTasks(), '被拒绝的删除不得改动清单').toEqual([])})@@ -232,7 +396,7 @@ describe('L2 宿主路由', () => {})expect(response.status, '未知任务必须 400').toBe(400)- expect(await response.json() as ActionResultPayload, '不存在文案必须逐字相等').toEqual({ error: '任务不存在' })+ expect(await response.json() as ActionResultPayload, '不存在文案必须逐字相等').toEqual({ ok: false, error: '任务不存在', code: 'task_not_found' })const after = await readRuns()expect(after.length, '被拒绝的立即执行不得写入执行记录').toBe(before.length)@@ -266,7 +430,6 @@ describe('L2 宿主路由', () => {expect(response.status, '选项路由必须存在且返回 200').toBe(200)- // G-SCH-3:字段集尚未纳入事实基线,此处只断言形状,不编造字段名。const body = await response.json() as unknownexpect(body, '选项载荷不得为 null').not.toBeNull()expect(typeof body, '选项载荷必须是对象').toBe('object')@@ -300,15 +463,67 @@ describe('L2 宿主路由', () => {expect(await readTasks(), '被拒的启停不得改动清单').toEqual([])})- it('验证执行记录清单在无记录时为空数组', async () => {- const response = await fetch(url(HISTORY_PATH), { headers: apiHeaders() })+ it.each([+ ['全局', ''],+ ['指定任务', '?taskId=task-e2e-scheduler-history-missing'],+ ])('[反向] 验证%s历史查询缺少显式 limit 返回 400', async (label, query) => {+ const response = await fetch(url(`${HISTORY_PATH}${query}`), { headers: apiHeaders() })++ expect(response.status, `${label}历史查询不得默认为无限量或隐式 limit`).toBe(400)+ expect(await response.json(), `${label}缺 limit 的错误码与文案必须逐字相等`).toEqual({+ ok: false,+ error: 'limit 必须是 1 到 100 的整数',+ code: 'history_invalid_limit',+ })+ })- expect(response.status, '执行记录清单必须可读').toBe(200)+ it.each([+ ['全局', ''],+ ['指定任务', 'taskId=task-e2e-scheduler-history-missing&'],+ ])('[反向] 验证%s历史查询拒绝所有非 1 到 100 整数 limit', async (label, prefix) => {+ for (const limit of ['', '0', '101', '-1', '1.5', '1.0', 'NaN', 'Infinity', '1e2', 'invalid', '2&limit=3']) {+ const response = await fetch(url(`${HISTORY_PATH}?${prefix}limit=${limit}`), { headers: apiHeaders() })++ expect(response.status, `${label} limit=${limit} 必须返回 400`).toBe(400)+ expect(await response.json(), `${label} limit=${limit} 必须返回精确校验错误而非截断或默认分页`).toEqual({+ ok: false,+ error: 'limit 必须是 1 到 100 的整数',+ code: 'history_invalid_limit',+ })+ }+ })- const body = await response.json() as HistoryPayload- expect(Array.isArray(body.runs), '响应体必须带 runs 数组字段').toBe(true)- expect(body.error, '成功路径不得带 error 字段').toBeUndefined()- expect(body.runs, '未执行过任何任务的 scratch 宿主必须恰好为空数组').toEqual([])+ it.each([+ ['全局', ''],+ ['指定任务', 'taskId=task-e2e-scheduler-history-missing&'],+ ])('[反向] 验证%s历史查询的不存在游标返回官方错误码', async (label, prefix) => {+ const response = await fetch(url(`${HISTORY_PATH}?${prefix}limit=20&before=receipt-e2e-scheduler-does-not-exist`), { headers: apiHeaders() })++ expect(response.status, `${label}历史查询不得将未知游标静默重置为第一页`).toBe(400)+ expect(await response.json(), `${label}游标错误必须使用 delivery_cursor_not_found`).toEqual({+ ok: false,+ error: '历史游标不存在或已被清理',+ code: 'delivery_cursor_not_found',+ })+ })++ it.each([+ ['全局最小 limit', '?limit=1'],+ ['全局最大 limit', '?limit=100'],+ ['指定任务最小 limit', '?taskId=task-e2e-scheduler-history-missing&limit=1'],+ ['指定任务最大 limit', '?taskId=task-e2e-scheduler-history-missing&limit=100'],+ ])('验证%s无记录时返回完整空分页与保留策略形状', async (label, query) => {+ const response = await fetch(url(`${HISTORY_PATH}${query}`), { headers: apiHeaders() })++ expect(response.status, `${label}边界值必须可读并返回 200`).toBe(200)+ expect(await response.json(), `${label}空页必须带两类空数组、显式 false 标志和字面量保留策略,不得伪造游标`).toEqual({+ ok: true,+ records: [],+ runs: [],+ earlierRecordsUnavailable: false,+ earlierRecordsPruned: false,+ retention: { days: 30, records: 200 },+ })})it('验证执行记录恢复端点幂等且不改写记录', async () => {diff --git a/test/plugin-patch-targets.test.ts b/test/plugin-patch-targets.test.tsindex 64ece621..791d3cd2 100644--- a/test/plugin-patch-targets.test.ts+++ b/test/plugin-patch-targets.test.ts@@ -11,7 +11,11 @@ import { readSource } from './setup/read-source'* `dsh-tauri-model` 是它的完整 fork、注册同一个 `settings.section/models`,故必须禁用。* 已被核心移除的 `ui-settings-unarchive-sessions` 不得再回到任何 patch 层。*/-const OFFICIAL_ROW_DISABLES = ['dsh-tauri-model → ui-settings-models']+const OFFICIAL_ROW_DISABLES = [+ 'dsh-tauri-model → ui-settings-models',+ 'dsh-tauri-scheduler → schedule',+ 'dsh-tauri-scheduler → ui-schedule',+]const PACKAGES_ROOT = new URL('../packages/', import.meta.url)@@ -35,6 +39,13 @@ function disabledRowIds(source: string): string[] {}describe('插件 patch 层的官方目标', () => {+ it('定时任务插件明确禁用完整官方调度栈且插入唯一实现', () => {+ const source = readPatchLayer('dsh-tauri-scheduler')+ expect(source).toMatch(/^- id: schedule\r?\n {2}disabled: true$/m)+ expect(source).toMatch(/^- id: ui-schedule\r?\n {2}disabled: true$/m)+ expect(source.match(/name: dsh-tauri-scheduler/g)).toHaveLength(1)+ })+it('只把核心仍在提供的官方入口列为 patch 目标', () => {const actual = packageNames().flatMap(pkg => disabledRowIds(readPatchLayer(pkg)).map(id => `${pkg} → ${id}`))diff --git a/test/setup/primitives-optional-deps.ts b/test/setup/primitives-optional-deps.tsnew file mode 100644index 00000000..925d8ec0--- /dev/null+++ b/test/setup/primitives-optional-deps.ts@@ -0,0 +1,53 @@+// Published ui-primitives keeps these optional renderer imports in devDependencies; picker tests never render them.+function unavailable(): never {+ throw new Error('Optional primitive renderer is outside the picker test contract')+}++export function createCssVariablesTheme(options: unknown): unknown {+ return options+}++export const createJavaScriptRegexEngine = () => ({})+export function createHighlighterCoreSync() {+ return { codeToTokens: (_code: string, options: { tokenizeTimeLimit?: number }) => options.tokenizeTimeLimit === 0 ? { tokens: [] } : unavailable() }+}+export const defaultJavaScriptRegexConstructor = unavailable+export const languageForPath = unavailable+export const CODE_HIGHLIGHT_EXTENSIONS = []+export default { ansiToJson: unavailable }++const glyph = { path: '', title: 'Unavailable optional site glyph' }+export const siAliexpress = glyph+export const siApple = glyph+export const siBaidu = glyph+export const siBilibili = glyph+export const siCsdn = glyph+export const siDuckduckgo = glyph+export const siEbay = glyph+export const siFacebook = glyph+export const siGithub = glyph+export const siGitlab = glyph+export const siGoogle = glyph+export const siInstagram = glyph+export const siJuejin = glyph+export const siMdnwebdocs = glyph+export const siNetflix = glyph+export const siNpm = glyph+export const siPypi = glyph+export const siQq = glyph+export const siQuora = glyph+export const siReddit = glyph+export const siSinaweibo = glyph+export const siSpotify = glyph+export const siStackoverflow = glyph+export const siTaobao = glyph+export const siTelegram = glyph+export const siTiktok = glyph+export const siV2ex = glyph+export const siWechat = glyph+export const siWhatsapp = glyph+export const siWikipedia = glyph+export const siX = glyph+export const siYcombinator = glyph+export const siYoutube = glyph+export const siZhihu = glyphdiff --git a/test/tooling-config.test.ts b/test/tooling-config.test.tsindex 4f57b9e3..85b9e816 100644--- a/test/tooling-config.test.ts+++ b/test/tooling-config.test.ts@@ -30,8 +30,14 @@ describe('tooling configuration contracts', () => {const source = path.join(root, 'src')expect(vite.resolve.alias).toContainEqual({ find: '@', replacement: source })expect(rootConfig.resolve?.alias).toEqual({ '@': source })+ const rendererDependency = path.join(root, 'test/setup/primitives-optional-deps.ts')+ const rendererAliases = Object.fromEntries([+ ...'simple-icons anser shiki/core shiki/engine/javascript @deepseek-ai/dsh-util-code-language'.split(' '),+ ...'typescript shellscript json python ruby go rust java c cpp csharp kotlin swift php yaml toml ini markdown mdx html css scss less sql xml lua bat powershell fish dotenv log csv diff http rst latex bibtex asciidoc r julia dart scala clojure erlang elixir haskell fsharp vb perl verilog system-verilog graphql proto hcl nix vue svelte make cmake groovy'.split(' ').map(language => `@shikijs/langs/${language}`),+ ].map(name => [name, rendererDependency]))expect(unitConfig.resolve?.alias).toEqual({'@': source,+ ...rendererAliases,'dsh-tauri/client': path.join(root, 'packages/dsh-tauri/src/client/index.ts'),'dsh-tauri': path.join(root, 'packages/dsh-tauri/src/index.ts'),'dsh-tauri-ui/client': path.join(root, 'packages/dsh-tauri-ui/src/client/index.ts'),@@ -45,6 +51,7 @@ describe('tooling configuration contracts', () => {it('each project retains its distinct setup, scheduling and timeout envelope', () => {expect(unitConfig.test).toEqual({name: 'unit',+ server: { deps: { inline: ['@deepseek-ai/dsh-client-ui-primitives'] } },include: ['packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}', 'test/**/*.test.ts', 'src/**/*.test.{ts,tsx}'],exclude: ['**/node_modules/**',diff --git a/vitest.unit.config.ts b/vitest.unit.config.tsindex 887a1b9a..3144d095 100644--- a/vitest.unit.config.ts+++ b/vitest.unit.config.ts@@ -2,10 +2,17 @@ import { fileURLToPath } from 'node:url'import { defineProject } from 'vitest/config'import { SHARED_ALIAS } from './tooling.config'+const optionalPrimitiveDependency = fileURLToPath(new URL('./test/setup/primitives-optional-deps.ts', import.meta.url))+const optionalPrimitiveAliases = Object.fromEntries([+ ...'simple-icons anser shiki/core shiki/engine/javascript @deepseek-ai/dsh-util-code-language'.split(' '),+ ...'typescript shellscript json python ruby go rust java c cpp csharp kotlin swift php yaml toml ini markdown mdx html css scss less sql xml lua bat powershell fish dotenv log csv diff http rst latex bibtex asciidoc r julia dart scala clojure erlang elixir haskell fsharp vb perl verilog system-verilog graphql proto hcl nix vue svelte make cmake groovy'.split(' ').map(language => `@shikijs/langs/${language}`),+].map(name => [name, optionalPrimitiveDependency]))+export default defineProject({resolve: {alias: {...SHARED_ALIAS,+ ...optionalPrimitiveAliases,'dsh-tauri/client': fileURLToPath(new URL('./packages/dsh-tauri/src/client/index.ts', import.meta.url)),'dsh-tauri': fileURLToPath(new URL('./packages/dsh-tauri/src/index.ts', import.meta.url)),'dsh-tauri-ui/client': fileURLToPath(new URL('./packages/dsh-tauri-ui/src/client/index.ts', import.meta.url)),@@ -14,6 +21,9 @@ export default defineProject({},test: {name: 'unit',+ server: {+ deps: { inline: ['@deepseek-ai/dsh-client-ui-primitives'] },+ },include: ['packages/**/*.{test,spec}.{ts,tsx,js,mjs,cjs}','test/**/*.test.ts',