Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

chore(plugins): simplify scheduler and context-menu internals (#816)

Mao Mr91bf3372840d
diff --git a/docs/audit/pkg-ssh-scheduler-notify-rightclick.md b/docs/audit/pkg-ssh-scheduler-notify-rightclick.md
index b3dd6ac1..8a84c785 100644
--- a/docs/audit/pkg-ssh-scheduler-notify-rightclick.md
+++ b/docs/audit/pkg-ssh-scheduler-notify-rightclick.md
@@ -73,3 +73,14 @@ rightclick 小计:**-10 行**(2 条),另 -2 deps。
- 另:`packages/dsh-tauri-ssh/package.json` 把 `yaml`(被 `host/service/allowlist.ts:21` 运行时 import)声明在 `catalog:testing` 分组——这是依赖归属问题,不是行数问题,交给 `dependencies.md` 口径处理。
net: -452 lines, -4 deps possible.
+
+## scheduler / notification / rightclick 执行复核(2026-09-30)
+
+以下结论覆盖原审计的对应建议;SSH 单独提交,不混入此批次。
+
+- 已执行:删除 notification 的写后不读变量 `statusAttached`;scheduler 私有 `merge` 就地调用 `defaults({}, patch, current)`,恢复扫描改用原生数组过滤;删除仅内部消费的 `useScheduler`、恒等 `schedulerSessionTitle`、`isTaskPaused`,并将 `PrefillState` 就地声明。
+- 已执行:rightclick 的 URL 协议白名单、扩展可见性过滤与会话排除改用原生数组/Set,保留顺序、重复项、不修改快照和 `visible(...) !== false`;宿主 URL 入口仍由 `safeWebUrl` 校验。
+- `keep:` 持久化/线上的 `SchedulerTask.module`、`agentPreset`、notification 结构字段、rightclick 类型别名及路由/事件出口。已有配置的 agent preset 仍可覆盖默认值,不因 UI 无写入口删掉协议字段。
+- `keep:` scheduler DTO 的接口与 readonly 约束、公开 recommendation.form 和 locale 词典;hydrate 注册仍承载生命周期,入口规范禁止把初始化请求移到 client entry。
+- `keep:` lodash 的深比较、默认值合并、形状校验及其余仍使用的方法与依赖。`Object.is` 不等价于 `isEqual`,对象展开不等价于跳过 undefined 的 `defaults`;原 -4 deps 预估不作为本次结果。
+- 验证:新增任务更新/恢复与快照顺序回归;三包 22 文件 / 203 用例连续六次乱序通过,深比较变异被测试拒绝。合并内部包装精简后,与 UI/extension 一起运行 52 文件 / 386 用例通过,限定源码别名类型检查通过,Lint 零错误。
diff --git a/packages/dsh-tauri-notification/src/client/register/notify.ts b/packages/dsh-tauri-notification/src/client/register/notify.ts
index 2841c7d2..47be728e 100644
--- a/packages/dsh-tauri-notification/src/client/register/notify.ts
+++ b/packages/dsh-tauri-notification/src/client/register/notify.ts
@@ -336,7 +336,6 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
}
// `uiSession` 的注册时机不由本插件决定,最多等 5 秒;等到了就订阅,等不到则维持列表兜底。
- let statusAttached = false
let statusAttempts = 0
const attachStatus = (): void => {
const source = readUiSession()?.sessionStatus
@@ -347,10 +346,8 @@ export const notifyFeature = defineRegister<ClientContext>((controller, ctx, ada
}
return
}
- statusAttached = true
controller.add(source.subscribe(observe))
observe()
}
attachStatus()
- void statusAttached
})
diff --git a/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
index 988f80cf..fa8f22e4 100644
--- a/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
+++ b/packages/dsh-tauri-rightclick/src/client/register/context-menu.menu.ts
@@ -6,7 +6,6 @@ import type {
WorkspaceViewLike,
} from '../types'
import type { MenuComposer } from './context-menu.types'
-import { reject } from 'dsh-tauri/client'
import { confirmDialog } from '../components/confirm-dialog'
import { locale } from '../locales'
import {
@@ -119,7 +118,7 @@ export function buildSessionMenu(
})
const visible = current
- ? reject(extensions, entry => entry.visible?.({ session: current, row }) === false)
+ ? extensions.filter(entry => entry.visible?.({ session: current, row }) !== false)
: []
if (visible.length) {
composer.split()
diff --git a/packages/dsh-tauri-rightclick/src/client/service/menu.test.ts b/packages/dsh-tauri-rightclick/src/client/service/menu.test.ts
index 0445a490..18f0d2d0 100644
--- a/packages/dsh-tauri-rightclick/src/client/service/menu.test.ts
+++ b/packages/dsh-tauri-rightclick/src/client/service/menu.test.ts
@@ -235,6 +235,17 @@ describe('loadUngroupedSessions', () => {
})
describe('loadWorkspaceSessions', () => {
+ it('preserves order and duplicates without mutating either snapshot', async () => {
+ const sessionIds = [sid('b'), sid('a'), sid('b'), sid('archived')]
+ const archivedSessionIds = [sid('archived')]
+ const workspaces = { list: { getSnapshot: () => ({ archivedSessionIds }) } } as unknown as WorkspacesRuntimeLike
+ const workspace = { sessionIds } as unknown as WorkspaceViewLike
+
+ await expect(loadWorkspaceSessions({ workspaces, workspace })).resolves.toEqual(['b', 'a', 'b'])
+ expect(sessionIds).toEqual(['b', 'a', 'b', 'archived'])
+ expect(archivedSessionIds).toEqual(['archived'])
+ })
+
it('removes archived sessions from the workspace listing', async () => {
const workspaces = {
list: { getSnapshot: () => ({ items: [], archivedSessionIds: ['s2'] }) },
diff --git a/packages/dsh-tauri-rightclick/src/client/service/menu.ts b/packages/dsh-tauri-rightclick/src/client/service/menu.ts
index 32d82bfe..212282d7 100644
--- a/packages/dsh-tauri-rightclick/src/client/service/menu.ts
+++ b/packages/dsh-tauri-rightclick/src/client/service/menu.ts
@@ -6,7 +6,7 @@ import type {
WorkspacesRuntimeLike,
WorkspaceViewLike,
} from '../types'
-import { difference, filter, get } from 'dsh-tauri/client'
+import { get } from 'dsh-tauri/client'
import { postOpenPath, postOpenUrl } from '../apis'
import { locale } from '../locales'
import { externalUrl } from '../utils/url'
@@ -131,10 +131,8 @@ export async function loadUngroupedSessions(input: {
const snapshot = input.workspaces.list.getSnapshot()
const assigned = snapshot.items.flatMap(workspace => workspace.sessionIds)
const sessionSnapshot = input.sessions.list.getSnapshot()
- return filter(
- difference(sessionSnapshot.ids, assigned, snapshot.archivedSessionIds),
- id => sessionSnapshot.byId[id]?.blank !== true,
- )
+ const excluded = new Set([...assigned, ...snapshot.archivedSessionIds])
+ return sessionSnapshot.ids.filter(id => !excluded.has(id) && sessionSnapshot.byId[id]?.blank !== true)
}
/** Query:工作区中尚未归档的会话 id。 */
@@ -142,7 +140,8 @@ export async function loadWorkspaceSessions(input: {
workspaces: WorkspacesRuntimeLike
workspace: WorkspaceViewLike
}): Promise<SessionId[]> {
- return difference(input.workspace.sessionIds, input.workspaces.list.getSnapshot().archivedSessionIds)
+ const archived = new Set(input.workspaces.list.getSnapshot().archivedSessionIds)
+ return input.workspace.sessionIds.filter(id => !archived.has(id))
}
/** Action:逐个归档会话。 */
diff --git a/packages/dsh-tauri-rightclick/src/client/utils/url.ts b/packages/dsh-tauri-rightclick/src/client/utils/url.ts
index b5a50327..f679d625 100644
--- a/packages/dsh-tauri-rightclick/src/client/utils/url.ts
+++ b/packages/dsh-tauri-rightclick/src/client/utils/url.ts
@@ -1,10 +1,8 @@
-import { includes } from 'dsh-tauri/client'
-
/** 只接受 http/https 的 URL 校验(用于外链打开 / 选中文本里的网址)。 */
export function externalUrl(value: string): string | null {
try {
const url = new URL(value)
- return includes(['http:', 'https:'], url.protocol) ? url.href : null
+ return ['http:', 'https:'].includes(url.protocol) ? url.href : null
}
catch {
return null
diff --git a/packages/dsh-tauri-rightclick/src/host/routes/open/url/post.ts b/packages/dsh-tauri-rightclick/src/host/routes/open/url/post.ts
index 8805821c..84c673d2 100644
--- a/packages/dsh-tauri-rightclick/src/host/routes/open/url/post.ts
+++ b/packages/dsh-tauri-rightclick/src/host/routes/open/url/post.ts
@@ -1,7 +1,6 @@
import type { EventHandlerRequest } from 'dsh-tauri'
import type { OperationResult } from '../../../types'
import { defineEventHandler, readBody, safeWebUrl } from 'dsh-tauri'
-import { get } from 'lodash-es'
import { JSON_CONTENT_TYPE } from '../../../config/constants'
import { opener } from '../../../service/opener'
@@ -13,7 +12,7 @@ export default defineEventHandler<EventHandlerRequest, Promise<OperationResult>>
}
const body = await readBody<{ url?: string }>(event, { type: 'json' })
- const url = safeWebUrl(get(body, 'url'))
+ const url = safeWebUrl(body?.url)
if (!url) {
event.res.status = 400
return { ok: false as const, error: 'invalid-url' }
diff --git a/packages/dsh-tauri-scheduler/src/client/components/schedule.utils.ts b/packages/dsh-tauri-scheduler/src/client/components/schedule.utils.ts
index bc03e067..96d1cf9f 100644
--- a/packages/dsh-tauri-scheduler/src/client/components/schedule.utils.ts
+++ b/packages/dsh-tauri-scheduler/src/client/components/schedule.utils.ts
@@ -58,10 +58,6 @@ export function formatRelative(iso: string | undefined, now: number, t: Translat
return `${days}${t('unitDays')}`
}
-export function isTaskPaused(task: { enabled: boolean }): boolean {
- return !task.enabled
-}
-
/**
* 未播种(`readAt === 0`)一律按已读处理,避免首屏闪出一片未读角标。
*
diff --git a/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx
index 7b887ecc..7b17550d 100644
--- a/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx
+++ b/packages/dsh-tauri-scheduler/src/client/components/scheduler-panel.tsx
@@ -2,15 +2,14 @@ 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 } from 'dsh-tauri/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 { useScheduler } from '../hooks/use-scheduler'
import { deleteRun, loadScheduler } from '../service/scheduler'
import { store } from '../store'
import { Recommendations } from './recommendations'
import { RunsTab } from './runs-tab'
-import { countUnreadRuns, describeSchedule, formatRelative, isTaskPaused } from './schedule.utils'
+import { countUnreadRuns, describeSchedule, formatRelative } from './schedule.utils'
import { TaskCard } from './task-card'
import { TaskCreateDialog } from './task-create-dialog'
@@ -38,7 +37,7 @@ function taskToForm(task: TaskView): TaskFormState {
}
export function SchedulerPanel({ t, onViaChat, onOpenSession }: SchedulerPanelProps): ReactElement {
- const state = useScheduler()
+ const state = useStore(store.scheduler)
const [tab, setTab] = useState<'tasks' | 'runs'>('tasks')
const [search, setSearch] = useState('')
const [dialog, setDialog] = useState<DialogState>(null)
@@ -158,7 +157,7 @@ export function SchedulerPanel({ t, onViaChat, onOpenSession }: SchedulerPanelPr
t={t}
describe={describeSchedule(task.schedule, t)}
nextRun={task.enabled ? formatRelative(task.nextRunAt, now, t) : undefined}
- paused={isTaskPaused(task)}
+ paused={!task.enabled}
onEdit={task => setDialog({ taskId: task.id, initial: taskToForm(task) })}
/>
))}
diff --git a/packages/dsh-tauri-scheduler/src/client/hooks/use-scheduler.ts b/packages/dsh-tauri-scheduler/src/client/hooks/use-scheduler.ts
deleted file mode 100644
index 08bd672a..00000000
--- a/packages/dsh-tauri-scheduler/src/client/hooks/use-scheduler.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { useStore } from 'dsh-tauri/client'
-import { store } from '../store'
-
-export function useScheduler() {
- return useStore(store.scheduler)
-}
diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.ts
index 8a18019a..252809a3 100644
--- a/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.ts
+++ b/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.ts
@@ -1,6 +1,9 @@
-import type { PrefillState } from './prefill.types'
import { defineStore } from 'dsh-tauri/client'
+interface PrefillState {
+ pending: string
+}
+
export const prefill = defineStore({
state: (): PrefillState => ({ pending: '' }),
actions: {
diff --git a/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.types.ts b/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.types.ts
deleted file mode 100644
index b4cea87c..00000000
--- a/packages/dsh-tauri-scheduler/src/client/store/modules/prefill.types.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export interface PrefillState {
- pending: string
-}
diff --git a/packages/dsh-tauri-scheduler/src/host/service/executor.ts b/packages/dsh-tauri-scheduler/src/host/service/executor.ts
index 43bfff1c..af985042 100644
--- a/packages/dsh-tauri-scheduler/src/host/service/executor.ts
+++ b/packages/dsh-tauri-scheduler/src/host/service/executor.ts
@@ -15,7 +15,6 @@ import { join } from 'pathe'
import { getCurrentHostInstance } from '../config/runtime'
import { loadSchedulerRuntimeModules, resolveSetupAgent } from '../utils/agent-runtime'
import { applyUnattendedPermission } from '../utils/permission'
-import { schedulerSessionTitle } from '../utils/session-title'
import { decideRunOutcome, isPluginUnloadError, summarizeCollectedRun, waitForTurnStart, watchSessionEvents } from './executor.utils'
import { runs } from './runs'
@@ -234,7 +233,7 @@ async function createAgent(
async function pinTitle(ctx: HostContext, session: unknown, taskName: string): Promise<void> {
try {
const title = ctx.get?.('sessionTitle') as { rename?: (target: unknown, value: string) => unknown } | undefined
- title?.rename?.(session, schedulerSessionTitle(taskName))
+ title?.rename?.(session, taskName)
}
catch (error) {
ctx.logger?.warn?.(`dsh-tauri-scheduler: failed to pin session title: ${error instanceof Error ? error.message : String(error)}`)
diff --git a/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts b/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts
new file mode 100644
index 00000000..cefb7671
--- /dev/null
+++ b/packages/dsh-tauri-scheduler/src/host/service/recovery.test.ts
@@ -0,0 +1,17 @@
+import { beforeEach, expect, it, vi } from 'vitest'
+import { recovery } from './recovery'
+import { runs } from './runs'
+
+vi.mock('./runs', () => ({ runs: { list: vi.fn(), save: vi.fn() } }))
+
+beforeEach(() => vi.clearAllMocks())
+
+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)
+ 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')
+})
diff --git a/packages/dsh-tauri-scheduler/src/host/service/recovery.ts b/packages/dsh-tauri-scheduler/src/host/service/recovery.ts
index 0e23df6e..54c2902a 100644
--- a/packages/dsh-tauri-scheduler/src/host/service/recovery.ts
+++ b/packages/dsh-tauri-scheduler/src/host/service/recovery.ts
@@ -1,12 +1,11 @@
import { defineService } from 'dsh-tauri'
-import { filter } from 'lodash-es'
import { runs } from './runs'
const SCHEDULER_INTERRUPTED_ERROR = 'host_interrupted'
export const recovery = defineService({
async recover(): Promise<void> {
- for (const run of filter(await runs.list(), { status: 'running' })) {
+ for (const run of (await runs.list()).filter(run => run.status === 'running')) {
await runs.save({
...run,
status: 'interrupted',
diff --git a/packages/dsh-tauri-scheduler/src/host/service/task.test.ts b/packages/dsh-tauri-scheduler/src/host/service/task.test.ts
new file mode 100644
index 00000000..b2af5a90
--- /dev/null
+++ b/packages/dsh-tauri-scheduler/src/host/service/task.test.ts
@@ -0,0 +1,58 @@
+import type { SchedulerTask } from '../types'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { storage } from '../storage'
+import { task } from './task'
+
+vi.mock('../storage', () => ({ storage: { getItem: vi.fn(), setItem: vi.fn() } }))
+
+const current: SchedulerTask = {
+ id: 'task-1',
+ name: 'existing',
+ prompt: 'run it',
+ schedule: { kind: 'weekly', weekdays: ['FR'], time: '16:00', timeZone: 'UTC' },
+ enabled: false,
+ permission: 'read-only',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ nextRunAt: '2026-02-06T16:00:00.000Z',
+ module: 'legacy-module',
+ agentPreset: 'custom-preset',
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-01-02T00:00:00.000Z'))
+ vi.mocked(storage.getItem).mockResolvedValue({ tasks: [structuredClone(current)] })
+})
+
+afterEach(() => vi.useRealTimers())
+
+describe('task storage and update', () => {
+ it('reads persisted protocol fields without pruning them', async () => {
+ expect(await task.get(current.id)).toEqual(current)
+ })
+
+ it('defaults undefined patches without mutating the caller and keeps deep-equal schedules', 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(patch).toEqual({ name: undefined, permission: undefined, schedule: current.schedule })
+ expect(storage.setItem).toHaveBeenCalledWith('tasks', expect.stringContaining(current.nextRunAt!))
+ })
+
+ 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.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 })
+ expect(storage.setItem).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: '任务名称不能为空' })
+ expect(storage.setItem).not.toHaveBeenCalled()
+ })
+})
diff --git a/packages/dsh-tauri-scheduler/src/host/service/task.ts b/packages/dsh-tauri-scheduler/src/host/service/task.ts
index a787df41..72b396ed 100644
--- a/packages/dsh-tauri-scheduler/src/host/service/task.ts
+++ b/packages/dsh-tauri-scheduler/src/host/service/task.ts
@@ -36,7 +36,7 @@ export const task = defineService({
const current = await findTask(id)
if (current === null)
return { ok: false, error: '任务不存在' }
- const merged = merge(current, patch)
+ const merged: TaskInput = defaults({}, patch, current)
const invalid = validateInput(merged)
if (invalid !== null)
return { ok: false, error: invalid }
@@ -158,10 +158,6 @@ function build(input: TaskInput): SchedulerTask {
}
}
-function merge(current: SchedulerTask, patch: Partial<TaskInput>): TaskInput {
- return defaults({}, patch, current)
-}
-
function validateInput(input: unknown): string | null {
if (!isObject(input))
return '请求体必须是对象'
diff --git a/packages/dsh-tauri-scheduler/src/host/utils/session-title.ts b/packages/dsh-tauri-scheduler/src/host/utils/session-title.ts
deleted file mode 100644
index adc3c161..00000000
--- a/packages/dsh-tauri-scheduler/src/host/utils/session-title.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export function schedulerSessionTitle(taskName: string): string {
- return taskName
-}