feat(schedule): unify task creation and editing (#7567)
* feat(schedule): unify task creation and editing * refactor(schedule): remove obsolete editor helper exports * fix(schedule): address unified editor review * fix(schedule): avoid a conflict notice during save refresh * test(schedule): use unified editor in zoom picker checks * fix(schedule): preserve drafts through conflict recovery * docs(schedule): match the linked-session control labels * fix(schedule): restore the latest linked session after conflicts * docs(schedule): clarify unsaved draft lifetime * fix(schedule): align conflict feedback with the detail layout * fix(schedule): fit editors to pane width and guide empty fields * fix(schedule): preserve task list and complete field examples * fix(schedule): keep required-field feedback in the editor * fix(schedule): align editor content and action gutters * fix(schedule): wrap localized actions in narrow editors
This commit is contained in:
1 parent
516ca64acb
commit
d9ed1e4e28
25 files changed
+1205
-444
No files matched your search
@@ -672,7 +672,6 @@ describe.skipIf(MODE === 'record')('web e2e: conversational reminders', () => {
|
||||
}
|
||||
expect(await detail.getByRole('tab', { name: 'Records', exact: true }).getAttribute('aria-selected')).toBe('true')
|
||||
await detail.getByRole('tab', { name: 'Rules', exact: true }).click()
|
||||
await detail.getByRole('button', { name: 'Edit', exact: true }).click()
|
||||
await detail.getByRole('button', { name: /^Repeat / }).click()
|
||||
await page.getByRole('menuitem', { name: 'Every N hours', exact: true }).click()
|
||||
const interval = detail.getByLabel('Interval', { exact: true })
|
||||
@@ -1251,9 +1250,8 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
|
||||
expect(await row.textContent()).toContain(frequency)
|
||||
await row.click()
|
||||
const detail = manager.getByRole('complementary', { name: 'Task details' })
|
||||
expect(await detail.getByText(frequency, { exact: true }).count()).toBe(1)
|
||||
expect(await detail.getByRole('button', { name: /^Repeat / }).textContent()).toContain('Every day')
|
||||
expect(await detail.getByText('Once', { exact: true }).count()).toBe(0)
|
||||
await detail.getByRole('button', { name: 'Edit', exact: true }).click()
|
||||
const runTime = detail.getByRole('region', { name: 'Run time', exact: true })
|
||||
const timeField = runTime.getByRole('button', { name: 'Time', exact: true })
|
||||
// The Time zone row is a menu trigger button; the zone is chosen, never typed.
|
||||
@@ -1281,7 +1279,7 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
|
||||
})
|
||||
expect(rruleOf(saved)).toContain('BYHOUR=12;BYMINUTE=34')
|
||||
// A stored zone equal to the browser zone is omitted from the frequency line.
|
||||
await expect.poll(() => detail.getByText('Daily at 12:34', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
|
||||
await expect.poll(() => row.textContent(), { timeout: 15_000 }).toContain('Daily at 12:34')
|
||||
expect(await scaffold.ctx.schedule.history({ id: created.id, limit: 20 }))
|
||||
.toEqual({ id: created.id, records: [], earlierRecordsUnavailable: false,
|
||||
earlierRecordsPruned: false, retention: { days: 30, records: 200 } })
|
||||
@@ -1296,6 +1294,39 @@ describe.skipIf(MODE === 'record')('web e2e: active Schedule catalog', () => {
|
||||
}
|
||||
}, 60_000)
|
||||
|
||||
it('restores the latest linked Session after reviewing a concurrent destination change', async () => {
|
||||
const before = SessionId('schedule-destination-before')
|
||||
const after = SessionId('schedule-destination-after')
|
||||
const fixture = await readFile(CATALOG_FIXTURE, 'utf8')
|
||||
for (const id of [before, after]) await seedSession(scaffold, fixture, id, 'standard')
|
||||
const created = await scaffold.ctx.schedule.create({ title: 'Destination recovery', prompt: 'Review the destination',
|
||||
timing: { kind: 'at', at: '2099-09-01T12:00:00.000Z' }, target: { kind: 'session', sessionId: before } })
|
||||
try {
|
||||
await page.getByRole('button', { name: 'Automation tasks', exact: true }).click()
|
||||
const manager = page.getByTestId('task-manager-page')
|
||||
await manager.getByRole('searchbox', { name: 'Search tasks' }).fill('')
|
||||
await manager.getByRole('button', { name: 'All', exact: true }).click()
|
||||
await manager.getByRole('button', { name: 'Destination recovery', exact: true }).click()
|
||||
const detail = manager.getByRole('complementary')
|
||||
await detail.getByRole('textbox', { name: 'Automation task name', exact: true }).fill('Recovered destination')
|
||||
await detail.getByRole('button', { name: /^Run in / }).click()
|
||||
await page.getByRole('menuitem', { name: /^Create a session and reuse it/ }).click()
|
||||
const remote = await scaffold.ctx.schedule.edit({ id: created.id, action: 'update', expectedUpdatedAt: created.updatedAt ?? null,
|
||||
patch: { target: { kind: 'session', sessionId: after } } })
|
||||
expect(remote).toMatchObject({ target: { kind: 'session', sessionId: after } })
|
||||
await detail.getByRole('button', { name: 'Review with my edits', exact: true }).click()
|
||||
await detail.getByRole('button', { name: /^Run in / }).click()
|
||||
await page.getByRole('menuitem', { name: 'Current linked session', exact: true }).click()
|
||||
await detail.getByRole('button', { name: 'Save changes', exact: true }).click()
|
||||
await detail.getByRole('heading', { name: 'Recovered destination', exact: true }).waitFor()
|
||||
expect(await scaffold.ctx.schedule.view({ id: created.id }))
|
||||
.toMatchObject({ title: 'Recovered destination', target: { kind: 'session', sessionId: after } })
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
} finally {
|
||||
await scaffold.ctx.schedule.edit({ id: created.id, action: 'delete' })
|
||||
}
|
||||
})
|
||||
|
||||
it('removes every ended task from the page and keeps the active ones', async () => {
|
||||
onTestFailed(() => saveFailureShot(page, 'web-e2e-schedule-clear-ended'))
|
||||
const endedSession = SessionId('schedule-manager-ended-clear')
|
||||
|
||||
@@ -30,8 +30,10 @@ it('creates from a paused empty state, selects the task, and saves an inline edi
|
||||
await page.getByRole('menuitem', { name: '手动创建', exact: true }).waitFor()
|
||||
await page.keyboard.press('Escape')
|
||||
await manager.getByRole('button', { name: '新建自动化任务', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '手动创建', exact: true })
|
||||
const dialog = manager.getByRole('complementary', { name: '手动创建', exact: true })
|
||||
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('AI 新闻简报')
|
||||
expect(await dialog.getByRole('status').count()).toBe(0)
|
||||
expect(await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).getAttribute('aria-required')).toBe('true')
|
||||
await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接。')
|
||||
await dialog.getByRole('button', { name: /^重复 / }).click()
|
||||
await page.getByRole('menuitem', { name: '周一至周五', exact: true }).click()
|
||||
@@ -62,14 +64,60 @@ it('creates from a paused empty state, selects the task, and saves an inline edi
|
||||
const task = (await scaffold.ctx.schedule.catalog()).find(task => task.title === 'AI 新闻简报')
|
||||
if (task === undefined || task.target.kind !== 'new_once') throw new Error('manual task was not created with the reusable target')
|
||||
expect(task.target.create.cwd).toBe(defaultPath)
|
||||
await detail.getByRole('button', { name: '编辑', exact: true }).click()
|
||||
expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
|
||||
expect(await detail.getByRole('button', { name: '暂停任务', exact: true }).isDisabled()).toBe(true)
|
||||
await manager.getByRole('button', { name: '关闭详情', exact: true }).click()
|
||||
await manager.getByRole('list', { name: '任务列表', exact: true }).getByRole('button', { name: task.title, exact: true }).click()
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue())
|
||||
.toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
|
||||
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
|
||||
await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).waitFor({ state: 'detached' })
|
||||
await detail.getByText('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。', { exact: true }).waitFor()
|
||||
await expect.poll(() => detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue())
|
||||
.toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
|
||||
const saved = await scaffold.ctx.schedule.view({ id: task.id })
|
||||
if ('code' in saved) throw new Error('edited task was not retained')
|
||||
expect(saved.prompt).toBe('整理过去 24 小时的 AI 新闻,附原文链接,按重要性排序。')
|
||||
await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('本地简报草稿')
|
||||
const remote = await scaffold.ctx.schedule.edit({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: saved.updatedAt ?? null, patch: { prompt: '来自其他窗口的新指令' } })
|
||||
expect(remote).toMatchObject({ prompt: '来自其他窗口的新指令' })
|
||||
const recovery = detail.getByRole('button', { name: '保留修改并复核', exact: true })
|
||||
await recovery.waitFor()
|
||||
const notice = detail.getByRole('alert').locator('..')
|
||||
const palettes = []
|
||||
for (const dark of [false, true]) {
|
||||
await page.evaluate(dark => document.body.toggleAttribute('data-ds-dark-theme', dark), dark)
|
||||
const [box, field, message, action] = await Promise.all([
|
||||
notice.boundingBox(), detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).locator('..').boundingBox(),
|
||||
detail.getByRole('alert').boundingBox(), recovery.boundingBox(),
|
||||
])
|
||||
expect(box).not.toBeNull()
|
||||
expect(field).not.toBeNull()
|
||||
expect(message).not.toBeNull()
|
||||
expect(action).not.toBeNull()
|
||||
expect(Math.abs(box!.x - field!.x)).toBeLessThanOrEqual(1)
|
||||
expect(Math.abs(box!.x + box!.width - field!.x - field!.width)).toBeLessThanOrEqual(1)
|
||||
expect(action!.y).toBeLessThan(message!.y + message!.height)
|
||||
expect(action!.y + action!.height).toBeGreaterThan(message!.y)
|
||||
expect(box!.y + box!.height).toBeLessThan(field!.y)
|
||||
palettes.push(await notice.evaluate((element) => {
|
||||
const style = getComputedStyle(element)
|
||||
return { color: style.color, background: style.backgroundColor }
|
||||
}))
|
||||
}
|
||||
expect(palettes[0]).not.toEqual(palettes[1])
|
||||
await page.evaluate(() => { document.body.removeAttribute('data-ds-dark-theme') })
|
||||
expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe(saved.prompt)
|
||||
await detail.getByRole('button', { name: '保留修改并复核', exact: true }).click()
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).inputValue()).toBe('本地简报草稿')
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe('来自其他窗口的新指令')
|
||||
expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: task.title })
|
||||
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
|
||||
await detail.getByRole('heading', { name: '本地简报草稿', exact: true }).waitFor()
|
||||
expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: '本地简报草稿', prompt: '来自其他窗口的新指令' })
|
||||
expect(await detail.evaluate(element => element === document.activeElement)).toBe(true)
|
||||
await manager.getByRole('button', { name: '选择创建方式', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: '手动创建', exact: true }).click()
|
||||
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('检查最新进展')
|
||||
@@ -92,7 +140,7 @@ it('creates from a paused empty state, selects the task, and saves an inline edi
|
||||
await detail.getByRole('button', { name: '恢复任务', exact: true }).waitFor()
|
||||
expect(await detail.getByText('待创建', { exact: true }).count()).toBe(0)
|
||||
expect(await detail.getByText('最近运行会话', { exact: true }).count()).toBe(0)
|
||||
expect(await detail.getByText('运行间隔至少', { exact: false }).count()).toBe(0)
|
||||
expect(await detail.getByText('运行间隔至少', { exact: false }).count()).toBe(1)
|
||||
expect(tripwire.pageErrors).toEqual([])
|
||||
expect(scaffold.ctx.agents.get(task.target.sessionId)).toBeUndefined()
|
||||
} finally {
|
||||
@@ -113,7 +161,7 @@ it('creates and edits Custom Cron through the built UI while retaining its expli
|
||||
const manager = page.getByTestId('task-manager-page')
|
||||
await manager.getByRole('button', { name: '选择创建方式', exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: '手动创建', exact: true }).click()
|
||||
const dialog = page.getByRole('dialog', { name: '手动创建', exact: true })
|
||||
const dialog = manager.getByRole('complementary', { name: '手动创建', exact: true })
|
||||
await dialog.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('Cron deployment check')
|
||||
await dialog.getByRole('textbox', { name: '自动化任务内容', exact: true }).fill('Check the deployment status.')
|
||||
await dialog.getByRole('button', { name: /^重复 / }).click()
|
||||
@@ -128,15 +176,14 @@ it('creates and edits Custom Cron through the built UI while retaining its expli
|
||||
expect(created).toMatchObject({ kind: 'cron', expression: '0 9 * * 1-5', timeZone: 'Asia/Shanghai' })
|
||||
expect(created).not.toHaveProperty('rrule')
|
||||
|
||||
await detail.getByRole('button', { name: '编辑', exact: true }).click()
|
||||
await detail.getByRole('textbox', { name: '自定义', exact: true }).fill(' ')
|
||||
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
|
||||
await detail.getByRole('alert').getByText('请检查规则内容和时区', { exact: true }).waitFor()
|
||||
expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
await detail.getByRole('status').getByText('请检查必填项和运行规则', { exact: true }).waitFor()
|
||||
expect(await scaffold.ctx.schedule.view({ id: created.id })).toEqual(created)
|
||||
await detail.getByRole('textbox', { name: '自定义', exact: true }).fill('0 10 * * 1-5')
|
||||
await detail.getByRole('button', { name: /^时区 / }).waitFor()
|
||||
await detail.getByRole('button', { name: '保存修改', exact: true }).click()
|
||||
await detail.getByRole('textbox', { name: '自定义', exact: true }).waitFor({ state: 'detached' })
|
||||
await expect.poll(() => detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
const edited = await scaffold.ctx.schedule.view({ id: created.id })
|
||||
expect(edited).toMatchObject({ id: created.id, kind: 'cron', expression: '0 10 * * 1-5', timeZone: 'Asia/Shanghai' })
|
||||
expect(edited).not.toHaveProperty('rrule')
|
||||
|
||||
@@ -53,6 +53,26 @@ async function viewFacts(page: Page): Promise<ViewFacts> {
|
||||
})
|
||||
}
|
||||
|
||||
/** Header, form, notices, and footer share the pane's visible content edges. */
|
||||
async function expectEditorAlignment(title: Locator): Promise<void> {
|
||||
await expect.poll(() => title.evaluate((field) => {
|
||||
const pane = field.closest('aside')!
|
||||
const bounds = pane.getBoundingClientRect()
|
||||
const name = field.parentElement!.getBoundingClientRect()
|
||||
const action = pane.querySelector('footer:last-of-type > button:last-of-type')!.getBoundingClientRect()
|
||||
const content = Array.from(pane.querySelectorAll('h2, textarea, [class*="_ruleRows"], [class*="_saveNotice"], [class*="_detailNotice"], [class*="_saveFailure"]'))
|
||||
.filter(node => node.getClientRects().length > 0)
|
||||
const offsets = {
|
||||
gutters: Math.abs(name.left - bounds.left - bounds.right + name.right),
|
||||
action: Math.abs(action.right - name.right),
|
||||
left: Math.max(...content.map(node => Math.abs(node.getBoundingClientRect().left - name.left))),
|
||||
right: Math.max(...Array.from(pane.querySelectorAll('textarea, [class*="_ruleRows"]'))
|
||||
.map(node => Math.abs(node.getBoundingClientRect().right - name.right))),
|
||||
}
|
||||
return Object.fromEntries(Object.entries(offsets).filter(([, offset]) => offset > 1))
|
||||
})).toEqual({})
|
||||
}
|
||||
|
||||
it('keeps the automation page on screen with its text fields at the touch step', async () => {
|
||||
const scaffold = await launchWebScaffold()
|
||||
const url = scaffold.authenticatedUrl
|
||||
@@ -82,7 +102,6 @@ it('keeps the automation page on screen with its text fields at the touch step',
|
||||
// The editor keeps the touch floor for its name and instruction fields.
|
||||
await phonePanel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click()
|
||||
await phonePanel.locator('[class*="_detailScroll"]').waitFor({ timeout: 10_000 })
|
||||
await phonePanel.getByRole('button', { name: '编辑', exact: true }).click()
|
||||
await expect.poll(() => viewFacts(phonePage)).toEqual({
|
||||
width: PHONE_PAGE_WIDTH,
|
||||
documentWidth: PHONE_PAGE_WIDTH,
|
||||
@@ -91,6 +110,66 @@ it('keeps the automation page on screen with its text fields at the touch step',
|
||||
search: '16px',
|
||||
instruction: '16px',
|
||||
})
|
||||
const detail = phonePanel.getByRole('complementary', { name: '任务详情', exact: true })
|
||||
await expectEditorAlignment(detail.getByRole('textbox', { name: '自动化任务名称', exact: true }))
|
||||
await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).fill('未保存的手机草稿')
|
||||
const task = (await scaffold.ctx.schedule.catalog()).find(item => item.title === PHONE_TASK_TITLE)
|
||||
if (task === undefined) throw new Error('phone task was not retained')
|
||||
await scaffold.ctx.schedule.edit({ id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt ?? null,
|
||||
patch: { prompt: '其他窗口的最新内容' } })
|
||||
const recovery = detail.getByRole('button', { name: '保留修改并复核', exact: true })
|
||||
await recovery.waitFor()
|
||||
await recovery.scrollIntoViewIfNeeded()
|
||||
const recoveryBox = await recovery.boundingBox()
|
||||
expect(recoveryBox).not.toBeNull()
|
||||
expect(recoveryBox!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(recoveryBox!.x + recoveryBox!.width).toBeLessThanOrEqual(PHONE_PAGE_WIDTH)
|
||||
expect(recoveryBox!.y).toBeGreaterThanOrEqual(0)
|
||||
expect(recoveryBox!.y + recoveryBox!.height).toBeLessThanOrEqual(844)
|
||||
const [noticeBox, messageBox, nameBox] = await Promise.all([
|
||||
detail.getByRole('alert').locator('..').boundingBox(), detail.getByRole('alert').boundingBox(),
|
||||
detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).locator('..').boundingBox(),
|
||||
])
|
||||
expect(noticeBox).not.toBeNull()
|
||||
expect(messageBox).not.toBeNull()
|
||||
expect(nameBox).not.toBeNull()
|
||||
expect(Math.abs(noticeBox!.x - nameBox!.x)).toBeLessThanOrEqual(1)
|
||||
expect(Math.abs(noticeBox!.x + noticeBox!.width - nameBox!.x - nameBox!.width)).toBeLessThanOrEqual(1)
|
||||
expect(recoveryBox!.y).toBeGreaterThanOrEqual(messageBox!.y + messageBox!.height)
|
||||
expect(recoveryBox!.x + recoveryBox!.width).toBeLessThanOrEqual(noticeBox!.x + noticeBox!.width)
|
||||
expect(await detail.getByRole('button', { name: '保存修改', exact: true }).isDisabled()).toBe(true)
|
||||
await recovery.click()
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务名称', exact: true }).inputValue()).toBe('未保存的手机草稿')
|
||||
expect(await detail.getByRole('textbox', { name: '自动化任务内容', exact: true }).inputValue()).toBe('其他窗口的最新内容')
|
||||
expect((await viewFacts(phonePage)).documentWidth).toBe(PHONE_PAGE_WIDTH)
|
||||
expect(await scaffold.ctx.schedule.view({ id: task.id })).toMatchObject({ title: PHONE_TASK_TITLE })
|
||||
await detail.getByRole('button', { name: '放弃', exact: true }).click()
|
||||
await phonePanel.getByRole('button', { name: '关闭详情', exact: true }).click()
|
||||
await phonePanel.getByRole('button', { name: '选择创建方式', exact: true }).click()
|
||||
await phonePage.getByRole('menuitem', { name: '手动创建', exact: true }).click()
|
||||
const creation = phonePanel.getByRole('complementary', { name: '手动创建', exact: true })
|
||||
await creation.waitFor()
|
||||
await expectEditorAlignment(creation.getByRole('textbox', { name: '自动化任务名称', exact: true }))
|
||||
await expect.poll(() => viewFacts(phonePage)).toEqual({
|
||||
width: PHONE_PAGE_WIDTH,
|
||||
documentWidth: PHONE_PAGE_WIDTH,
|
||||
smallestField: 16,
|
||||
name: '16px',
|
||||
search: '16px',
|
||||
instruction: '16px',
|
||||
})
|
||||
for (const name of ['放弃', '创建']) {
|
||||
const button = creation.getByRole('button', { name, exact: true })
|
||||
await button.scrollIntoViewIfNeeded()
|
||||
const box = await button.boundingBox()
|
||||
expect(box).not.toBeNull()
|
||||
expect(box!.x).toBeGreaterThanOrEqual(0)
|
||||
expect(box!.x + box!.width).toBeLessThanOrEqual(PHONE_PAGE_WIDTH)
|
||||
expect(box!.y).toBeGreaterThanOrEqual(0)
|
||||
expect(box!.y + box!.height).toBeLessThanOrEqual(844)
|
||||
}
|
||||
await creation.getByRole('button', { name: '放弃', exact: true }).click()
|
||||
expect(await phonePanel.getByRole('complementary').count()).toBe(0)
|
||||
await phone.close()
|
||||
|
||||
// A fine pointer keeps the compact steps: the floor is pointer-scoped.
|
||||
@@ -108,7 +187,6 @@ it('keeps the automation page on screen with its text fields at the touch step',
|
||||
})
|
||||
await desktopPanel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click()
|
||||
await desktopPanel.locator('[class*="_detailScroll"]').waitFor({ timeout: 10_000 })
|
||||
await desktopPanel.getByRole('button', { name: '编辑', exact: true }).click()
|
||||
await expect.poll(() => viewFacts(desktopPage)).toEqual({
|
||||
width: 1024,
|
||||
documentWidth: 1024,
|
||||
@@ -130,3 +208,83 @@ it('keeps the automation page on screen with its text fields at the touch step',
|
||||
await scaffold.close()
|
||||
}
|
||||
}, 180_000)
|
||||
|
||||
it.each([
|
||||
{ locale: 'en-US', tasks: 'Automation tasks', sidebar: 'Collapse sidebar', openSidebar: 'Open sidebar', close: 'Close details',
|
||||
methods: 'Choose a creation method', manual: 'Create manually', title: 'Automation task name', discard: 'Discard',
|
||||
instruction: 'Automation task instruction', create: 'Create',
|
||||
repeat: /^Repeat /, frequencies: ['Every month', 'Weekly', 'Once'] },
|
||||
{ locale: 'zh-CN', tasks: '自动化任务', sidebar: '收起侧边栏', openSidebar: '打开侧边栏', close: '关闭详情',
|
||||
methods: '选择创建方式', manual: '手动创建', title: '自动化任务名称', discard: '放弃',
|
||||
instruction: '自动化任务内容', create: '创建',
|
||||
repeat: /^重复 /, frequencies: ['每月', '每周', '仅一次'] },
|
||||
{ locale: 'fr-FR', tasks: "Tâches d'automatisation", sidebar: 'Réduire la barre latérale', openSidebar: 'Ouvrir la barre latérale', close: 'Fermer les détails',
|
||||
methods: 'Choisir le mode de création', manual: 'Créer manuellement', title: "Nom de la tâche d'automatisation", discard: 'Abandonner',
|
||||
instruction: "Instruction de tâche d'automatisation", create: 'Créer',
|
||||
repeat: /^Répéter /, frequencies: ['Tous les mois', 'Hebdomadaire', 'Une fois'] },
|
||||
] as const)('keeps both editor modes inside a narrow pane with the sidebar open ($locale)', async (copy) => {
|
||||
const scaffold = await launchWebScaffold()
|
||||
let browser: Browser | undefined
|
||||
try {
|
||||
browser = await chromium.launch()
|
||||
await scaffold.ctx.schedule.create({
|
||||
title: PHONE_TASK_TITLE, prompt: 'Check the deployment log',
|
||||
timing: { kind: 'at', at: '2099-08-25T12:08:00.000Z' }, target: { kind: 'new_once' },
|
||||
})
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 844 }, locale: copy.locale, timezoneId: 'Asia/Shanghai' })
|
||||
const page = await context.newPage()
|
||||
const consoleWatch = watchConsole(page)
|
||||
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
|
||||
await page.getByRole('button', { name: copy.sidebar, exact: true }).waitFor()
|
||||
await page.getByRole('button', { name: copy.tasks, exact: true }).click()
|
||||
const panel = page.getByTestId('task-manager-page')
|
||||
await panel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).click()
|
||||
await page.evaluate(() => document.fonts.ready)
|
||||
for (const mode of ['edit', 'create']) {
|
||||
if (mode === 'create') {
|
||||
await panel.getByRole('button', { name: copy.close, exact: true }).click()
|
||||
await panel.getByRole('button', { name: copy.methods, exact: true }).click()
|
||||
await page.getByRole('menuitem', { name: copy.manual, exact: true }).click()
|
||||
}
|
||||
const editor = panel.getByRole('complementary')
|
||||
const title = editor.getByRole('textbox', { name: copy.title, exact: true })
|
||||
if (mode === 'create') {
|
||||
for (const name of [copy.title, copy.instruction]) {
|
||||
const field = editor.getByRole('textbox', { name, exact: true })
|
||||
expect(await field.getAttribute('required')).toBeNull()
|
||||
expect(await field.getAttribute('aria-required')).toBe('true')
|
||||
expect(await field.evaluate(node => (node as HTMLInputElement | HTMLTextAreaElement).validationMessage)).toBe('')
|
||||
}
|
||||
expect(await editor.getByRole('button', { name: copy.create, exact: true }).isDisabled()).toBe(true)
|
||||
}
|
||||
await title.fill('Retained draft through resizing')
|
||||
await editor.getByRole('button', { name: copy.discard, exact: true }).waitFor()
|
||||
for (const width of [1280, 1100, 1024, 900, 800]) {
|
||||
await title.focus()
|
||||
await page.setViewportSize({ width, height: 844 })
|
||||
expect(await title.evaluate(node => document.activeElement === node)).toBe(true)
|
||||
// Entering the shell's narrow range publishes the reopen action after its resize observer runs.
|
||||
if (width === 900) { await page.getByRole('button', { name: copy.openSidebar, exact: true }).click(); await title.focus() }
|
||||
await page.getByRole('button', { name: copy.sidebar, exact: true }).waitFor()
|
||||
expect(await panel.getByRole('button', { name: PHONE_TASK_TITLE, exact: true }).isVisible()).toBe(true)
|
||||
for (const frequency of copy.frequencies) {
|
||||
await editor.getByRole('button', { name: copy.repeat }).click()
|
||||
await page.getByRole('menuitem', { name: frequency, exact: true }).click()
|
||||
await expectEditorAlignment(title)
|
||||
await expect.poll(() => editor.locator('[class*="_detailScroll"]').evaluate(node => node.scrollWidth - node.clientWidth)).toBe(0)
|
||||
expect(await editor.locator('input, textarea, button').evaluateAll(nodes => nodes.every((node) => {
|
||||
const box = node.getBoundingClientRect()
|
||||
const pane = node.closest('aside')!.getBoundingClientRect()
|
||||
return box.left >= pane.left && box.right <= pane.right
|
||||
}))).toBe(true)
|
||||
}
|
||||
expect(await title.inputValue()).toBe('Retained draft through resizing')
|
||||
}
|
||||
await page.setViewportSize({ width: 1100, height: 844 })
|
||||
}
|
||||
expect(consoleWatch.pageErrors).toEqual([])
|
||||
expect(consoleWatch.warnings).toEqual([])
|
||||
} finally {
|
||||
try { await browser?.close() } finally { await scaffold.close() }
|
||||
}
|
||||
}, 180_000)
|
||||
@@ -50,8 +50,8 @@ async function expectEllipsizedText(labels: Locator): Promise<void> {
|
||||
}
|
||||
|
||||
describe.each([
|
||||
{ locale: 'en-US', tasks: 'Automation tasks', edit: 'Edit', time: 'Time', second: 'Second', zone: 'Time zone' },
|
||||
{ locale: 'zh-CN', tasks: '自动化任务', edit: '编辑', time: '时间', second: '秒', zone: '时区' },
|
||||
{ locale: 'en-US', tasks: 'Automation tasks', time: 'Time', second: 'Second', zone: 'Time zone' },
|
||||
{ locale: 'zh-CN', tasks: '自动化任务', time: '时间', second: '秒', zone: '时区' },
|
||||
])('automation pickers ($locale)', (copy) => {
|
||||
it.each(['clock', 'zone'] as const)('ellipsizes the %s labels and keeps vertical choices reachable at 500% zoom', async (kind) => {
|
||||
const context = await browser.newContext({
|
||||
@@ -66,7 +66,6 @@ describe.each([
|
||||
await page.getByRole('button', { name: copy.tasks, exact: true }).click()
|
||||
const detail = page.getByTestId('task-manager-page')
|
||||
await detail.getByRole('button', { name: TITLE, exact: true }).click()
|
||||
await detail.getByRole('button', { name: copy.edit, exact: true }).click()
|
||||
await page.evaluate(() => document.fonts.ready)
|
||||
const trigger = kind === 'clock'
|
||||
? detail.getByRole('button', { name: copy.time, exact: true })
|
||||
|
||||
@@ -12,14 +12,14 @@
|
||||
en: c1d163bf7d366e24
|
||||
zh: 34dccfbb0bf3701d
|
||||
/schedule-reminders/create-reminders:
|
||||
en: 9bd962e3653a8a72
|
||||
zh: 6b0887ed1477420c
|
||||
en: 762ecb7a7743cd2d
|
||||
zh: 1b163ae679601767
|
||||
/schedule-reminders/inspect-run-and-delete-tasks:
|
||||
en: 9407dca2b849be4a
|
||||
zh: 9e158a42f4d95305
|
||||
en: 9f1e9d732597aa28
|
||||
zh: 66feec44adf24332
|
||||
/schedule-reminders/edit-a-task:
|
||||
en: 45f9dac1f9d86696
|
||||
zh: 3193f010cc6168da
|
||||
en: fe8c59251f0b4620
|
||||
zh: a422e44f758adae1
|
||||
/schedule-reminders/timing-and-delivery-reference:
|
||||
en: acb84b04d567d15c
|
||||
zh: c658a81d8c6875f4
|
||||
|
||||
@@ -27,7 +27,7 @@ A conversation that a delivery creates joins the Workspace registered at its wor
|
||||
|
||||
For example, ask: “Remind me every day at 23:00 in Asia/Shanghai to check the weather.” Below the reply, a card shows the created reminder's name and frequency; Open shows its details in the right sidebar. Check that the frequency repeats every day at 23:00, not Once. A one-time reminder does not become recurring after delivery. After the reminder is deleted, the card shows Deleted and no longer opens it.
|
||||
|
||||
To create a reminder without the model, open Automation tasks from the sidebar, open Choose a creation method beside New, and choose Create manually; when no task exists, New automation task opens the same dialog. The Create manually dialog asks for an Automation task name, an Automation task instruction, Run in, Linked workspace, and Run time. It starts with Once at one hour from now in the browser's time zone and with Create a conversation and reuse it. Run in offers Create a conversation and reuse it, which creates one conversation at the first run and keeps using it, and New conversation for every run, which creates a separate conversation at each run and shows the Host's minimum run interval. Linked workspace lists each registered Workspace with its directory and selects the Workspace whose directory the new conversation uses; it starts at Default workspace, or at the first Workspace when the default Workspace is not registered. When no Workspace exists, Linked workspace shows Ungrouped and the Host project directory is used. The new conversation uses the default preset. Create creates the task and selects it in the list, and Cancel closes the dialog without creating one. If the Host refuses the task, the dialog keeps your input and states the problem, for example that the date and time must be in the future.
|
||||
To create a reminder without the model, open Automation tasks from the sidebar, open Choose a creation method beside New, and choose Create manually; when no task exists, New automation task opens the same editor. This editor also opens existing tasks and asks for an Automation task name, an Automation task instruction, Run in, Linked workspace, and Run time. It starts with Once at one hour from now in the browser's time zone and with Create a conversation and reuse it. Run in offers Create a conversation and reuse it, which creates one conversation at the first run and keeps using it, and New conversation for every run, which creates a separate conversation at each run and shows the Host's minimum run interval. Linked workspace lists each registered Workspace with its directory and selects the Workspace whose directory the new conversation uses; it starts at Default workspace, or at the first Workspace when the default Workspace is not registered. When no Workspace exists, Linked workspace shows Ungrouped and the Host project directory is used. The new conversation uses the default preset. Create creates the task and selects it in the list, and Discard closes the editor without creating one. If the Host refuses the task, the editor keeps your input and states the problem, for example that the date and time must be in the future.
|
||||
|
||||
New, and Create in a conversation in the same menu, open a new conversation in the current or most recent Workspace; ask the model there to create the task.
|
||||
|
||||
@@ -50,7 +50,7 @@ When retention removed earlier records, the last page states that earlier delive
|
||||
|
||||
Active tasks participate in scheduling. Paused and ended tasks do not schedule another delivery. A one-time task ends after its reminder is durably written to the conversation inbox, and a repeating task ends after the last occurrence of its rule; choose All or Ended in Task status to find an ended task. The Session header clock, the row mark, and the hover card show only active tasks, so disappearance from those views does not mean that the task was deleted.
|
||||
|
||||
Pause in the details stops the future deliveries of an active task, and Resume restarts a paused task. Run now, in the Automation task actions menu, asks the Host to deliver the instruction once now and keeps the next scheduled run, also for a paused or ended task. While a delivery of a task that delivers to an existing conversation or to one new conversation is queued or running, Edit, Pause, Resume, Run now, and Delete task are disabled, and the details state that the task is queued or running and that you manage it in its conversation, which the button at the bottom of the details opens. A task that creates a new conversation for every run is not disabled this way; its runs continue beside one another. After a delivery, Run now stays disabled until the task's minimum delivery interval ends; while only the interval holds it, hold the pointer on Run now or move the keyboard to it to see when it becomes available. If the Host refuses a run for one of these reasons, the details state that the task is queued, running, or was just delivered. Run now is also disabled while the conversation that the task delivers to is archived. If you stop the conversation while the task's instruction waits there, the instruction stays queued until your next message, the task's next scheduled run, or Run now starts it.
|
||||
Pause in the details stops the future deliveries of an active task, and Resume restarts a paused task. Run now, in the Automation task actions menu, asks the Host to deliver the instruction once now and keeps the next scheduled run, also for a paused or ended task. While a delivery of a task that delivers to an existing conversation or to one new conversation is queued or running, the fields, Save changes, Pause, Resume, Run now, and Delete task are disabled, and the details state that the task is queued or running and that you manage it in its conversation, which the button at the bottom of the details opens. A task that creates a new conversation for every run is not disabled this way; its runs continue beside one another. After a delivery, Run now stays disabled until the task's minimum delivery interval ends; while only the interval holds it, hold the pointer on Run now or move the keyboard to it to see when it becomes available. If the Host refuses a run for one of these reasons, the details state that the task is queued, running, or was just delivered. Run now is also disabled while the conversation that the task delivers to is archived. If you stop the conversation while the task's instruction waits there, the instruction stays queued until your next message, the task's next scheduled run, or Run now starts it.
|
||||
|
||||
Choose Delete task from the Automation task actions menu and confirm to stop future delivery and remove the task from the list, including for a paused or ended task. Deletion removes the task together with its saved delivery records, so the task's saved history is gone. Confirming the deletion reports the outcome in one app-wide notice — deleted, which also closes the details, or a failure that leaves the task in place to retry; it does not remove the conversations or retract a message already queued there. The row stays visible until a successful query confirms the remaining tasks. If a query fails, Retry reloads the catalog; the error is not an empty successful result.
|
||||
|
||||
@@ -59,7 +59,7 @@ Choose Delete task from the Automation task actions menu and confirm to stop fut
|
||||
|
||||
Ask the model to change a reminder's name, instruction, repeat rule, or delivery target, or to pause or resume it; the change keeps the reminder id and saved delivery records.
|
||||
|
||||
In Automation tasks, select a task and choose Edit to change its Automation task name, Automation task instruction, Run in, Linked workspace, and Run time, including for a paused or ended task. Edits stay in a local draft until you choose Save changes. Editing keeps the task id, latest delivery receipt, and all saved delivery records. A changed rule makes an ended task active again and keeps a paused task paused. For a task that delivers to an existing conversation, Run in shows Current linked conversation; choosing another option makes later runs create their conversations and sets Linked workspace to its starting value, as in Create manually. A task keeps its stored preset while its Workspace stays the same; a changed Workspace uses the default preset.
|
||||
In Automation tasks, select a task to change its Automation task name, Automation task instruction, Run in, Linked workspace, and Run time, including for a paused or ended task. Edits stay in a local draft until you choose Save changes. Editing keeps the task id, latest delivery receipt, and all saved delivery records. A changed rule makes an ended task active again and keeps a paused task paused. For a task that delivers to an existing conversation, Run in shows Current linked conversation; choosing another option makes later runs create their conversations and sets Linked workspace to its starting value, as in Create manually. A task keeps its stored preset while its Workspace stays the same; a changed Workspace uses the default preset.
|
||||
|
||||
- Once: Date opens a month calendar, Time opens Hour, Minute, and Second columns, and Time zone interprets them. The task runs once and then ends.
|
||||
- Every N minutes and Every N hours: Interval sets the number of minutes or hours, at least 1. The interval counts from the minute at which you save the task.
|
||||
@@ -70,9 +70,9 @@ In Automation tasks, select a task and choose Edit to change its Automation task
|
||||
|
||||
Time zone lists recently selected zones first, marks the system zone, and searches by UTC offset, IANA ID, or city. It appears for guided choices and Custom expressions that use a separate zone; otherwise the Custom rule text supplies its zone.
|
||||
|
||||
The fields change only a local draft. While you edit, the bottom of the details shows Unsaved changes with Cancel and Save changes; Save changes sends only the changed fields in one update, and Cancel restores the stored values. A save sends a new rule only when the timing changed. Save changes stays disabled while the name or instruction is empty or a guided choice is incomplete. The Host validates a supplied Custom rule on save; invalid text keeps the draft and shows an error. The fields are disabled while a save is in flight. Leaving the details does not roll back a Host write already begun.
|
||||
The fields change only a local draft. If the task targets an existing conversation, Current linked session remains available so you can undo a destination change without discarding other edits. While you edit, the bottom of the details shows Unsaved changes with Discard and Save changes; Save changes sends only the changed fields in one update, and Discard restores the stored values. A save sends a new rule only when the timing changed. Save changes stays disabled until a meaningful change has valid fields and timing. Invalid Custom text keeps the draft and shows a correction message; the Host also validates the rule on save. Pause, resume, Run now, and deletion wait until you save or discard unsaved changes. The fields are disabled while a save is in flight. Leaving the details does not roll back a Host write already begun.
|
||||
|
||||
A catalog refresh does not change the draft. If delivery or another edit changed the task before the save arrives, the Host refuses the save and changes nothing; the details state that the task changed elsewhere, Load latest version replaces the draft with the latest version, and Save changes stays disabled until then. If another save fails, the draft stays and the details ask you to try again; check the task before retrying an update whose outcome is unknown. An accepted update refreshes the catalog. Late responses after closing details or switching tasks do not replace the current view.
|
||||
Switching tasks or leaving the page keeps unsaved drafts. A catalog refresh updates a pristine form; an edited form keeps all fields and its original version. If delivery or another edit changes the task, the details state that the task changed elsewhere and disable Save changes when the newer version arrives. The Host also checks the version on save. Review with my edits keeps the title, prompt, timing, and target groups you changed and loads the latest values for the other groups. Review the whole form before saving; this action alone does not save. If the same group changed elsewhere, your edits take precedence in the form. Discard replaces the whole draft with the latest stored values. If another save fails, the draft stays and the details ask you to try again; check the task before retrying an update whose outcome is unknown. An accepted update refreshes the catalog. Late responses after closing details or switching tasks do not replace the current view.
|
||||
|
||||
<a id="timing-and-delivery"></a>
|
||||
## Timing and delivery reference
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
|
||||
例如,请求:“每天 Asia/Shanghai 时区 23:00 提醒我查看天气。”回复下方的卡片显示刚创建的提醒的名称和频率;“打开”在右侧栏显示其详情。检查频率是每天 23:00 重复,而非“仅一次”。一次性提醒不会在投递后变成重复任务。提醒删除后,卡片显示“已删除”,且不再打开该提醒。
|
||||
|
||||
不经模型创建提醒时,从侧栏打开自动化任务页面,打开“新建”旁的“选择创建方式”,再选择“手动创建”;尚无任务时,“新建自动化任务”打开同一对话框。“手动创建”对话框要求填写“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”。初始运行时间为“仅一次”,时间为浏览器时区下的一小时后,初始执行位置为“新建对话并复用”。“执行位置”提供“新建对话并复用”和“每次新建对话”:前者在首次运行时创建一个对话并在之后沿用,后者在每次运行时创建独立对话,并显示宿主的最小运行间隔。“关联工作区”列出每个已注册的 Workspace 及其目录,并选择新对话使用其目录的 Workspace;初始值为“默认工作区”,未注册默认 Workspace 时为第一个 Workspace。尚无任何 Workspace 时,“关联工作区”显示“未分组”,并使用宿主项目目录。新对话使用默认 preset。“创建”创建该任务并在列表中选中它,“取消”关闭对话框而不创建任务。若宿主拒绝该任务,对话框保留你的输入并说明问题,例如日期和时间必须在未来。
|
||||
不经模型创建提醒时,从侧栏打开自动化任务页面,打开“新建”旁的“选择创建方式”,再选择“手动创建”;尚无任务时,“新建自动化任务”打开同一编辑页。已有任务也使用此页面,填写“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”。初始运行时间为“仅一次”,时间为浏览器时区下的一小时后,初始执行位置为“新建对话并复用”。“执行位置”提供“新建对话并复用”和“每次新建对话”:前者在首次运行时创建一个对话并在之后沿用,后者在每次运行时创建独立对话,并显示宿主的最小运行间隔。“关联工作区”列出每个已注册的 Workspace 及其目录,并选择新对话使用其目录的 Workspace;初始值为“默认工作区”,未注册默认 Workspace 时为第一个 Workspace。尚无任何 Workspace 时,“关联工作区”显示“未分组”,并使用宿主项目目录。新对话使用默认 preset。“创建”创建该任务并在列表中选中它,“放弃”关闭编辑页而不创建任务。若宿主拒绝该任务,编辑页保留你的输入并说明问题,例如日期和时间必须在未来。
|
||||
|
||||
“新建”以及同一菜单中的“在对话中创建”会在当前或最近使用的 Workspace 中打开一个新对话;在其中请模型创建该任务。
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
|
||||
活动任务参与调度;已暂停和已结束的任务不会再次安排投递。一次性任务在提醒持久写入对话收件箱后结束,重复任务在其规则的最后一个发生时点后结束;在“任务状态”中选择“全部”或“已结束”即可找到已结束的任务。Session 顶部的提醒时钟、Session 行的时钟标识和悬浮卡片只显示活动任务,因此从这些视图消失并不表示任务已被删除。
|
||||
|
||||
详情中的“暂停任务”停止活动任务之后的投递,“恢复任务”重新启动已暂停的任务。“自动化任务操作”菜单中的“立即执行”请宿主现在投递一次指令,并保留下次计划运行;已暂停或已结束的任务也可以这样运行。投递到现有对话或一个新对话的任务的一次投递已排队或正在运行时,“编辑”“暂停任务”“恢复任务”“立即执行”和“删除任务”均禁用,详情说明此任务已排队或执行中,请在会话中管理任务;详情底部的按钮打开该会话。每次运行都创建新对话的任务不会这样禁用;它的各次运行并行继续。一次投递之后,“立即执行”保持禁用,直到该任务的最小投递间隔结束;仅因间隔禁用时,将指针停在“立即执行”上或用键盘移到该项,即可查看它恢复可用的时间。若宿主因上述原因之一拒绝运行,详情会说明该任务已排队、执行中或刚执行过。任务投递到的对话已归档时,“立即执行”同样禁用。若在任务指令仍在对话中等待时停止该对话,指令会保持排队,直到你的下一条消息、该任务的下一次计划运行或“立即执行”使其开始。
|
||||
详情中的“暂停任务”停止活动任务之后的投递,“恢复任务”重新启动已暂停的任务。“自动化任务操作”菜单中的“立即执行”请宿主现在投递一次指令,并保留下次计划运行;已暂停或已结束的任务也可以这样运行。投递到现有对话或一个新对话的任务的一次投递已排队或正在运行时,字段、“保存修改”“暂停任务”“恢复任务”“立即执行”和“删除任务”均禁用,详情说明此任务已排队或执行中,请在会话中管理任务;详情底部的按钮打开该会话。每次运行都创建新对话的任务不会这样禁用;它的各次运行并行继续。一次投递之后,“立即执行”保持禁用,直到该任务的最小投递间隔结束;仅因间隔禁用时,将指针停在“立即执行”上或用键盘移到该项,即可查看它恢复可用的时间。若宿主因上述原因之一拒绝运行,详情会说明该任务已排队、执行中或刚执行过。任务投递到的对话已归档时,“立即执行”同样禁用。若在任务指令仍在对话中等待时停止该对话,指令会保持排队,直到你的下一条消息、该任务的下一次计划运行或“立即执行”使其开始。
|
||||
|
||||
从“自动化任务操作”菜单选择“删除任务”并确认,可停止未来投递并将该任务从列表中移除,包括已暂停或已结束的任务。删除会移除该任务及其已保存的发送记录,因此该任务的已保存历史随之消失。确认删除会在同一个应用级提示里报告结果——已删除(同时关闭详情),或失败(失败时任务保留、可重试);删除不会删除相关对话,也不会撤回已进入其队列的消息。该行会保留到成功查询确认剩余任务为止。查询失败时,“重试”重新加载目录;错误不会被视为查询成功的空结果。
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
|
||||
请模型修改提醒的名称、指令、重复规则或投递目标,或暂停、恢复提醒;修改保留提醒 id 与已保存的投递记录。
|
||||
|
||||
在自动化任务页面选择任务并选择“编辑”,即可修改其“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”,包括已暂停或已结束的任务。修改先保存在本地草稿中,直到选择“保存修改”。编辑保留任务 id、最近一次投递回执以及全部已保存的发送记录。规则改变后,已结束的任务重新变为活动,已暂停的任务保持暂停。对于投递到现有对话的任务,“执行位置”显示“当前关联对话”;选择其他选项后,之后的运行会创建各自的对话,“关联工作区”也设为其初始值,与“手动创建”相同。Workspace 保持不变时,任务保留已存储的 preset;改换 Workspace 后使用默认 preset。
|
||||
在自动化任务页面选择任务,即可直接修改其“自动化任务名称”“自动化任务内容”“执行位置”“关联工作区”和“运行时间”,包括已暂停或已结束的任务。修改先保存在本地草稿中,直到选择“保存修改”。编辑保留任务 id、最近一次投递回执以及全部已保存的发送记录。规则改变后,已结束的任务重新变为活动,已暂停的任务保持暂停。对于投递到现有对话的任务,“执行位置”显示“当前关联对话”;选择其他选项后,之后的运行会创建各自的对话,“关联工作区”也设为其初始值,与“手动创建”相同。Workspace 保持不变时,任务保留已存储的 preset;改换 Workspace 后使用默认 preset。
|
||||
|
||||
- “仅一次”:“日期”打开月历,“时间”打开“时”“分”“秒”三列,“时区”决定如何解释它们。任务运行一次后结束。
|
||||
- “每 N 分钟”和“每 N 小时”:“重复间隔”设置分钟数或小时数,至少为 1。间隔从你保存任务时所在的分钟起算。
|
||||
@@ -70,9 +70,9 @@
|
||||
|
||||
“时区”先列出最近选择的时区,标出系统时区,并可按 UTC 偏移、IANA 标识或城市搜索。引导式选项和使用独立时区的“自定义”表达式显示此字段;其他“自定义”规则由文本指定时区。
|
||||
|
||||
各字段只修改本地草稿。编辑期间,详情底部显示“有未保存的修改”以及“取消”和“保存修改”;“保存修改”以一次更新只提交已修改的字段,“取消”恢复已存储的值。只有时间规则改变时,保存才会提交新规则。名称或指令为空,或引导式选择不完整时,“保存修改”保持禁用。宿主在保存时验证所填的“自定义”规则;文本无效时保留草稿并显示错误。保存进行期间,各字段禁用。离开详情不会回滚宿主已开始的写入。
|
||||
各字段只修改本地草稿。若任务指向已有会话,执行位置仍提供“当前关联会话”,可撤销目标变更而保留其他修改。编辑期间,详情底部显示“有未保存的修改”以及“放弃”和“保存修改”;“保存修改”以一次更新只提交已修改的字段,“放弃”恢复已存储的值。只有时间规则改变时,保存才会提交新规则。只有实际修改且字段和时间规则有效时,才能“保存修改”。无效的自定义文本保留在草稿中,并显示纠正提示;宿主也会在保存时校验规则。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。保存进行期间,各字段禁用。离开详情不会回滚宿主已开始的写入。
|
||||
|
||||
刷新目录不会改变草稿。若投递或其他编辑在保存到达前改变了任务,宿主拒绝保存且不做任何修改;详情会说明此任务已在其他位置更新,“载入最新版本”用最新版本替换草稿,在此之前“保存修改”保持禁用。保存因其他原因失败时,草稿保留,详情提示你重试;对于结果未知的更新,请在重试前检查任务。更新被接受后刷新目录。关闭详情或切换任务后才到达的响应不会替换当前视图。
|
||||
切换任务或离开页面时保留未保存的草稿。刷新目录会更新未修改的表单;已修改的表单保留全部字段和原版本。若投递或其他编辑改变了任务,详情会在收到新版本后说明任务已在其他位置更新,并禁用“保存修改”。宿主也会在保存时检查版本。“保留修改并复核”保留你改过的名称、内容、时间和目标字段组,其余字段组载入最新值。保存前请复核整份表单;此操作本身不保存。若同一字段组在其他位置也有更改,表单优先保留你的修改。“放弃”用最新存储值替换整份草稿。保存因其他原因失败时,草稿保留,详情提示你重试;对于结果未知的更新,请在重试前检查任务。更新被接受后刷新目录。关闭详情或切换任务后才到达的响应不会替换当前视图。
|
||||
|
||||
<a id="timing-and-delivery"></a>
|
||||
## 时间与投递参考
|
||||
|
||||
@@ -9,20 +9,20 @@
|
||||
en: 862120984d5392eb
|
||||
zh: eb3e5d5a802da592
|
||||
/deepseek-ai-dsh-client-ui-schedule/summary:
|
||||
en: 0ccbbf29836a8fca
|
||||
zh: d2de9b43e89ab05e
|
||||
en: 9a690c99b0562de5
|
||||
zh: 77a7464316afb3ed
|
||||
/deepseek-ai-dsh-client-ui-schedule/table-of-contents:
|
||||
en: d152484eb41ac6b4
|
||||
zh: 405b30feaf48c087
|
||||
/deepseek-ai-dsh-client-ui-schedule/use-this-package:
|
||||
en: 43cae3c92503c742
|
||||
zh: 41c64476fd9f2375
|
||||
en: 928ae699661089c5
|
||||
zh: 9895b75c5a30771b
|
||||
/deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source:
|
||||
en: 4005b800e930f581
|
||||
zh: ccb9318dad7f7e8f
|
||||
/deepseek-ai-dsh-client-ui-schedule/understand-the-implementation:
|
||||
en: 2ff0c2b6a93cd6b5
|
||||
zh: 388305ea48a79734
|
||||
en: f9895e84de5f5eb7
|
||||
zh: 844cba2fc3f424bc
|
||||
/deepseek-ai-dsh-client-ui-schedule/further-exploration:
|
||||
en: 2fd968202916b197
|
||||
zh: f1ab66194846562b
|
||||
|
||||
@@ -9,7 +9,7 @@ English | [中文](README.zh.md)
|
||||
|
||||
## Summary
|
||||
|
||||
The Automation tasks page and right Sidebar task tab share task rules, local edits, saved delivery records, deletion, and conversation navigation. Manual creation and target selection use the Host Schedule service; conversation cards, header clocks, and Session row marks retain their existing locations.
|
||||
The Automation tasks page and right Sidebar task tab use the same editor for task rules, saved delivery records, deletion, and conversation navigation. Manual creation and target selection use the Host Schedule service; conversation cards, header clocks, and Session row marks retain their existing locations.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -27,17 +27,17 @@ The Automation tasks page and right Sidebar task tab share task rules, local edi
|
||||
|
||||
Below 768px, the task list uses 20px horizontal insets, matching the Plugins page.
|
||||
|
||||
The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New retains its existing behavior: open a new conversation and let the user enter an instruction. Its adjacent menu offers Create in conversation and Create manually. Manual creation opens the shared Modal, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme.
|
||||
The shipped Web composition mounts `ui-schedule` with Host Schedule. The Automation tasks sidebar entry opens the task list without selecting or activating a Session. New retains its existing behavior: open a new conversation and let the user enter an instruction. Its adjacent menu offers Create in conversation and Create manually. Manual creation opens the same editor as an existing task, validates required fields, and saves a task without starting an Agent or sending the instruction. A failed request leaves the form and its values visible. The empty state shows a decorative document-and-clock illustration whose colors follow the theme.
|
||||
|
||||
Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens Rules / Records. Edit stages a draft; Save sends changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. An unchanged Save still asks the Host to store the current row shape. A successful save returns to the read-only view and focuses Edit. Conflict retains the draft and offers Reload; Cancel discards it. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari.
|
||||
Enabled, Paused, Ended, and All filters combine with text search over the title, prompt, and linked Session id; the page starts on Enabled. The search-row menu clears all ended tasks after confirmation, preserving active and paused tasks. Selecting a task opens its editable Rules / Records page. Save is enabled only for valid, meaningful changes and sends only changed fields with `expectedUpdatedAt`, or `null` when no stored revision exists. The fields stay editable after saving. Unsaved drafts survive navigation between tasks and away from the page. A conflict retains the whole draft and disables Save. Review with my edits reapplies the changed field groups to the latest values for review before saving; Discard replaces the draft with the latest stored values. For a new task, Discard closes the editor. Late responses cannot change another task's detail. Coarse-pointer search, instruction, and timing fields use 16px text to prevent focus zoom on iOS Safari.
|
||||
|
||||
The destination menu offers a new conversation that the first delivery creates and later deliveries reuse, or a new conversation at every delivery. Manual creation defaults to reuse. A task already bound to a Session shows Current linked conversation as its destination, and editing it preserves that destination unless the user explicitly chooses a new one. The Linked workspace selector lists the framework Workspace catalog, shows each Workspace's directory under its name, and labels the first-use Workspace with its localized default name. A new destination starts in that Workspace, else in the first listed one. A stored task without a directory shows Ungrouped, because the Sessions it creates join no Workspace. For a reusable destination, the bottom conversation entry shows Pending creation until the first Session exists. A per-run destination instead shows Latest run conversation after its first delivery and hides the entry before that delivery; earlier conversations remain accessible from delivery records. Available links recheck membership and archive state before opening; missing or archived Sessions remain disabled.
|
||||
|
||||
The repeat editor offers once, minute, hour, day, week, month, and custom rules. Date and clock controls reuse existing pickers. Guided presets produce RRULE; minute and hour intervals start from the current minute in the selected zone. The Custom choice and Customize input do not name either syntax; the input accepts a two-line RRULE or a five-field Cron expression with an explicit zone. RRULE retains the zone in `DTSTART`; Cron retains its expression and selected zone as Cron timing. Complex RRULE values remain verbatim. Save validates Custom text through the Host; invalid or empty input keeps the draft open and shows the existing correction message. Existing After, At, Every, Daily, and Weekly records show their description in Custom and keep their typed timing until a replacement is entered. Editing other fields preserves the committed occurrence.
|
||||
The repeat editor offers once, minute, hour, day, week, month, and custom rules. Date and clock controls reuse existing pickers. Guided presets produce RRULE; minute and hour intervals start from the current minute in the selected zone. The Custom choice and Customize input do not name either syntax; the input accepts a two-line RRULE or a five-field Cron expression with an explicit zone. RRULE retains the zone in `DTSTART`; Cron retains its expression and selected zone as Cron timing. Complex RRULE values remain verbatim. The shared time parser checks new or changed Custom text before enabling Save; invalid or empty input keeps the draft and shows the correction message. The Host performs the final validation on save. Existing After, At, Every, Daily, and Weekly records show their description in Custom and keep their typed timing until a replacement is entered. Editing other fields preserves the committed occurrence.
|
||||
|
||||
Pause and resume update lifecycle state. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables Edit, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt.
|
||||
Pause and resume update lifecycle state. Unsaved changes hold pause, resume, Run now, and Delete until you save or discard them. The detail menu offers Run now and Delete. It offers no queued-message cancellation: one inbox message may contain deliveries from several tasks. While a delivery to a reused conversation is queued or running, the detail disables its fields, Save, pause and resume, Run now, and Delete, and states that the task is queued or running and is managed in its conversation, which the bottom conversation entry opens. The minimum delivery interval disables another immediate run until the interval ends, while pause and deletion remain available once execution is idle. When the interval is the only cause, the Run now row stays focusable, and its tooltip states that the minimum run interval has not passed and when Run now becomes available. An archived linked conversation of a task already bound to a Session also disables Run now, because the Host refuses that delivery. A run that the Host refuses with `schedule_execution_pending` shows a status notice instead of an error. Deletion requires confirmation, removes the task and its saved records, retains Sessions and already-delivered messages, and reports the result through the existing app-wide toast. The confirmation focuses Cancel first; when it closes, focus returns to the detail menu button. The detail keeps the task until the Host answers. An applied deletion closes the detail or its task tab; a failed deletion keeps the task open for another attempt.
|
||||
|
||||
The list, detail, header, and Session hover show the later of the scheduled occurrence and the Host delivery floor as the next run. Creation and editing show one short minimum-interval hint for per-run conversation targets, read from `schedule.deliveryLimits`; a failed read offers Retry. The read-only detail keeps the next-run time without repeating that hint. Scheduled and immediate runs share this limit.
|
||||
The list, detail, header, and Session hover show the later of the scheduled occurrence and the Host delivery floor as the next run. Creation and editing show one short minimum-interval hint for per-run conversation targets, read from `schedule.deliveryLimits`; a failed read offers Retry. Scheduled and immediate runs share this limit.
|
||||
|
||||
Records lazily requests 20 saved deliveries, supports newest-first pagination, retains loaded records after failure, and ignores superseded or unmounted requests. Each record shows its occurrence and saved prompt, with Expand / Collapse for long prompts; legacy records without prompt text never substitute the current instruction. A receipt's actual destination has a conversation link when the Session is available. Confirmed pruning is stated only after the final saved page and offers the current retention explanation. These records acknowledge inbox delivery, not model execution success.
|
||||
|
||||
@@ -55,7 +55,7 @@ Task menus use the [standard menu geometry](../../../docs/ui-radius.md#nested-ho
|
||||
<details>
|
||||
<summary>Implementation details — click to expand</summary>
|
||||
|
||||
While the Peer may read `schedule/catalog`, the plugin registers the existing `schedules` main panel, Session header utility, Turn tail card, Session row mark and hover entries, and `scheduleTask` right Sidebar tab. Slot injection supplies framework readers and action callbacks; components own disposable selection, search, form, and paging state. The Host owns task storage and execution. Browsing catalogs does not activate a Session.
|
||||
While the Peer may read `schedule/catalog`, the plugin registers the existing `schedules` main panel, Session header utility, Turn tail card, Session row mark and hover entries, and `scheduleTask` right Sidebar tab. Slot injection supplies framework readers and action callbacks; components own selection, search, and paging state. Entry-declared stores retain each task draft and its CAS baseline across navigation within their root or Session scope; the main panel and Session tabs have independent drafts. Pristine forms follow the catalog. A dirty form retains all fields and its original revision. A newer catalog revision prevents saving until the user discards the draft or explicitly reapplies changed title, prompt, timing, and target groups to that revision. Reapplying does not write; the user reviews the resulting form and saves with the new CAS baseline. Untouched groups follow the newer record. Missing tasks retain editable local drafts while Host mutations stay disabled. Drafts are not persisted; a Client reload or disposal of the owning entry or Session scope drops them. The Host owns task storage and execution. Browsing catalogs does not activate a Session. Conflict feedback reuses the catalog notice style; its outlined review action wraps below the message in narrow panes.
|
||||
|
||||
The manager, task tabs, row marks, and conversation-header projections share one observable `schedule.catalog` source. Header and row views filter active records by involvement and delivery target. Mutations use task-id-based `schedule.create`, `schedule.edit`, and `schedule.run`; history uses task identity and cursor without a Session ownership parameter. A mutation acknowledgment triggers a fresh authoritative read; a failed read remains a catalog error rather than changing the acknowledged write into a failure.
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ kind: "package-reference"
|
||||
|
||||
## 概述
|
||||
|
||||
自动化任务页和右侧栏任务页签共用任务规则、本地编辑、已保存的投递记录、删除及会话导航。手动创建和执行目标选择使用宿主的 Schedule 服务;会话卡片、页头时钟和会话行标记保留现有位置。
|
||||
自动化任务页和右侧栏任务页签使用同一编辑器处理任务规则、已保存的投递记录、删除及会话导航。手动创建和执行目标选择使用宿主的 Schedule 服务;会话卡片、页头时钟和会话行标记保留现有位置。
|
||||
|
||||
## 目录
|
||||
|
||||
@@ -27,17 +27,17 @@ kind: "package-reference"
|
||||
|
||||
宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。
|
||||
|
||||
发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”保留现有行为:进入新会话,由用户输入指令。相邻下拉提供“在对话中创建”和“手动创建”。手动创建打开共用 Modal,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。
|
||||
发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”保留现有行为:进入新会话,由用户输入指令。相邻下拉提供“在对话中创建”和“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。
|
||||
|
||||
“已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务打开“规则 / 任务运行记录”。编辑暂存草稿;保存发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。未改动的保存仍要求宿主写入当前行格式。成功后返回只读视图并聚焦“编辑”。冲突保留草稿并提供“重新加载”;取消丢弃草稿。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。
|
||||
“已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。
|
||||
|
||||
执行位置下拉提供“新建对话并复用”和“每次新建对话”,手动创建默认前者。已经关联会话的任务,执行位置显示“当前关联对话”;编辑时保留原目标,只有用户主动选择新方式才会切换。“关联工作区”选择器列出框架工作区目录,在每个工作区名称下显示其路径,并以本地化默认名称标注首次使用时创建的工作区。新的执行位置默认使用该工作区;没有该工作区时使用列表中的第一个。没有目录的已有任务显示“未分组”,因为它创建的会话不加入任何工作区。复用目标的首次会话尚未存在时,详情底部入口显示“待创建”。每次新建的目标在首次投递后显示“最近运行对话”,首次投递前隐藏该入口;更早的对话仍可从任务运行记录进入。可用链接在打开前再次检查会话是否仍存在、是否归档;缺失或归档会话保持禁用。
|
||||
|
||||
重复编辑提供仅一次、每分钟、每小时、每天、每周、每月和自定义规则。日期和时间控件复用已有选择器。引导选项生成 RRULE;分钟和小时间隔从所选时区的当前分钟开始。自定义选项和自定义输入框不提示任何语法名称;输入框接受两行 RRULE 或带显式时区的五字段 Cron。RRULE 在 `DTSTART` 中保留时区;Cron 将表达式和所选时区保留为 Cron 时间类型。复杂 RRULE 保持原文。保存通过 Host 校验自定义文本;无效或空输入保持草稿打开,并显示已有纠正提示。已有 After、At、Every、Daily、Weekly 记录在自定义中显示描述,并在输入替代规则前保留原类型。编辑其他字段保留已提交发生时点。
|
||||
重复编辑提供仅一次、每分钟、每小时、每天、每周、每月和自定义规则。日期和时间控件复用已有选择器。引导选项生成 RRULE;分钟和小时间隔从所选时区的当前分钟开始。自定义选项和自定义输入框不提示任何语法名称;输入框接受两行 RRULE 或带显式时区的五字段 Cron。RRULE 在 `DTSTART` 中保留时区;Cron 将表达式和所选时区保留为 Cron 时间类型。复杂 RRULE 保持原文。新的或已修改的自定义文本由共享时间解析器校验,校验通过后才能保存;无效或空输入保留草稿并显示纠正提示。宿主在保存时执行最终校验。已有 After、At、Every、Daily、Weekly 记录在自定义中显示描述,并在输入替代规则前保留原类型。编辑其他字段保留已提交发生时点。
|
||||
|
||||
暂停和恢复修改生命周期状态。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用编辑、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。
|
||||
暂停和恢复修改生命周期状态。有未保存修改时,先保存或放弃更改,才能暂停、恢复、立即执行或删除。详情菜单提供立即执行和删除,不提供取消排队消息:同一条收件箱消息可能包含多个任务的投递。投递到复用对话的投递排队或执行期间,详情禁用字段、保存、暂停与恢复、立即执行和删除,并说明此任务已排队或执行中,请在会话中管理任务;详情底部的会话入口打开该会话。最小投递间隔结束前禁用再次立即执行,执行空闲后仍可暂停或删除。仅因间隔禁用时,立即执行项仍可聚焦,其提示说明未满最小运行间隔,并给出可以立即执行的时间。已经关联会话的任务,其关联对话已归档时,同样禁用立即执行,因为宿主拒绝这次投递。宿主以 `schedule_execution_pending` 拒绝的立即执行显示为状态提示,而非错误。删除需要确认,移除任务及其已保存记录,保留会话和已经投递的消息,并通过现有应用级提示报告结果。确认对话框首先聚焦“取消”;对话框关闭后,焦点回到详情菜单按钮。宿主答复之前,详情保持显示该任务。删除生效后关闭详情或其任务页签;删除失败时保留任务,以便再次尝试。
|
||||
|
||||
列表、详情、页头和会话悬浮内容的下次运行时间,取计划发生时间和宿主最早允许投递时间中较晚的一项。创建和编辑“每次新建对话”时,通过 `schedule.deliveryLimits` 读取宿主配置,以一句短提示显示最小间隔;读取失败可重试。只读详情保留下次运行时间,不重复该提示。定时与立即执行共用此限制。
|
||||
列表、详情、页头和会话悬浮内容的下次运行时间,取计划发生时间和宿主最早允许投递时间中较晚的一项。创建和编辑“每次新建对话”时,通过 `schedule.deliveryLimits` 读取宿主配置,以一句短提示显示最小间隔;读取失败可重试。定时与立即执行共用此限制。
|
||||
|
||||
“任务运行记录”按需请求 20 条已保存投递,支持从新到旧分页,失败时保留已加载记录,并忽略被刷新替代或卸载后的请求。每条记录显示投递发生时间与已保存指令,长指令可展开、收起;缺少指令的旧记录不使用当前指令替代。回执的实际执行会话可用时提供入口。仅在最后一页且确认裁剪后显示清理提示,并提供当前保留规则说明。这些记录确认收件箱投递,不表示模型执行成功。
|
||||
|
||||
@@ -55,7 +55,7 @@ kind: "package-reference"
|
||||
<details>
|
||||
<summary>实现内部细节 — 点击展开</summary>
|
||||
|
||||
Peer 可读取 `schedule/catalog` 时,插件注册现有 `schedules` 主面板、会话页头功能位、轮次尾部卡片、会话行标记与悬浮内容,以及 `scheduleTask` 右侧栏页签。槽位注入提供框架读取器与操作回调;组件拥有可丢弃的选择、搜索、表单和分页状态。宿主拥有任务存储与执行。浏览目录不会激活会话。
|
||||
Peer 可读取 `schedule/catalog` 时,插件注册现有 `schedules` 主面板、会话页头功能位、轮次尾部卡片、会话行标记与悬浮内容,以及 `scheduleTask` 右侧栏页签。槽位注入提供框架读取器与操作回调;组件拥有选择、搜索和分页状态。入口声明的存储在根或会话作用域中按任务保留草稿和 CAS 基线,支持导航后恢复;主面板与会话页签的草稿相互独立。未修改的表单跟随目录更新。已修改的表单保留全部字段及原版本。目录出现新版本后,须放弃草稿,或由用户明确将改过的名称、内容、时间和目标字段组重新应用到该版本,才能保存。此操作不写入任务;用户复核结果后,以新版本作为 CAS 基线保存。未修改的字段组采用新记录的值。任务缺失时保留可编辑的本地草稿,宿主修改操作仍禁用。草稿不持久化;客户端重新加载,或所属入口、会话作用域销毁时,草稿随之释放。宿主拥有任务存储与执行。浏览目录不会激活会话。冲突反馈沿用目录提示样式;复核按钮采用描边样式,在窄面板中换到提示下方。
|
||||
|
||||
管理页、任务页签、行标记和会话页头投影共享一个可观察的 `schedule.catalog` 数据源。页头与会话行根据关联关系和执行目标筛选活动记录。修改使用基于任务 id 的 `schedule.create`、`schedule.edit` 和 `schedule.run`;历史使用任务标识和游标,不携带会话所有权参数。修改确认后发起新的权威读取;回读失败仍是目录错误,不将已经确认的写入改判为失败。
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@
|
||||
"@deepseek-ai/dsh-api-workspace-controller": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-connection": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-locale": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-store": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-test-runtime": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-conversation": "workspace:*",
|
||||
"@deepseek-ai/dsh-client-ui-layout": "workspace:*",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* offer identical fields, Host edits and runs, saved deliveries, confirmed
|
||||
* deletion, and the linked Session entry. A record restored by a reload carries
|
||||
* no parameters, so the body falls back to the provider-owned binding that the
|
||||
* navigation wrote; a task that an open edit or a confirmed deletion retained
|
||||
* navigation wrote; a task that an unsaved draft or a confirmed deletion retained
|
||||
* keeps the detail on screen after the catalog row disappears, and an applied
|
||||
* deletion closes this tab once the catalog refresh after it settles; without a
|
||||
* retained task, the body reports that the task is gone.
|
||||
@@ -23,6 +23,7 @@ import type { CatalogSnapshot } from './catalog-source.ts'
|
||||
import { CatalogFeedback } from './CatalogFeedback.tsx'
|
||||
import { TaskDetail, useTaskDetail, type TaskDetailInjected } from './TaskDetail.tsx'
|
||||
import type { TaskTabBindings } from './task-tab-bindings.ts'
|
||||
import type { TaskEditorStoreProps } from './editor-store.ts'
|
||||
import { useTaskTabTarget } from './task-tab-target.ts'
|
||||
import css from './TaskManagerPage.module.css'
|
||||
|
||||
@@ -43,6 +44,7 @@ export interface ScheduleTaskTabInjected extends TaskDetailInjected, ScheduleTas
|
||||
|
||||
/** Props of the task tab's body: the tab it draws, localized copy, and its catalog face. */
|
||||
export type ScheduleTaskTabProps = PropsRuntime<'sidebar.right.pane.tab'>
|
||||
& TaskEditorStoreProps
|
||||
& PropsLocale<'schedule.manager'>
|
||||
& InjectFace<ScheduleTaskTabInjected>
|
||||
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
/** Manual creation reuses the existing Modal and Rules editor controls. */
|
||||
import { useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ScheduleCatalogEntry, ScheduleCreateRequest } from '@deepseek-ai/dsh-schedule/client'
|
||||
import { Button, Modal } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { TaskEditorFields, draftTarget, newTaskDraft, taskDraftValid } from './TaskEditorFields.tsx'
|
||||
import type { ProjectChoices } from './TaskEditorFields.tsx'
|
||||
import { timingFromDraft } from './editor-timing.ts'
|
||||
import type { HostTaskActions } from './TaskDetail.tsx'
|
||||
import { NewSessionLimit } from './NewSessionLimit.tsx'
|
||||
import css from './TaskManagerPage.module.css'
|
||||
|
||||
/** Creation outcome retains Host validation and never closes a failed draft. */
|
||||
export type TaskCreateOutcome = { readonly created: ScheduleCatalogEntry }
|
||||
| { readonly failed: 'host.createError' | 'host.notFuture' | 'host.invalidRule' }
|
||||
|
||||
/** Create one task without starting an Agent or sending its instruction. */
|
||||
export function TaskCreateDialog({ projects, onCreate, onClose, onCreated, loadNewSessionInterval, t }: PropsLocale<'schedule.manager'> & {
|
||||
readonly projects: ProjectChoices
|
||||
readonly loadNewSessionInterval: HostTaskActions['loadNewSessionInterval']
|
||||
readonly onCreate: (request: ScheduleCreateRequest) => Promise<TaskCreateOutcome>
|
||||
readonly onClose: () => void
|
||||
readonly onCreated: (task: ScheduleCatalogEntry) => void
|
||||
}): ReactNode {
|
||||
const [input, setDraft] = useState(newTaskDraft)
|
||||
// An unchosen directory follows the starting Workspace, which can arrive after the dialog opens.
|
||||
const draft = input.cwd === '' ? { ...input, cwd: projects.defaultCwd } : input
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<Extract<TaskCreateOutcome, { failed: string }>['failed'] | null>(null)
|
||||
const save = async (): Promise<void> => {
|
||||
setPending(true)
|
||||
setFailure(null)
|
||||
const outcome = await onCreate({
|
||||
title: draft.title, prompt: draft.prompt, timing: timingFromDraft(draft, true), target: draftTarget(draft),
|
||||
})
|
||||
setPending(false)
|
||||
if ('created' in outcome) onCreated(outcome.created)
|
||||
else setFailure(outcome.failed)
|
||||
}
|
||||
return <Modal open className={css.manualDialog as string} title={t('host.manualCreate')}
|
||||
closeLabel={t('host.closeCreate')} onClose={() => { if (!pending) onClose() }}
|
||||
footer={<div className={css.confirmActions}>
|
||||
<Button disabled={pending} onClick={onClose}>{t('delete.cancel')}</Button>
|
||||
<Button variant="primary" disabled={pending || !taskDraftValid(draft)} onClick={() => { void save() }}>
|
||||
{t(pending ? 'host.creating' : 'host.create')}
|
||||
</Button>
|
||||
</div>}>
|
||||
<TaskEditorFields draft={draft} onChange={setDraft} projects={projects} disabled={pending} t={t} />
|
||||
{draft.target === 'new' && <NewSessionLimit load={loadNewSessionInterval} t={t} />}
|
||||
{failure !== null && <p className={css.saveFailure} role="alert">{t(failure)}</p>}
|
||||
</Modal>
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
/** One task's rule, saved deliveries, edits, runs, and linked Session. */
|
||||
import { useEffect, useId, useRef, useState } from 'react'
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { flushSync } from 'react-dom'
|
||||
import clsx from 'clsx'
|
||||
import type { PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ScheduleCatalogEntry, ScheduleEditRequest, ScheduleId } from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { ScheduleCatalogEntry, ScheduleCreateRequest, ScheduleEditRequest, ScheduleId } from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import {
|
||||
@@ -14,9 +13,11 @@ import {
|
||||
import { CatalogFeedback } from './CatalogFeedback.tsx'
|
||||
import { DeliveryHistory, type DeliveryHistoryInjected } from './DeliveryHistory.tsx'
|
||||
import type { CatalogDeleteOutcome, CatalogSnapshot } from './catalog-source.ts'
|
||||
import { TaskEditorFields, draftTarget, projectChoices, targetLabelKey, taskDraft, taskDraftValid } from './TaskEditorFields.tsx'
|
||||
import { TaskEditorFields, draftTarget, newTaskDraft, projectChoices, reapplyTaskDraft, taskDraft, taskDraftPatch, taskDraftValid } from './TaskEditorFields.tsx'
|
||||
import type { TaskEditorDraft } from './TaskEditorFields.tsx'
|
||||
import type { TaskEditorStoreProps } from './editor-store.ts'
|
||||
import { timingFromDraft } from './editor-timing.ts'
|
||||
import { formatAvailableAt, formatScheduleFrequency, nextRunParts, recordTimeZone, zoneLabel } from './schedule-format.ts'
|
||||
import { formatAvailableAt, nextRunParts, recordTimeZone } from './schedule-format.ts'
|
||||
import { sessionLinkState } from './session-link.ts'
|
||||
import { taskNextRunAt, taskSessionId } from './task-record.ts'
|
||||
import { NewSessionLimit } from './NewSessionLimit.tsx'
|
||||
@@ -29,6 +30,10 @@ export type HostEditFailure = 'host.saveError' | 'host.conflict' | 'host.notFutu
|
||||
/** Localized reason the Host refused a run, or reason the wiring could not confirm it. */
|
||||
export type HostRunFailure = 'host.runError' | 'host.executionPending' | 'detail.missing'
|
||||
|
||||
/** Creation keeps a failed draft and never creates or activates its destination Session. */
|
||||
export type TaskCreateOutcome = { readonly created: ScheduleCatalogEntry }
|
||||
| { readonly failed: 'host.createError' | 'host.notFuture' | 'host.invalidRule' }
|
||||
|
||||
/** Target-based mutations supplied by the owning plugin's Remote wiring. */
|
||||
export interface HostTaskActions {
|
||||
/**
|
||||
@@ -76,28 +81,21 @@ export interface TaskDetailInjected extends DeliveryHistoryInjected {
|
||||
}
|
||||
|
||||
/** One task's detail, as the Tasks page and the task tab both compose it. */
|
||||
export type TaskDetailProps = TaskDetailInjected
|
||||
type TaskDetailCommonProps = TaskDetailInjected
|
||||
& TaskEditorStoreProps
|
||||
& PropsLocale<'schedule.manager'>
|
||||
& Pick<PropsRuntime<'main'>, 'useSessions' | 'useWorkspaces'>
|
||||
& {
|
||||
/** Task shown; an authoritative catalog row refreshes on its own outside an open edit. */
|
||||
readonly task: ScheduleCatalogEntry
|
||||
/**
|
||||
* Whether an authoritative catalog row backs the shown task; a retained task alone disables its edit, pause,
|
||||
* run, and delete entries.
|
||||
*/
|
||||
readonly authoritative: boolean
|
||||
/** Element id shared by the detail panels and any control that points at them. */
|
||||
readonly id: string
|
||||
/** Catalog query state; loading keeps every action visible and disabled. */
|
||||
/** Catalog query state; loading disables saved-task actions. */
|
||||
readonly status: 'loading' | 'ready' | 'error'
|
||||
/** Tasks with a deletion in flight. */
|
||||
readonly deleting: readonly ScheduleId[]
|
||||
/**
|
||||
* Report the task that an open edit started from or that a confirmed deletion is removing, so its owner
|
||||
* retains it outside the catalog, or null when that edit closes or the Host does not apply that deletion.
|
||||
* Retain a task while a confirmed deletion and its catalog refresh settle.
|
||||
*/
|
||||
readonly onEditState: (task: ScheduleCatalogEntry | null) => void
|
||||
readonly onRetainTask: (task: ScheduleCatalogEntry | null) => void
|
||||
/** Active detail view; the owner resets it to Rules when it selects another task. */
|
||||
readonly tab: TaskDetailTab
|
||||
/** Select the active detail view. */
|
||||
@@ -115,44 +113,60 @@ export type TaskDetailProps = TaskDetailInjected
|
||||
readonly onClose?: () => void
|
||||
}
|
||||
|
||||
/** One task detail's editing state, as its Tasks page or task tab owns it. */
|
||||
/** New and existing tasks use the same editable page; only submission and saved-task actions differ. */
|
||||
export type TaskDetailProps = TaskDetailCommonProps & ({
|
||||
readonly task: ScheduleCatalogEntry
|
||||
readonly authoritative: boolean
|
||||
readonly onCreateTask?: never
|
||||
readonly onCreated?: never
|
||||
} | {
|
||||
readonly task?: undefined
|
||||
readonly authoritative?: never
|
||||
readonly onCreateTask: (request: ScheduleCreateRequest) => Promise<TaskCreateOutcome>
|
||||
readonly onCreated: (task: ScheduleCatalogEntry) => void
|
||||
})
|
||||
|
||||
/** One task detail's selected tab, confirmation, and retained catalog row. */
|
||||
export interface TaskDetailController {
|
||||
/** Catalog row the shown id resolves to, or undefined when the read has no such row. */
|
||||
readonly record: ScheduleCatalogEntry | undefined
|
||||
/** Task to show: the catalog row, or the task that an open edit or a confirmed deletion retained. */
|
||||
/** Task to show: the catalog row, an unsaved draft's baseline, or a confirmed deletion's retained row. */
|
||||
readonly task: ScheduleCatalogEntry | undefined
|
||||
/** Props the shared detail element takes, without the task it shows. */
|
||||
readonly props: Omit<TaskDetailProps, 'task' | 'authoritative' | 'onClose' | 'onDeleted'>
|
||||
readonly props: Omit<TaskDetailCommonProps, 'onClose' | 'onDeleted'>
|
||||
}
|
||||
|
||||
/**
|
||||
* Own the editing state one task detail shares across both of its owners.
|
||||
* Own selected-task state shared by the Tasks page and task tabs.
|
||||
*
|
||||
* The shown task is the catalog row for `taskId`, or the task that an open edit
|
||||
* or a confirmed deletion of that row retained after the row left the catalog.
|
||||
* The view, the confirmation, and the retained task all reset when `taskId`
|
||||
* changes, so one task's edit never carries into another.
|
||||
* The shown task comes from the catalog, an unsaved form's CAS baseline, or a
|
||||
* confirmed deletion. The view and confirmation reset when selection changes;
|
||||
* the entry's store retains unsaved fields by task identity.
|
||||
* @param injected - detail actions, localized copy, and framework readers.
|
||||
* @param catalog - the owner's authoritative task catalog snapshot.
|
||||
* @param taskId - task the owner selected, or undefined when it selected none.
|
||||
* @returns the shown task and catalog row, its element id, its confirmation, and the detail props.
|
||||
*/
|
||||
export function useTaskDetail(
|
||||
injected: TaskDetailInjected & PropsLocale<'schedule.manager'> & Pick<PropsRuntime<'main'>, 'useSessions' | 'useWorkspaces'>,
|
||||
injected: TaskDetailInjected & TaskEditorStoreProps & PropsLocale<'schedule.manager'> & Pick<PropsRuntime<'main'>, 'useSessions' | 'useWorkspaces'>,
|
||||
catalog: CatalogSnapshot<ScheduleCatalogEntry>,
|
||||
taskId: ScheduleId | undefined,
|
||||
): TaskDetailController {
|
||||
const [draft, setDraft] = useState<ScheduleCatalogEntry | null>(null)
|
||||
const [retained, setRetained] = useState<ScheduleCatalogEntry | null>(null)
|
||||
const [tab, setTab] = useState<TaskDetailTab>('rule')
|
||||
const [confirmId, setConfirmId] = useState<ScheduleId | null>(null)
|
||||
const id = useId()
|
||||
const savedDraft = injected.useStore(state => taskId === undefined ? undefined : state.drafts[`task:${taskId}`])
|
||||
useEffect(() => {
|
||||
setDraft(null)
|
||||
setRetained(null)
|
||||
setTab('rule')
|
||||
setConfirmId(null)
|
||||
}, [taskId])
|
||||
const record = taskId === undefined ? undefined : catalog.records.find(item => item.id === taskId)
|
||||
const task = record ?? (draft !== null && draft.id === taskId ? draft : undefined)
|
||||
const edited = record === undefined && savedDraft?.base !== undefined
|
||||
&& Object.keys(taskDraftPatch(savedDraft.draft, savedDraft.base)).length > 0
|
||||
? savedDraft.base : undefined
|
||||
const task = record ?? edited ?? (retained !== null && retained.id === taskId ? retained : undefined)
|
||||
return {
|
||||
record, task,
|
||||
props: {
|
||||
@@ -160,7 +174,7 @@ export function useTaskDetail(
|
||||
status: catalog.status,
|
||||
deleting: catalog.deleting,
|
||||
id,
|
||||
onEditState: setDraft,
|
||||
onRetainTask: setRetained,
|
||||
tab,
|
||||
onTabChange: setTab,
|
||||
confirmId,
|
||||
@@ -170,12 +184,12 @@ export function useTaskDetail(
|
||||
}
|
||||
|
||||
/**
|
||||
* Render one task's rule or saved deliveries; changing its id resets the edit.
|
||||
* Render one new or existing task's editable rule or saved deliveries.
|
||||
* @param props - Task, catalog state, detail view, confirmation, locale, and actions.
|
||||
* @returns The detail region and its deletion confirmation dialog.
|
||||
*/
|
||||
export function TaskDetail(props: TaskDetailProps): ReactNode {
|
||||
return <TaskDetailView key={props.task.id} {...props} />
|
||||
return <TaskDetailView key={props.task === undefined ? 'new' : `task:${props.task.id}`} {...props} />
|
||||
}
|
||||
|
||||
function TaskDetailView(props: TaskDetailProps): ReactNode {
|
||||
@@ -183,111 +197,131 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
|
||||
onRetry, onOpenSession, loadHistory, status, deleting, useSessions, useWorkspaces, t, hostActions } = props
|
||||
const sessions = useSessions(snapshot => snapshot)
|
||||
const workspaces = useWorkspaces(snapshot => snapshot)
|
||||
const [editing, setEditing] = useState(false)
|
||||
const [draft, setDraft] = useState(() => taskDraft(task))
|
||||
const [base, setBase] = useState(task)
|
||||
const [pending, setPending] = useState(false)
|
||||
const [failure, setFailure] = useState<HostEditFailure | HostRunFailure | null>(null)
|
||||
const key = task === undefined ? 'new' : `task:${task.id}`
|
||||
const stored = props.useStore(state => state.drafts[key])
|
||||
const [seed] = useState(newTaskDraft)
|
||||
const initial = stored?.initial ?? seed
|
||||
const changes = useMemo(() => stored?.base === undefined ? undefined : taskDraftPatch(stored.draft, stored.base),
|
||||
[stored?.draft, stored?.base])
|
||||
const storedDirty = changes !== undefined && Object.keys(changes).length > 0
|
||||
const cached = stored?.base !== undefined && !storedDirty && !stored.pending && stored.failure === undefined
|
||||
&& stored.base.updatedAt !== task?.updatedAt ? undefined : stored
|
||||
const base = cached?.base ?? task
|
||||
const input = cached?.draft ?? (task === undefined ? initial : taskDraft(task))
|
||||
const projects = projectChoices(workspaces.items, t('host.defaultProject'))
|
||||
// Until a directory is chosen, a new form follows the Workspace list as it arrives.
|
||||
const draft = task === undefined && input.cwd === '' ? { ...input, cwd: projects.defaultCwd } : input
|
||||
const dirty = base === undefined
|
||||
? JSON.stringify(draft) !== JSON.stringify({ ...initial, cwd: initial.cwd || projects.defaultCwd }) : storedDirty
|
||||
const valid = !dirty || taskDraftValid(draft, changes)
|
||||
const [actionPending, setPending] = useState(false)
|
||||
const [actionFailure, setFailure] = useState<HostEditFailure | HostRunFailure | null>(null)
|
||||
const saving = cached?.pending === true
|
||||
const pending = actionPending || saving
|
||||
const failure = !pending && dirty && base !== undefined && task !== undefined && base.updatedAt !== task.updatedAt
|
||||
? 'host.conflict' : actionFailure ?? cached?.failure ?? null
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const editRef = useRef<HTMLButtonElement>(null)
|
||||
const moreRef = useRef<HTMLButtonElement>(null)
|
||||
const panelRef = useRef<HTMLElement>(null)
|
||||
const scrollRef = useRef<HTMLDivElement>(null)
|
||||
const mounted = useRef(true)
|
||||
useLayoutEffect(() => {
|
||||
const scroll = scrollRef.current as HTMLDivElement
|
||||
const measure = (): void => {
|
||||
scroll.style.setProperty('--detail-scrollbar-space', `${scroll.offsetWidth - scroll.clientWidth}px`)
|
||||
}
|
||||
measure()
|
||||
const observer = new ResizeObserver(measure)
|
||||
observer.observe(scroll)
|
||||
return () => { observer.disconnect() }
|
||||
}, [tab])
|
||||
useEffect(() => {
|
||||
mounted.current = true
|
||||
panelRef.current?.focus({ preventScroll: true })
|
||||
return () => { mounted.current = false }
|
||||
}, [])
|
||||
const floorEndsAt = task.deliveryFloorEndsAt === undefined ? undefined : Date.parse(task.deliveryFloorEndsAt)
|
||||
const floorEndsAt = task?.deliveryFloorEndsAt === undefined ? undefined : Date.parse(task.deliveryFloorEndsAt)
|
||||
// A sample at the floor's end enables Run now when the interval passes, not up to one period later.
|
||||
const now = useRelativeClock(RELATIVE_CLOCK_PERIOD_MS, floorEndsAt)
|
||||
const busy = pending || status === 'loading' || deleting.includes(task.id)
|
||||
const executionActive = task.executionActive === true
|
||||
const deletingTask = task !== undefined && deleting.includes(task.id)
|
||||
const busy = pending || deletingTask || task !== undefined && status === 'loading'
|
||||
const executionActive = task?.executionActive === true
|
||||
const deliveryFloor = floorEndsAt !== undefined && floorEndsAt > now
|
||||
const linkedId = taskSessionId(task)
|
||||
const linkedId = task === undefined ? undefined : taskSessionId(task)
|
||||
const linkedText = linkedId === undefined ? '' : sessions.byId[linkedId]?.displayTitle ?? linkedId
|
||||
const linkedState = linkedId === undefined ? 'unavailable' : sessionLinkState(linkedId, sessions, workspaces)
|
||||
// The Host refuses to deliver to an archived target Session.
|
||||
const targetArchived = task.target.kind !== 'new' && linkedState === 'archived'
|
||||
const targetArchived = task?.target.kind !== 'new' && linkedState === 'archived'
|
||||
// Only the interval needs the row to explain itself: each other cause shows in the detail or is transient.
|
||||
const runHeld = busy || editing || executionActive || targetArchived || !props.authoritative
|
||||
const nextRunAt = taskNextRunAt(task)
|
||||
const next = nextRunParts(nextRunAt, t('time.locale'), now, t)
|
||||
const runHeld = busy || dirty || executionActive || targetArchived || !props.authoritative
|
||||
const nextRunAt = task === undefined ? '' : taskNextRunAt(task)
|
||||
const next = task === undefined ? undefined : nextRunParts(nextRunAt, t('time.locale'), now, t)
|
||||
// SessionListState gives every listed id a byId row.
|
||||
const choices = sessions.ids.map(value => ({ value, label: (sessions.byId[value] as SessionSummary).displayTitle }))
|
||||
const projects = projectChoices(workspaces.items, t('host.defaultProject'))
|
||||
|
||||
const beginEdit = (): void => {
|
||||
setBase(task)
|
||||
setDraft(taskDraft(task))
|
||||
const setDraft = (value: TaskEditorDraft): void => {
|
||||
props.actions.setDraft(key, { base, draft: value, ...(task === undefined ? { initial } : {}),
|
||||
...(cached?.failure === 'host.conflict' ? { failure: cached.failure } : {}) })
|
||||
setFailure(null)
|
||||
props.onEditState(task)
|
||||
setEditing(true)
|
||||
onTabChange('rule')
|
||||
}
|
||||
const reset = (): void => { props.actions.clearDraft(key); setFailure(null) }
|
||||
const save = async (): Promise<void> => {
|
||||
setPending(true)
|
||||
props.actions.setDraft(key, { base, draft, pending: true, ...(task === undefined ? { initial } : {}) })
|
||||
setFailure(null)
|
||||
const target = draftTarget(draft, base)
|
||||
const seeded = taskDraft(base)
|
||||
const timingChanged = JSON.stringify(timingFromDraft(draft)) !== JSON.stringify(timingFromDraft(seeded))
|
||||
const targetChanged = draft.target !== seeded.target || draft.sessionId !== seeded.sessionId || draft.cwd !== seeded.cwd
|
||||
const patch = {
|
||||
...(draft.title === base.title ? {} : { title: draft.title }),
|
||||
...(draft.prompt === base.prompt ? {} : { prompt: draft.prompt }),
|
||||
...(timingChanged ? { timing: timingFromDraft(draft, true) } : {}),
|
||||
...(targetChanged ? { target } : {}),
|
||||
}
|
||||
if (Object.keys(patch).length === 0) Object.assign(patch, { title: draft.title })
|
||||
const outcome = await hostActions.edit({ id: task.id, action: 'update', patch, expectedUpdatedAt: base.updatedAt ?? null })
|
||||
if (!mounted.current) return
|
||||
// The read-only view returns at once, so its Edit button can take back the focus of the removed Save button.
|
||||
flushSync(() => {
|
||||
setPending(false)
|
||||
if (outcome === 'saved') { setEditing(false); props.onEditState(null) }
|
||||
else setFailure(outcome.failed)
|
||||
})
|
||||
if (outcome === 'saved') editRef.current?.focus()
|
||||
const existingBase = base as ScheduleCatalogEntry
|
||||
const outcome = task === undefined
|
||||
? await props.onCreateTask({ title: draft.title.trim(), prompt: draft.prompt.trim(),
|
||||
timing: timingFromDraft(draft, true), target: draftTarget(draft) })
|
||||
: await hostActions.edit({ id: task.id, action: 'update', patch: taskDraftPatch(draft, existingBase, true),
|
||||
expectedUpdatedAt: existingBase.updatedAt ?? null })
|
||||
if (outcome === 'saved' || 'created' in outcome) {
|
||||
props.actions.clearDraft(key)
|
||||
if (mounted.current && outcome !== 'saved') props.onCreated?.(outcome.created)
|
||||
if (mounted.current && outcome === 'saved') panelRef.current?.focus({ preventScroll: true })
|
||||
} else props.actions.setDraft(key, { base, draft, failure: outcome.failed, ...(task === undefined ? { initial } : {}) })
|
||||
}
|
||||
const setActive = async (): Promise<void> => {
|
||||
const setActive = async (task: ScheduleCatalogEntry): Promise<void> => {
|
||||
setPending(true)
|
||||
const outcome = await hostActions.edit({ id: task.id, action: 'update', patch: { active: task.status !== 'active' }, expectedUpdatedAt: task.updatedAt ?? null })
|
||||
if (!mounted.current) return
|
||||
setPending(false)
|
||||
setFailure(outcome === 'saved' ? null : outcome.failed)
|
||||
}
|
||||
const run = async (): Promise<void> => {
|
||||
const run = async (id: ScheduleId): Promise<void> => {
|
||||
setMenuOpen(false)
|
||||
setPending(true)
|
||||
const outcome = await hostActions.run(task.id)
|
||||
const outcome = await hostActions.run(id)
|
||||
if (!mounted.current) return
|
||||
setPending(false)
|
||||
setFailure(outcome === 'queued' ? null : outcome.failed)
|
||||
}
|
||||
|
||||
return <>
|
||||
<aside ref={panelRef} tabIndex={-1} className={css.detail} id={id} aria-label={t('detail.label')}>
|
||||
<aside ref={panelRef} tabIndex={-1} className={css.detail} id={id} aria-busy={pending || deletingTask}
|
||||
aria-label={t(task === undefined ? 'host.manualCreate' : 'detail.label')}
|
||||
onKeyDown={(event) => {
|
||||
if (pending && event.key === 'Escape' && !event.defaultPrevented) { event.preventDefault(); event.stopPropagation() }
|
||||
}}>
|
||||
<div className={css.detailTabsBar}>
|
||||
<div className={css.detailTabs} role="tablist" aria-label={t('detail.tabs')}>
|
||||
{(['rule', 'records'] as const).map(value => <button key={value} type="button" role="tab"
|
||||
id={`${id}-${value}-tab`} aria-controls={`${id}-${value}-panel`} tabIndex={tab === value ? 0 : -1}
|
||||
aria-selected={tab === value} className={css.detailTab}
|
||||
onKeyDown={(event) => {
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
|
||||
event.preventDefault()
|
||||
const next = event.key === 'Home' ? 0 : event.key === 'End' ? 1 : value === 'rule' ? 1 : 0
|
||||
onTabChange(next === 0 ? 'rule' : 'records')
|
||||
const button = event.currentTarget.parentElement?.children[next]
|
||||
if (button instanceof HTMLButtonElement) button.focus()
|
||||
}}
|
||||
onClick={() => { onTabChange(value) }}>{t(value === 'rule' ? 'detail.rule' : 'detail.records')}</button>)}
|
||||
</div>
|
||||
{task === undefined ? <h2 className={css.createTitle}>{t('host.manualCreate')}</h2>
|
||||
: <div className={css.detailTabs} role="tablist" aria-label={t('detail.tabs')}>
|
||||
{(['rule', 'records'] as const).map(value => <button key={value} type="button" role="tab"
|
||||
id={`${id}-${value}-tab`} aria-controls={`${id}-${value}-panel`} tabIndex={tab === value ? 0 : -1}
|
||||
aria-selected={tab === value} className={css.detailTab}
|
||||
onKeyDown={(event) => {
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return
|
||||
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return
|
||||
event.preventDefault()
|
||||
const next = event.key === 'Home' ? 0 : event.key === 'End' ? 1 : value === 'rule' ? 1 : 0
|
||||
onTabChange(next === 0 ? 'rule' : 'records')
|
||||
const button = event.currentTarget.parentElement?.children[next]
|
||||
if (button instanceof HTMLButtonElement) button.focus()
|
||||
}}
|
||||
onClick={() => { onTabChange(value) }}>{t(value === 'rule' ? 'detail.rule' : 'detail.records')}</button>)}
|
||||
</div>}
|
||||
<div className={css.detailActions}>
|
||||
{!editing && <Button ref={editRef} size="sm" disabled={busy || executionActive || !props.authoritative} onClick={beginEdit}>{t('host.edit')}</Button>}
|
||||
<Tooltip label={t(task.status === 'active' ? 'host.pause' : 'host.resume')} side="bottom" delayMs={500} portal>
|
||||
<span><Button size="sm" className={css.detailIconButton} disabled={busy || editing || executionActive || task.status === 'ended' || !props.authoritative}
|
||||
aria-label={t(task.status === 'active' ? 'host.pause' : 'host.resume')} onClick={() => { void setActive() }}>
|
||||
{task !== undefined && <><Tooltip label={t(task.status === 'active' ? 'host.pause' : 'host.resume')} side="bottom" delayMs={500} portal>
|
||||
<span><Button size="sm" className={css.detailIconButton} disabled={busy || dirty || executionActive || task.status === 'ended' || !props.authoritative}
|
||||
aria-label={t(task.status === 'active' ? 'host.pause' : 'host.resume')} onClick={() => { void setActive(task) }}>
|
||||
{task.status === 'active' ? <IconPauseOutlineRegular /> : <IconPlayOutlineRegular />}
|
||||
</Button></span>
|
||||
</Tooltip>
|
||||
@@ -299,8 +333,8 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
|
||||
<MenuItemButton disabled={runHeld || deliveryFloor}
|
||||
disabledReason={deliveryFloor && !runHeld
|
||||
? t('host.runAfterInterval', { time: formatAvailableAt(floorEndsAt, t('time.locale'), now) }) : undefined}
|
||||
onSelect={() => { void run() }}>{t('host.run')}</MenuItemButton>
|
||||
<MenuItemButton disabled={busy || editing || executionActive || !props.authoritative}
|
||||
onSelect={() => { void run(task.id) }}>{t('host.run')}</MenuItemButton>
|
||||
<MenuItemButton disabled={busy || dirty || executionActive || !props.authoritative}
|
||||
onSelect={() => {
|
||||
// The dialog returns focus to the control that held it on open, not to the removed menu row.
|
||||
moreRef.current?.focus()
|
||||
@@ -309,55 +343,55 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
|
||||
}}>
|
||||
{t('delete.action')}
|
||||
</MenuItemButton>
|
||||
</Menu>
|
||||
{onClose !== undefined && <Button size="sm" className={css.detailIconButton} aria-label={t('detail.close')}
|
||||
</Menu></>}
|
||||
{onClose !== undefined && <Button size="sm" className={css.detailIconButton} aria-label={t(task === undefined ? 'host.closeCreate' : 'detail.close')}
|
||||
disabled={pending} onClick={onClose}><IconCloseOutlineRegular /></Button>}
|
||||
</div>
|
||||
</div>
|
||||
<div className={clsx(css.detailScroll, tab === 'records' && css.detailRecords)} role="tabpanel"
|
||||
id={`${id}-${tab}-panel`} aria-labelledby={`${id}-${tab}-tab`} tabIndex={0}>
|
||||
<div ref={scrollRef} className={clsx(css.detailScroll, tab === 'records' && css.detailRecords)} role={task === undefined ? undefined : 'tabpanel'}
|
||||
id={`${id}-${tab}-panel`} aria-labelledby={task === undefined ? undefined : `${id}-${tab}-tab`} tabIndex={0}>
|
||||
<CatalogFeedback status={status} populated onRetry={onRetry} t={t} />
|
||||
{tab === 'rule' && <>
|
||||
{!editing && <>
|
||||
{task !== undefined && <>
|
||||
<header className={css.detailHeader}><h2 className={css.readonlyName}>{task.title}</h2></header>
|
||||
<div className={css.nextRun}><p>{task.status === 'active'
|
||||
? <>{t('detail.nextRun')} <time dateTime={nextRunAt}>{next.absolute}</time>{' '}
|
||||
<span className={css.nextRunRelative}>{next.relative}</span></>
|
||||
? <>{t('detail.nextRun')} <time dateTime={nextRunAt}>{next?.absolute}</time>{' '}
|
||||
<span className={css.nextRunRelative}>{next?.relative}</span></>
|
||||
: t(`status.${task.status}`)}</p></div>
|
||||
<p className={css.readonlyPrompt}>{task.prompt}</p>
|
||||
<div className={css.ruleCard}>
|
||||
<div className={css.hostRuleRow}><span>{t('rule.repeat')}</span><span>{formatScheduleFrequency(task, t, {
|
||||
system: Intl.DateTimeFormat().resolvedOptions().timeZone, label: zone => zoneLabel(zone, t),
|
||||
})}</span></div>
|
||||
<div className={css.hostRuleRow}><span>{t('host.target')}</span><span>{t(targetLabelKey(task.target.kind))}</span></div>
|
||||
</div>
|
||||
{linkedId !== undefined && linkedState !== 'available' && task.target.kind === 'session'
|
||||
&& <p className={css.detailNotice} role="status">{t(linkedState === 'archived' ? 'detail.sessionArchived'
|
||||
: linkedState === 'loading' ? 'detail.sessionLoading' : 'detail.sessionUnavailable')}</p>}
|
||||
{/* A refused run states the same cause, so it alone reports a queued or running execution. */}
|
||||
{executionActive && failure !== 'host.executionPending'
|
||||
&& <p className={css.detailNotice} role="status">{t('host.executionActive')}</p>}
|
||||
{dirty && !props.authoritative && status === 'ready' && !deletingTask && failure !== 'detail.missing'
|
||||
&& <p className={css.detailNotice} role="status">{t('detail.missing')}</p>}
|
||||
</>}
|
||||
{editing && <TaskEditorFields draft={draft} onChange={setDraft} disabled={pending}
|
||||
projects={projects} original={base} t={t} />}
|
||||
{editing && draft.target === 'new'
|
||||
&& <NewSessionLimit load={hostActions.loadNewSessionInterval} t={t} />}
|
||||
{/* A refused run is an expected wait, not a failure of the Host or of the user's input. */}
|
||||
{failure === 'host.executionPending' ? <p className={css.detailNotice} role="status">{t(failure)}</p>
|
||||
{failure === 'host.conflict' ? <div className={clsx(css.notice, css.conflictNotice)}>
|
||||
<p role="alert">{t(failure)}</p>
|
||||
{changes !== undefined && dirty && task !== undefined && props.authoritative && status === 'ready'
|
||||
&& <Button variant="outline" size="sm" disabled={busy} onClick={() => {
|
||||
props.actions.setDraft(key, { base: task, draft: reapplyTaskDraft(draft, task, changes) })
|
||||
setFailure(null)
|
||||
panelRef.current?.focus({ preventScroll: true })
|
||||
}}>{t('host.reapply')}</Button>}
|
||||
</div> : failure === 'host.executionPending' ? <p className={css.detailNotice} role="status">{t(failure)}</p>
|
||||
: failure !== null && <p className={css.saveFailure} role="alert">{t(failure)}</p>}
|
||||
{failure === 'host.conflict' && <Button onClick={beginEdit}>{t('host.reload')}</Button>}
|
||||
<TaskEditorFields draft={draft} onChange={setDraft}
|
||||
disabled={pending || executionActive || deletingTask}
|
||||
projects={projects} original={base} t={t} />
|
||||
{draft.target === 'new'
|
||||
&& <NewSessionLimit load={hostActions.loadNewSessionInterval} t={t} />}
|
||||
{failure === null && dirty && !valid && draft.title.trim() !== '' && draft.prompt.trim() !== ''
|
||||
&& <p className={css.saveFailure} role="status">{t('rule.invalid')}</p>}
|
||||
</>}
|
||||
{tab === 'records' && <DeliveryHistory id={task.id} latestMessageId={task.lastDelivery?.messageId}
|
||||
{tab === 'records' && task !== undefined && <DeliveryHistory id={task.id} latestMessageId={task.lastDelivery?.messageId}
|
||||
timeZone={recordTimeZone(task)} loadHistory={loadHistory} onOpenSession={onOpenSession}
|
||||
sessionTitles={Object.fromEntries(choices.map(choice => [choice.value, choice.label]))}
|
||||
availableSessionIds={sessions.ids.filter(value => sessionLinkState(value, sessions, workspaces) === 'available')} t={t} />}
|
||||
</div>
|
||||
{editing ? <footer className={css.saveFooter}>
|
||||
<span className={css.saveNotice}>{t('rule.unsaved')}</span>
|
||||
<Button disabled={pending} onClick={() => { setEditing(false); props.onEditState(null); setFailure(null) }}>{t('rule.cancel')}</Button>
|
||||
<Button variant="primary" disabled={pending || !taskDraftValid(draft) || failure === 'host.conflict'}
|
||||
onClick={() => { void save() }}>{t(pending ? 'rule.saving' : 'rule.save')}</Button>
|
||||
</footer> : (task.target.kind !== 'new' || linkedId !== undefined) && <footer className={css.hostSessionFooter}>
|
||||
{task !== undefined && (task.target.kind !== 'new' || linkedId !== undefined) && <footer className={css.hostSessionFooter}>
|
||||
<span>{t(task.target.kind === 'new' ? 'host.latestConversation' : 'detail.session')}</span>
|
||||
{linkedId === undefined || (task.target.kind === 'new_once' && linkedState === 'unavailable')
|
||||
? <span className={css.hostSessionEmpty}>{t('host.sessionAfterFirstRun')}</span>
|
||||
@@ -367,21 +401,32 @@ function TaskDetailView(props: TaskDetailProps): ReactNode {
|
||||
{linkedText}<IconChevronRightOutlineRegular />
|
||||
</Button>}
|
||||
</footer>}
|
||||
{(tab === 'rule' || dirty) && <footer className={css.saveFooter}>
|
||||
<span className={css.saveNotice}>{dirty ? t('rule.unsaved') : ''}</span>
|
||||
<Button disabled={pending || task !== undefined && !dirty && failure === null}
|
||||
onClick={() => { reset(); if (task === undefined) onClose?.() }}>{t('rule.cancel')}</Button>
|
||||
<Button variant="primary" disabled={busy || !dirty || !valid || failure === 'host.conflict'
|
||||
|| task !== undefined && (!props.authoritative || executionActive)}
|
||||
onClick={() => { void save() }}>{t(saving ? task === undefined ? 'host.creating' : 'rule.saving' : task === undefined ? 'host.create' : 'rule.save')}</Button>
|
||||
</footer>}
|
||||
</aside>
|
||||
<Modal open={confirmId === task.id} className={css.confirmDialog as string} contentClassName={css.confirmContent as string}
|
||||
{task !== undefined && <Modal open={confirmId === task.id}
|
||||
className={css.confirmDialog as string} contentClassName={css.confirmContent as string}
|
||||
title={t('delete.title')} description={t('delete.description')} closeLabel={t('delete.close')} onClose={() => { onConfirm(null) }}
|
||||
footer={<div className={css.confirmActions}>
|
||||
<Button data-modal-autofocus onClick={() => { onConfirm(null) }}>{t('delete.cancel')}</Button>
|
||||
<Button disabled={busy} onClick={() => {
|
||||
onConfirm(null)
|
||||
setPending(true)
|
||||
// The refresh that drops the row lands before the outcome, so the owner retains the task until then.
|
||||
props.onEditState(task)
|
||||
props.onRetainTask(task)
|
||||
void onDelete(task.id).then((outcome) => {
|
||||
if (!mounted.current) return
|
||||
if (outcome === 'deleted') onDeleted()
|
||||
else props.onEditState(null)
|
||||
setPending(false)
|
||||
if (outcome === 'deleted') { props.actions.clearDraft(key); onDeleted() }
|
||||
else props.onRetainTask(null)
|
||||
})
|
||||
}}>{t('delete.confirm')}</Button>
|
||||
</div>}><p className={css.confirmPrompt}>{task.prompt}</p></Modal>
|
||||
</div>}><p className={css.confirmPrompt}>{task.prompt}</p></Modal>}
|
||||
</>
|
||||
}
|
||||
@@ -4,20 +4,20 @@ import { useId, useRef, useState } from 'react'
|
||||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { ScheduleCatalogEntry, ScheduleTargetRequest } from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { ScheduleCatalogEntry, SchedulePatch, ScheduleTargetRequest } from '@deepseek-ai/dsh-schedule/client'
|
||||
import { Cron, RRule } from '@deepseek-ai/dsh-util-time'
|
||||
import clsx from 'clsx'
|
||||
import { DEFAULT_WORKSPACE_DIRECTORY, workspaceDisplayTitle } from '@deepseek-ai/dsh-api-workspace-controller/default-workspace'
|
||||
import { IconClockOutlineRegular, Input, PathLabel } from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import { ClockPicker } from './ClockPicker.tsx'
|
||||
import { DatePicker } from './DatePicker.tsx'
|
||||
import { defaultTiming, rruleFromDraft, timingFromRecord } from './editor-timing.ts'
|
||||
import { defaultTiming, rruleFromDraft, timingFromDraft, timingFromRecord } from './editor-timing.ts'
|
||||
import type { FrequencyPreset, TimingDraft } from './editor-timing.ts'
|
||||
import { RuleSelectRow, RuleZoneRow } from './RuleSelectRow.tsx'
|
||||
import { formatScheduleFrequency, zoneLabel } from './schedule-format.ts'
|
||||
import type { FrequencyZone } from './schedule-format.ts'
|
||||
import { RuleStepper, RuleWeekdayRow } from './TaskRuleControls.tsx'
|
||||
import { IconCalendarOutlineRegular } from './CalendarIcon.tsx'
|
||||
import type { TaskManagerKey } from './task-manager-locales.ts'
|
||||
import css from './TaskManagerPage.module.css'
|
||||
|
||||
/** Local form values; only Save writes a task. */
|
||||
@@ -29,12 +29,9 @@ export interface TaskEditorDraft extends TimingDraft {
|
||||
readonly cwd: string
|
||||
}
|
||||
|
||||
/** A Session or project label supplied by the owning framework readers. */
|
||||
export interface EditorChoice { readonly value: string; readonly label: string }
|
||||
|
||||
/** Registered Workspaces offered as the directory of a created Session. */
|
||||
export interface ProjectChoices {
|
||||
readonly items: readonly EditorChoice[]
|
||||
interface ProjectChoices {
|
||||
readonly items: readonly { readonly value: string; readonly label: string }[]
|
||||
/** Directory a new destination starts with: the default Workspace, else the first listed one, else empty. */
|
||||
readonly defaultCwd: string
|
||||
}
|
||||
@@ -47,11 +44,6 @@ export function projectChoices(workspaces: WorkspaceSnapshot['items'], defaultNa
|
||||
}
|
||||
}
|
||||
|
||||
/** Name a destination strategy; a Session target is the conversation that the task already uses. */
|
||||
export function targetLabelKey(target: TaskEditorDraft['target']): TaskManagerKey {
|
||||
return target === 'session' ? 'host.currentConversation' : target === 'new_once' ? 'host.targetNewOnce' : 'host.targetNew'
|
||||
}
|
||||
|
||||
/** Initialize a new task without creating or activating a Session. */
|
||||
export function newTaskDraft(): TaskEditorDraft {
|
||||
return { ...defaultTiming(), title: '', prompt: '', target: 'new_once', sessionId: '', cwd: '' }
|
||||
@@ -67,8 +59,8 @@ export function taskDraft(task: ScheduleCatalogEntry): TaskEditorDraft {
|
||||
}
|
||||
|
||||
/** Required fields and guided selections that the form can validate locally. */
|
||||
export function taskDraftValid(draft: TaskEditorDraft): boolean {
|
||||
return draft.title.trim() !== '' && draft.prompt.trim() !== ''
|
||||
export function taskDraftValid(draft: TaskEditorDraft, changes?: SchedulePatch): boolean {
|
||||
const fieldsValid = draft.title.trim() !== '' && draft.prompt.trim() !== ''
|
||||
&& draft.title.trim().length <= 120
|
||||
&& (draft.target !== 'session' || draft.sessionId !== '')
|
||||
&& (draft.frequency === 'once' || draft.frequency === 'advanced'
|
||||
@@ -76,6 +68,40 @@ export function taskDraftValid(draft: TaskEditorDraft): boolean {
|
||||
&& (draft.frequency !== 'weekly' || draft.weekdays.length > 0)
|
||||
&& (draft.frequency !== 'monthly' || Number.isInteger(draft.monthDay) && draft.monthDay >= 1 && draft.monthDay <= 31)
|
||||
&& (draft.frequency !== 'daily' || /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(draft.dailyTime))
|
||||
if (!fieldsValid) return false
|
||||
// An untouched stored rule remains authoritative for a content-only edit.
|
||||
if (changes !== undefined && changes.timing === undefined) return true
|
||||
const timing = timingFromDraft(draft, true)
|
||||
if (timing.kind === 'cron') return Cron.parse(timing.cron.expression, timing.cron.time_zone).kind === 'accepted'
|
||||
if (timing.kind !== 'rrule') return true
|
||||
const parsed = RRule.parse(timing.rrule, { rejectIneffectiveSetPositions: true })
|
||||
return parsed.kind === 'accepted'
|
||||
}
|
||||
|
||||
/** Only meaningful field changes enter the CAS edit; untouched timing is never rewritten. */
|
||||
export function taskDraftPatch(draft: TaskEditorDraft, original: ScheduleCatalogEntry, intervalFromNow = false): SchedulePatch {
|
||||
const seeded = taskDraft(original)
|
||||
const timingChanged = JSON.stringify(timingFromDraft(draft)) !== JSON.stringify(timingFromDraft(seeded))
|
||||
const targetChanged = draft.target !== seeded.target || draft.sessionId !== seeded.sessionId || draft.cwd !== seeded.cwd
|
||||
return {
|
||||
...(draft.title.trim() === seeded.title.trim() ? {} : { title: draft.title.trim() }),
|
||||
...(draft.prompt.trim() === seeded.prompt.trim() ? {} : { prompt: draft.prompt.trim() }),
|
||||
...(timingChanged ? { timing: timingFromDraft(draft, intervalFromNow) } : {}),
|
||||
...(targetChanged ? { target: draftTarget(draft, original) } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
/** Reapply changed field groups only after the user chooses to review a newer revision. */
|
||||
export function reapplyTaskDraft(draft: TaskEditorDraft, latest: ScheduleCatalogEntry, changes: SchedulePatch): TaskEditorDraft {
|
||||
const { title, prompt, target, sessionId, cwd, ...timing } = draft
|
||||
const { title: latestTitle, prompt: latestPrompt, target: latestTarget,
|
||||
sessionId: latestSessionId, cwd: latestCwd, ...latestTiming } = taskDraft(latest)
|
||||
return {
|
||||
...(changes.timing === undefined ? latestTiming : timing),
|
||||
title: changes.title === undefined ? latestTitle : title,
|
||||
prompt: changes.prompt === undefined ? latestPrompt : prompt,
|
||||
...(changes.target === undefined ? { target: latestTarget, sessionId: latestSessionId, cwd: latestCwd } : { target, sessionId, cwd }),
|
||||
}
|
||||
}
|
||||
|
||||
/** Resolve the explicit destination, preserving an existing preset when the project is unchanged. */
|
||||
@@ -95,7 +121,7 @@ export function TaskEditorFields({ draft, onChange, projects, disabled, original
|
||||
readonly onChange: (draft: TaskEditorDraft) => void
|
||||
readonly projects: ProjectChoices
|
||||
readonly disabled: boolean
|
||||
readonly original?: ScheduleCatalogEntry
|
||||
readonly original?: ScheduleCatalogEntry | undefined
|
||||
readonly t: PropsLocale<'schedule.manager'>['t']
|
||||
}): ReactNode {
|
||||
const [dateOpen, setDateOpen] = useState(false)
|
||||
@@ -107,7 +133,9 @@ export function TaskEditorFields({ draft, onChange, projects, disabled, original
|
||||
const change = (patch: Partial<TaskEditorDraft>): void => { onChange({ ...draft, ...patch }) }
|
||||
const clock = draft.frequency === 'daily' ? `${draft.dailyTime}:00` : draft.start.slice(11)
|
||||
const frequencyZone: FrequencyZone = { system: Intl.DateTimeFormat().resolvedOptions().timeZone, label: zone => zoneLabel(zone, t) }
|
||||
const targetLabel = (target: TaskEditorDraft['target']): string => t(targetLabelKey(target))
|
||||
const targetLabel = (target: TaskEditorDraft['target']): string =>
|
||||
t(target === 'session' ? 'host.currentConversation' : target === 'new_once' ? 'host.targetNewOnce' : 'host.targetNew')
|
||||
const currentSessionId = original?.target.kind === 'session' ? original.target.sessionId : ''
|
||||
const weekdays = draft.frequency === 'weekly' && draft.weekdays.length === 5 && [1, 2, 3, 4, 5].every(day => draft.weekdays.includes(day))
|
||||
const frequencyItems = [
|
||||
{ id: 'weekly', label: t('rule.weekly') }, { id: 'weekdays', label: t('rule.weekdays') },
|
||||
@@ -127,18 +155,22 @@ export function TaskEditorFields({ draft, onChange, projects, disabled, original
|
||||
if (dateOpen) { setDateOpen(false); dateAnchor.current?.focus() }
|
||||
else { setClockOpen(false); clockAnchor.current?.focus() }
|
||||
}}>
|
||||
<label className={css.editorField}>{t('detail.name')}<Input value={draft.title} maxLength={120}
|
||||
<label className={css.editorField}>{t('detail.name')}<Input value={draft.title} maxLength={120} aria-required placeholder={t('detail.namePlaceholder')}
|
||||
onChange={(event) => { change({ title: event.target.value }) }} /></label>
|
||||
<label className={css.editorField}>{t('detail.instruction')}<textarea className={css.instruction}
|
||||
<label className={css.editorField}>{t('detail.instruction')}<textarea className={css.instruction} aria-required placeholder={t('detail.instructionPlaceholder')}
|
||||
value={draft.prompt} onChange={(event) => { change({ prompt: event.target.value }) }} /></label>
|
||||
<div className={css.ruleRows}>
|
||||
<RuleSelectRow label={t('host.target')} value={draft.target} current={targetLabel(draft.target)} disabled={disabled}
|
||||
listClassName={css.targetMenu} items={(['new_once', 'new'] as const).map(value => ({
|
||||
id: value, label: <span className={css.targetMenuItem}><span>{targetLabel(value)}</span>
|
||||
<span className={css.targetMenuDescription}>{t(value === 'new_once' ? 'host.targetNewOnceHelp' : 'host.targetNewHelp')}</span></span>,
|
||||
}))}
|
||||
listClassName={css.targetMenu} items={[
|
||||
...(currentSessionId === '' ? [] : [{ id: 'session', label: targetLabel('session') }]),
|
||||
...(['new_once', 'new'] as const).map(value => ({
|
||||
id: value, label: <span className={css.targetMenuItem}><span>{targetLabel(value)}</span>
|
||||
<span className={css.targetMenuDescription}>{t(value === 'new_once' ? 'host.targetNewOnceHelp' : 'host.targetNewHelp')}</span></span>,
|
||||
})),
|
||||
]}
|
||||
onChange={(value) => { change({ target: value as TaskEditorDraft['target'],
|
||||
...(draft.target === 'session' ? { cwd: projects.defaultCwd } : {}) }) }} />
|
||||
sessionId: value === 'session' ? currentSessionId : draft.sessionId,
|
||||
cwd: value === 'session' ? '' : draft.target === 'session' ? projects.defaultCwd : draft.cwd }) }} />
|
||||
{draft.target !== 'session' && <RuleSelectRow label={t('host.project')} value={draft.cwd} disabled={disabled}
|
||||
current={projects.items.find(choice => choice.value === draft.cwd)?.label ?? (draft.cwd || t('host.ungrouped'))}
|
||||
listClassName={css.workspaceMenu} items={workspaceItems.length === 0 ? [{ id: '', label: t('host.ungrouped'), disabled: true }]
|
||||
@@ -149,7 +181,7 @@ export function TaskEditorFields({ draft, onChange, projects, disabled, original
|
||||
current={(frequencyItems.find(item => item.id === frequencyValue) as { label: string }).label} onChange={(value) => {
|
||||
const frequency = value === 'weekdays' ? 'weekly' : value as FrequencyPreset
|
||||
change({ frequency, ...(value === 'weekdays' ? { weekdays: [1, 2, 3, 4, 5] } : {}),
|
||||
...(frequency === 'advanced' ? { rrule: rruleFromDraft(draft, true) } : {}) })
|
||||
...(frequency === 'advanced' ? { rrule: rruleFromDraft(draft, original === undefined) } : {}) })
|
||||
}} />
|
||||
{draft.frequency !== 'once' && draft.frequency !== 'advanced' && <div className={css.ruleRow}>
|
||||
<label className={css.ruleLabel} htmlFor={rowId('interval')}>{t('host.interval')}</label>
|
||||
|
||||
@@ -111,7 +111,6 @@
|
||||
border-radius: 0 var(--dsw-radius-lg) var(--dsw-radius-lg) 0;
|
||||
border-left: 0.5px solid color-mix(in srgb, var(--dsw-alias-label-primary-foreground) 30%, transparent);
|
||||
}
|
||||
.manualDialog { width: 520px; max-width: calc(100vw - 48px); }
|
||||
.createMenu [role='menuitem'] { gap: 10px; padding: 6px 12px; }
|
||||
.targetMenu { width: 320px; max-width: calc(100vw - 48px); }
|
||||
.targetMenu [role='menuitem'] { height: 72px; box-sizing: border-box; gap: 10px; padding: 6px 12px; }
|
||||
@@ -135,9 +134,9 @@
|
||||
.taskEditor { border: 0; margin: 0; padding: 0; min-width: 0; display: grid; gap: 20px; }
|
||||
.editorField { display: grid; gap: 8px; font-size: 14px; min-width: 0; }
|
||||
.editorField > h3 { margin: 0; font: inherit; }
|
||||
.hostRuleRow { display: flex; align-items: baseline; justify-content: space-between; gap: 16px; padding: 12px 0; font-size: 13px; }
|
||||
.hostRuleRow > :last-child { text-align: right; overflow-wrap: anywhere; }
|
||||
.hostSessionFooter { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px 24px; font-size: 13px; }
|
||||
.editorField input::placeholder,
|
||||
.instruction::placeholder { color: var(--dsw-alias-label-secondary); }
|
||||
.hostSessionFooter { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px var(--detail-gutter); font-size: 13px; }
|
||||
.hostSessionFooter button { min-width: 0; max-width: 75%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; }
|
||||
.hostSessionEmpty { color: var(--dsw-alias-label-tertiary); }
|
||||
|
||||
@@ -430,6 +429,20 @@
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.conflictNotice {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Wrap the review action below its message in narrow detail panes. */
|
||||
.conflictNotice p {
|
||||
flex-basis: 20em;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.conflictNotice > button {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* The centered state every panel without content shares: empty, deleted,
|
||||
loading, and failure alike, on tertiary 14px/400 text with a caption-ink
|
||||
glyph and no bold step. The list page renders its heading as an h2, the
|
||||
@@ -621,6 +634,8 @@
|
||||
border-bottom: 0.5px solid var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
.createTitle { margin: 0; font: inherit; font-weight: 500; }
|
||||
|
||||
.detailTabs {
|
||||
display: flex;
|
||||
flex: 1 1 auto;
|
||||
@@ -702,6 +717,7 @@
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 24px var(--detail-gutter) 28px;
|
||||
padding-right: max(0px, calc(var(--detail-gutter) - var(--detail-scrollbar-space, 0px)));
|
||||
scrollbar-gutter: stable;
|
||||
--dsh-scrollbar-width: 9px;
|
||||
--dsh-scrollbar-thumb-border: 2px;
|
||||
@@ -782,14 +798,10 @@
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* The read-only rule rows sit 28px below the task instruction. */
|
||||
.ruleCard {
|
||||
margin-top: 28px;
|
||||
}
|
||||
|
||||
.ruleRows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
padding: 0 12px;
|
||||
border: 0.5px solid var(--dsw-alias-border-l3);
|
||||
border-radius: 16px;
|
||||
@@ -1132,16 +1144,6 @@
|
||||
border-color: var(--dsw-alias-state-business-primary);
|
||||
}
|
||||
|
||||
/* The stored instruction reads as plain text: no box and no edit affordance,
|
||||
on the instruction field's own 14px/24px step. */
|
||||
.readonlyPrompt {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 24px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Delivery records follow the design mock: the clock glyph owns its own column
|
||||
and every record line starts at the text column's left edge. The mock's
|
||||
`.history-row` inherits its 14px body text and 22px leading from the page
|
||||
@@ -1286,10 +1288,10 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* The edit bar closes the detail under its scrolling view while a task is in
|
||||
edit mode. */
|
||||
/* Save and discard remain below the shared editor's scrolling view. */
|
||||
.saveFooter {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
@@ -1304,21 +1306,21 @@
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.saveFooter > :last-child {
|
||||
margin-right: -8px;
|
||||
}
|
||||
|
||||
.saveNotice {
|
||||
margin-right: auto;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
font-size: 12px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* The localized reason an edit, a run, or a manual create did not take effect. */
|
||||
.saveFailure {
|
||||
flex-shrink: 0;
|
||||
margin: 0;
|
||||
padding: 12px var(--detail-gutter) 0;
|
||||
padding: 12px 0 0;
|
||||
background: var(--dsw-alias-bg-base);
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
font-size: 12px;
|
||||
@@ -1329,7 +1331,7 @@
|
||||
.detailNotice {
|
||||
flex-shrink: 0;
|
||||
margin: 0;
|
||||
padding: 0 var(--detail-gutter) 6px;
|
||||
padding: 0 0 6px;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
font-size: 12px;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
@@ -9,8 +9,8 @@ import {
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
|
||||
import type { ScheduleId, ScheduleCatalogEntry, ScheduleCreateRequest } from '@deepseek-ai/dsh-schedule/client'
|
||||
import { TaskCreateDialog, type TaskCreateOutcome } from './TaskCreateDialog.tsx'
|
||||
import { projectChoices } from './TaskEditorFields.tsx'
|
||||
import type { TaskCreateOutcome } from './TaskDetail.tsx'
|
||||
import type { TaskEditorStoreProps } from './editor-store.ts'
|
||||
import { taskNextRunAt, taskSessionId } from './task-record.ts'
|
||||
import type { CatalogSnapshot } from './catalog-source.ts'
|
||||
import { CatalogFeedback } from './CatalogFeedback.tsx'
|
||||
@@ -47,6 +47,7 @@ export interface TaskManagerInjected extends TaskDetailInjected {
|
||||
/** Root-scoped task catalog props derived from the framework and injected actions. */
|
||||
export type TaskManagerPageProps = PropsRuntime<'main'>
|
||||
& InjectFace<TaskManagerInjected>
|
||||
& TaskEditorStoreProps
|
||||
& PropsLocale<'schedule.manager'>
|
||||
|
||||
type StatusFilter = 'all' | ScheduleCatalogEntry['status']
|
||||
@@ -57,8 +58,7 @@ type StatusFilter = 'all' | ScheduleCatalogEntry['status']
|
||||
* @returns the searchable task list beside the selected task's detail.
|
||||
*/
|
||||
export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
const { useCatalog, onNewTask, onClearEnded, onRetry, onCreateTask, useWorkspaces, t } = props
|
||||
const workspaces = useWorkspaces(snapshot => snapshot)
|
||||
const { useCatalog, onNewTask, onClearEnded, onRetry, onCreateTask, t } = props
|
||||
const [createMenuOpen, setCreateMenuOpen] = useState(false)
|
||||
const [manualOpen, setManualOpen] = useState(false)
|
||||
const catalog = useCatalog(snapshot => snapshot)
|
||||
@@ -77,6 +77,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
const { record: catalogRecord, task: selected,
|
||||
props: { id: detailId, confirmId, onConfirm: setConfirmId, onTabChange: setTab } } = detail
|
||||
const rowRef = useRef<HTMLButtonElement | null>(null)
|
||||
const createTriggerRef = useRef<HTMLButtonElement>(null)
|
||||
const headingRef = useRef<HTMLHeadingElement>(null)
|
||||
const clearTriggerRef = useRef<HTMLButtonElement | null>(null)
|
||||
// Set when the confirmation opens: its settled removal can hide the trigger
|
||||
@@ -107,23 +108,22 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
: statusFilter === 'paused' ? 'list.emptyPaused'
|
||||
: statusFilter === 'ended' ? 'list.emptyInactive'
|
||||
: statusFilter === 'active' ? 'list.emptyActive' : 'list.empty'
|
||||
// The list's frequency line omits a rule zone equal to the host's and otherwise
|
||||
// names it, the same way the detail's Repeat row does.
|
||||
// The list's frequency line omits a rule zone equal to the host's and otherwise names it.
|
||||
const systemZone = Intl.DateTimeFormat().resolvedOptions().timeZone
|
||||
const frequencyZone: FrequencyZone = { system: systemZone, label: zone => zoneLabel(zone, t) }
|
||||
|
||||
useEffect(() => {
|
||||
// The detail focuses its own panel; with nothing selected, focus returns
|
||||
// to the row that opened it, or to the page heading once that row is gone.
|
||||
// to the control that opened it, or to the page heading once that control is gone.
|
||||
// An open confirmation owns the focus until it closes, even when a refresh
|
||||
// drops the selected task behind it.
|
||||
if (selectedId !== null || clearConfirm) return
|
||||
if (selectedId !== null || manualOpen || clearConfirm) return
|
||||
if (rowRef.current !== null) {
|
||||
const target = rowRef.current.isConnected ? rowRef.current : headingRef.current
|
||||
target?.focus()
|
||||
rowRef.current = null
|
||||
}
|
||||
}, [selectedId, clearConfirm])
|
||||
}, [selectedId, manualOpen, clearConfirm])
|
||||
|
||||
useEffect(() => {
|
||||
if (status !== 'ready') return
|
||||
@@ -133,6 +133,11 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
|
||||
const closeDetails = (): void => {
|
||||
setSelectedId(null)
|
||||
setManualOpen(false)
|
||||
}
|
||||
const createManually = (trigger: HTMLButtonElement | null): void => {
|
||||
rowRef.current = trigger
|
||||
setSelectedId(null); setManualOpen(true); setTab('rule')
|
||||
}
|
||||
|
||||
// The Modal restores focus to the element it captured when it opened; the
|
||||
@@ -173,7 +178,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
|
||||
return (
|
||||
<section
|
||||
className={clsx(css.page, selected !== undefined && css.hasDetails)}
|
||||
className={clsx(css.page, (selected !== undefined || manualOpen) && css.hasDetails)}
|
||||
aria-label={t('title')}
|
||||
data-testid="task-manager-page"
|
||||
onKeyDown={(event) => {
|
||||
@@ -182,20 +187,13 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
// Modal's document bubble listener, which runs after this React handler,
|
||||
// so the `clearConfirm` guard is what keeps this page from also closing
|
||||
// the detail while the dialog closes.
|
||||
if (event.key !== 'Escape' || event.defaultPrevented || confirmId !== null || clearConfirm || manualOpen
|
||||
|| selectedId === null) return
|
||||
if (event.key !== 'Escape' || event.defaultPrevented || confirmId !== null || clearConfirm
|
||||
|| selectedId === null && !manualOpen) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
closeDetails()
|
||||
}}
|
||||
>
|
||||
{manualOpen && <TaskCreateDialog
|
||||
loadNewSessionInterval={props.hostActions.loadNewSessionInterval}
|
||||
projects={projectChoices(workspaces.items, t('host.defaultProject'))}
|
||||
onCreate={onCreateTask} onClose={() => { setManualOpen(false) }}
|
||||
onCreated={(task) => {
|
||||
setManualOpen(false); setSearch(''); setStatusFilter('all'); setSelectedId(task.id); setTab('rule')
|
||||
}} t={t} />}
|
||||
<div className={css.listPane}>
|
||||
<div className={css.pageScroll}>
|
||||
<div className={css.pageContent}>
|
||||
@@ -207,14 +205,14 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
onClick={onNewTask}>{t('new.action')}</Button>
|
||||
<Menu open={createMenuOpen} onClose={() => { setCreateMenuOpen(false) }} align="end" portal autoFocus
|
||||
listClassName={css.createMenu}
|
||||
anchor={<Button variant="primary" size="sm" className={css.createMore} aria-label={t('host.createMethod')}
|
||||
anchor={<Button ref={createTriggerRef} variant="primary" size="sm" className={css.createMore} aria-label={t('host.createMethod')}
|
||||
aria-haspopup="menu" aria-expanded={createMenuOpen} onClick={() => { setCreateMenuOpen(value => !value) }}>
|
||||
<IconChevronDownOutlineRegular size={12} />
|
||||
</Button>}>
|
||||
<MenuItemButton icon={<ReferenceIconRegular kind="session" size={14} />}
|
||||
onSelect={() => { setCreateMenuOpen(false); onNewTask() }}>{t('host.chatCreate')}</MenuItemButton>
|
||||
<MenuItemButton icon={<IconEditOutlineRegular size={14} />}
|
||||
onSelect={() => { setCreateMenuOpen(false); setManualOpen(true) }}>
|
||||
onSelect={() => { setCreateMenuOpen(false); createManually(createTriggerRef.current) }}>
|
||||
{t('host.manualCreate')}
|
||||
</MenuItemButton>
|
||||
</Menu>
|
||||
@@ -286,7 +284,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
{status === 'ready' && rows.length === 0 && <div className={css.empty} role="status">
|
||||
<ScheduleEmptyIllustration className={css.emptyIllustration} />
|
||||
<h2>{t(emptyTitle)}</h2>
|
||||
<Button variant="outline" className={css.emptyAction} onClick={() => { setManualOpen(true) }}>
|
||||
<Button variant="outline" className={css.emptyAction} onClick={(event) => { createManually(event.currentTarget) }}>
|
||||
{t('empty.action')}
|
||||
</Button>
|
||||
</div>}
|
||||
@@ -307,6 +305,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
aria-controls={selectedId === record.id ? detailId : undefined}
|
||||
onClick={(event) => {
|
||||
rowRef.current = event.currentTarget
|
||||
setManualOpen(false)
|
||||
setSelectedId(record.id)
|
||||
setTab('rule')
|
||||
}}
|
||||
@@ -335,7 +334,10 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{selected !== undefined && <TaskDetail
|
||||
{manualOpen ? <TaskDetail {...detail.props} onCreateTask={onCreateTask} onClose={closeDetails} onDeleted={closeDetails}
|
||||
onCreated={(task) => {
|
||||
setManualOpen(false); setSearch(''); setStatusFilter('all'); setSelectedId(task.id); setTab('rule')
|
||||
}} /> : selected !== undefined && <TaskDetail
|
||||
{...detail.props}
|
||||
task={selected}
|
||||
authoritative={catalogRecord !== undefined}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
/** Unsaved task forms survive navigation without persisting business records. */
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-store'
|
||||
import type { PropsStore } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { TaskEditorDraft } from './TaskEditorFields.tsx'
|
||||
import type { HostEditFailure, TaskCreateOutcome } from './TaskDetail.tsx'
|
||||
|
||||
type EditorFailure = HostEditFailure | Extract<TaskCreateOutcome, { failed: string }>['failed']
|
||||
|
||||
interface EditorDraft {
|
||||
readonly draft: TaskEditorDraft
|
||||
readonly base: ScheduleCatalogEntry | undefined
|
||||
readonly initial?: TaskEditorDraft
|
||||
readonly pending?: boolean
|
||||
readonly failure?: EditorFailure
|
||||
}
|
||||
|
||||
interface EditorState {
|
||||
drafts: Record<string, EditorDraft | undefined>
|
||||
}
|
||||
|
||||
const editorActions = {
|
||||
setDraft: (state: EditorState, key: string, draft: EditorDraft) => { state.drafts[key] = draft },
|
||||
clearDraft: (state: EditorState, key: string) => {
|
||||
state.drafts = Object.fromEntries(Object.entries(state.drafts).filter(([id]) => id !== key))
|
||||
},
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare drafts retained by the framework for one entry's scope.
|
||||
* @returns the entry's store handle.
|
||||
*/
|
||||
export function createEditorStore(): EngineStoreHandle<EditorState, typeof editorActions> {
|
||||
return defineStore({
|
||||
init: (): EditorState => ({ drafts: {} }),
|
||||
actions: editorActions,
|
||||
})
|
||||
}
|
||||
|
||||
/** Framework-bound selectors and actions; components never receive the store itself. */
|
||||
export type TaskEditorStoreProps = PropsStore<ReturnType<typeof createEditorStore>>
|
||||
@@ -1,5 +1,6 @@
|
||||
/** Lossless guided and Custom editor projections for typed Schedule timing. */
|
||||
import type { ScheduleCatalogEntry, ScheduleTiming } from '@deepseek-ai/dsh-schedule/client'
|
||||
import { Cron, RRule } from '@deepseek-ai/dsh-util-time'
|
||||
import { hostFrequencyKind, ruleFields } from './task-record.ts'
|
||||
|
||||
/** Periods represented by guided controls, plus a lossless advanced editor. */
|
||||
@@ -144,8 +145,14 @@ export function timingFromDraft(draft: TimingDraft, intervalFromNow = false): Sc
|
||||
if (draft.frequency === 'advanced') {
|
||||
if (draft.rrule.trim() === '' && draft.retainedTiming !== undefined) return draft.retainedTiming
|
||||
if (!draft.rrule.trimStart().startsWith('DTSTART')) {
|
||||
return { kind: 'cron', cron: { expression: draft.rrule.trim(), time_zone: draft.timeZone } }
|
||||
const expression = draft.rrule.trim()
|
||||
const parsed = Cron.parse(expression, draft.timeZone)
|
||||
return { kind: 'cron', cron: {
|
||||
expression: parsed.kind === 'accepted' ? parsed.rule.expression : expression, time_zone: draft.timeZone,
|
||||
} }
|
||||
}
|
||||
}
|
||||
return { kind: 'rrule', rrule: rruleFromDraft(draft, intervalFromNow) }
|
||||
const rrule = rruleFromDraft(draft, intervalFromNow)
|
||||
const parsed = draft.frequency === 'advanced' ? RRule.parse(rrule) : undefined
|
||||
return { kind: 'rrule', rrule: parsed?.kind === 'accepted' ? parsed.rule.expression : rrule }
|
||||
}
|
||||
@@ -55,6 +55,7 @@ import { ScheduleTaskTabTitle } from './ScheduleTaskTabTitle.tsx'
|
||||
import { SessionScheduleHover } from './SessionScheduleHover.tsx'
|
||||
import { SessionScheduleMark } from './SessionScheduleMark.tsx'
|
||||
import { TaskTabBindings } from './task-tab-bindings.ts'
|
||||
import { createEditorStore } from './editor-store.ts'
|
||||
import { TaskManagerPage, type TaskManagerInjected } from './TaskManagerPage.tsx'
|
||||
import type { TaskDetailInjected } from './TaskDetail.tsx'
|
||||
import { TaskManagerIcon } from './TaskManagerIcon.tsx'
|
||||
@@ -205,6 +206,7 @@ export function apply(ctx: ClientContext): void {
|
||||
name: 'sidebar.right.pane.tab',
|
||||
key: SCHEDULE_TASK_ID,
|
||||
locale: MANAGER_NS,
|
||||
store: createEditorStore(),
|
||||
inject: (): ScheduleTaskTabInjected => ({ ...detail, taskBindings }),
|
||||
}, ScheduleTaskTab))
|
||||
yield ctx.slots.inject('sidebar.right.pane.tab.title', () => ctx.slots.register({
|
||||
@@ -217,6 +219,7 @@ export function apply(ctx: ClientContext): void {
|
||||
name: 'main',
|
||||
key: PANEL_ID,
|
||||
locale: MANAGER_NS,
|
||||
store: createEditorStore(),
|
||||
inject: (): TaskManagerInjected => ({
|
||||
...detail,
|
||||
onNewTask: () => { ctx.uiWorkspace.startSession() },
|
||||
|
||||
@@ -7,7 +7,7 @@ export const en = {
|
||||
'host.createMethod': 'Choose a creation method',
|
||||
'host.chatCreate': 'Create in a session',
|
||||
'host.manualCreate': 'Create manually',
|
||||
'host.closeCreate': 'Close task creation',
|
||||
'host.closeCreate': 'Close creation form',
|
||||
'host.creating': 'Creating…',
|
||||
'host.createError': 'Could not create the task. Your input is preserved; try again.',
|
||||
'host.notFuture': 'Choose a future schedule; edit the task timing before resuming',
|
||||
@@ -28,14 +28,13 @@ export const en = {
|
||||
'host.newSessionInterval': 'Minimum run interval: {interval}',
|
||||
'host.limitsLoading': 'Loading the run interval limit',
|
||||
'host.limitsError': 'Could not load the run interval limit. Try again before saving.',
|
||||
'host.edit': 'Edit',
|
||||
'host.pause': 'Pause',
|
||||
'host.resume': 'Resume',
|
||||
'host.run': 'Run now',
|
||||
'host.runAfterInterval': 'The minimum run interval has not passed. Run now is available at {time}.',
|
||||
'host.saveError': 'Could not save. Your changes are preserved; try again.',
|
||||
'host.conflict': 'This task changed elsewhere. Load the latest version before saving.',
|
||||
'host.reload': 'Load latest version',
|
||||
'host.conflict': 'This task changed elsewhere. Review the latest values with your edits, or discard your changes.',
|
||||
'host.reapply': 'Review with my edits',
|
||||
'host.runError': 'Could not queue the task. Try again.',
|
||||
'host.executionPending': 'This task is queued, running, or was just delivered. Try again later.',
|
||||
'host.executionActive': 'This task is queued or running. Manage it in the session.',
|
||||
@@ -88,7 +87,9 @@ export const en = {
|
||||
'delivery.retentionBounds': 'Each task keeps up to {records} delivery records from the last {days} days.',
|
||||
'delivery.retentionExplanation': 'When a new record is saved, older records outside these limits are cleared automatically. Clearing records does not stop the task.',
|
||||
'detail.name': 'Automation task name',
|
||||
'detail.namePlaceholder': 'E.g. Daily reading digest',
|
||||
'detail.instruction': 'Automation task instruction',
|
||||
'detail.instructionPlaceholder': 'Describe the task and result.\nE.g. Summarize my reading list with source links.',
|
||||
'detail.session': 'Linked session',
|
||||
'detail.openSession': 'Linked session: open linked session',
|
||||
'detail.openSessionTitle': 'Linked session {title}: open linked session',
|
||||
@@ -119,7 +120,8 @@ export const en = {
|
||||
'rule.unsaved': 'Unsaved changes',
|
||||
'rule.save': 'Save changes',
|
||||
'rule.saving': 'Saving…',
|
||||
'rule.cancel': 'Cancel',
|
||||
'rule.invalid': 'Check the required fields and schedule',
|
||||
'rule.cancel': 'Discard',
|
||||
'rule.once': 'Once',
|
||||
'rule.everyMinutes': 'Every N minutes',
|
||||
'rule.everyHours': 'Every N hours',
|
||||
@@ -163,8 +165,8 @@ export const zh: Record<TaskManagerKey, string> = {
|
||||
'host.createMethod': '选择创建方式',
|
||||
'host.chatCreate': '在会话中创建',
|
||||
'host.manualCreate': '手动创建',
|
||||
'host.closeCreate': '关闭任务创建',
|
||||
'host.creating': '正在创建…',
|
||||
'host.closeCreate': '关闭创建页',
|
||||
'host.creating': '创建中…',
|
||||
'host.createError': '无法创建任务,已保留填写内容,请重试',
|
||||
'host.notFuture': '请选择未来的运行时间;恢复前请先修改任务时间',
|
||||
'host.invalidRule': '请检查规则内容和时区',
|
||||
@@ -184,14 +186,13 @@ export const zh: Record<TaskManagerKey, string> = {
|
||||
'host.newSessionInterval': '运行间隔至少 {interval}',
|
||||
'host.limitsLoading': '正在读取运行间隔限制',
|
||||
'host.limitsError': '无法读取运行间隔限制,请在保存前重试',
|
||||
'host.edit': '编辑',
|
||||
'host.pause': '暂停任务',
|
||||
'host.resume': '恢复任务',
|
||||
'host.run': '立即执行',
|
||||
'host.runAfterInterval': '未满最小运行间隔,{time} 后可立即执行',
|
||||
'host.saveError': '无法保存,已保留修改,请重试',
|
||||
'host.conflict': '此任务已在其他位置更新,请载入最新版本后再保存',
|
||||
'host.reload': '载入最新版本',
|
||||
'host.conflict': '任务已在其他位置更新。可保留修改并复核最新值,或放弃更改。',
|
||||
'host.reapply': '保留修改并复核',
|
||||
'host.runError': '无法将任务加入队列,请重试',
|
||||
'host.executionPending': '此任务已排队、执行中或刚执行过,请稍后再试',
|
||||
'host.executionActive': '此任务已排队或执行中,请在会话中管理任务',
|
||||
@@ -244,7 +245,9 @@ export const zh: Record<TaskManagerKey, string> = {
|
||||
'delivery.retentionBounds': '每个任务最多保留近 {days} 天内的 {records} 条运行记录。',
|
||||
'delivery.retentionExplanation': '产生新记录时,超出范围的旧记录会自动清理。清理记录不影响任务继续运行。',
|
||||
'detail.name': '自动化任务名称',
|
||||
'detail.namePlaceholder': '例如:每日阅读摘要',
|
||||
'detail.instruction': '自动化任务内容',
|
||||
'detail.instructionPlaceholder': '说明任务内容和预期结果\n例如:汇总阅读清单中的新文章,并附原文链接',
|
||||
'detail.session': '关联会话',
|
||||
'detail.openSession': '关联会话:打开关联会话',
|
||||
'detail.openSessionTitle': '关联会话 {title}:打开关联会话',
|
||||
@@ -275,7 +278,8 @@ export const zh: Record<TaskManagerKey, string> = {
|
||||
'rule.unsaved': '有未保存的修改',
|
||||
'rule.save': '保存修改',
|
||||
'rule.saving': '保存中…',
|
||||
'rule.cancel': '取消',
|
||||
'rule.invalid': '请检查必填项和运行规则',
|
||||
'rule.cancel': '放弃',
|
||||
'rule.once': '仅一次',
|
||||
'rule.everyMinutes': '每 N 分钟',
|
||||
'rule.everyHours': '每 N 小时',
|
||||
@@ -315,7 +319,7 @@ export const ja = {
|
||||
'host.createMethod': '作成方法を選択',
|
||||
'host.chatCreate': '会話で作成',
|
||||
'host.manualCreate': '手動で作成',
|
||||
'host.closeCreate': 'タスクの作成を閉じる',
|
||||
'host.closeCreate': '作成フォームを閉じる',
|
||||
'host.creating': '作成中…',
|
||||
'host.createError': 'タスクを作成できませんでした。入力は保持されています。もう一度お試しください。',
|
||||
'host.notFuture': '将来の実行時刻を指定してください。再開前にタスクの実行時刻を変更してください。',
|
||||
@@ -336,14 +340,13 @@ export const ja = {
|
||||
'host.newSessionInterval': '最小実行間隔: {interval}',
|
||||
'host.limitsLoading': '実行間隔の上限を読み込み中',
|
||||
'host.limitsError': '実行間隔の上限を読み込めませんでした。保存前にもう一度お試しください。',
|
||||
'host.edit': '編集',
|
||||
'host.pause': '一時停止',
|
||||
'host.resume': '再開',
|
||||
'host.run': '今すぐ実行',
|
||||
'host.runAfterInterval': '最小実行間隔がまだ経過していません。{time}から今すぐ実行できます。',
|
||||
'host.saveError': '保存できませんでした。変更は保持されています。もう一度お試しください。',
|
||||
'host.conflict': 'このタスクは別の場所で変更されました。保存前に最新のバージョンを読み込んでください。',
|
||||
'host.reload': '最新のバージョンを読み込む',
|
||||
'host.conflict': 'このタスクは別の場所で変更されました。編集内容を保持して最新の値を確認するか、変更を破棄してください。',
|
||||
'host.reapply': '編集内容を保持して確認',
|
||||
'host.runError': 'タスクをキューに追加できませんでした。もう一度お試しください。',
|
||||
'host.executionPending': 'このタスクはキューに入っているか、実行中か、直前に配信されました。しばらくしてからお試しください。',
|
||||
'host.executionActive': 'このタスクはキューに入っているか実行中です。会話内で管理してください。',
|
||||
@@ -395,7 +398,9 @@ export const ja = {
|
||||
'delivery.retentionBounds': '各タスクは過去 {days} 日間の配信記録を最大 {records} 件保持します。',
|
||||
'delivery.retentionExplanation': '新しい記録を保存すると、これらの上限を超えた古い記録は自動的に削除されます。記録を削除してもタスクは停止しません。',
|
||||
'detail.name': '自動化タスク名',
|
||||
'detail.namePlaceholder': '例:毎日の読書ダイジェスト',
|
||||
'detail.instruction': '自動化タスクの指示',
|
||||
'detail.instructionPlaceholder': '実行する内容と期待する結果を入力してください\n例:読書リストの記事を要約し、元記事のリンクを付ける',
|
||||
'detail.session': 'リンクされたセッション',
|
||||
'detail.openSession': 'リンクされたセッション: リンクされたセッションを開く',
|
||||
'detail.openSessionTitle': 'リンクされたセッション {title}: リンクされたセッションを開く',
|
||||
@@ -425,7 +430,8 @@ export const ja = {
|
||||
'rule.unsaved': '未保存の変更',
|
||||
'rule.save': '変更を保存',
|
||||
'rule.saving': '保存中…',
|
||||
'rule.cancel': 'キャンセル',
|
||||
'rule.invalid': '必須項目と実行ルールを確認してください',
|
||||
'rule.cancel': '破棄',
|
||||
'rule.once': '1回のみ',
|
||||
'rule.everyMinutes': 'N分ごと',
|
||||
'rule.everyHours': 'N時間ごと',
|
||||
@@ -500,7 +506,9 @@ export const es = {
|
||||
'delivery.retentionBounds': 'Cada tarea mantiene registros de entrega hasta {records} de los últimos días {days}.',
|
||||
'delivery.retentionExplanation': 'Cuando se guarda un nuevo registro, los registros más antiguos que estén fuera de estos límites se borran automáticamente. Borrar registros no detiene la tarea.',
|
||||
'detail.name': 'Nombre de la tarea de automatización',
|
||||
'detail.namePlaceholder': 'Ej.: resumen diario de lectura',
|
||||
'detail.instruction': 'Instrucción de tarea de automatización',
|
||||
'detail.instructionPlaceholder': 'Describe la tarea y el resultado.\nEj.: resume mi lista de lectura con enlaces a los originales.',
|
||||
'detail.session': 'Sesión vinculada',
|
||||
'detail.openSession': 'Sesión vinculada: abrir sesión vinculada',
|
||||
'detail.openSessionTitle': 'Sesión vinculada {title}: abrir sesión vinculada',
|
||||
@@ -531,7 +539,8 @@ export const es = {
|
||||
'rule.unsaved': 'Cambios no guardados',
|
||||
'rule.save': 'Guardar cambios',
|
||||
'rule.saving': 'Guardando…',
|
||||
'rule.cancel': 'Cancelar',
|
||||
'rule.invalid': 'Comprueba los campos obligatorios y la programación',
|
||||
'rule.cancel': 'Descartar',
|
||||
'rule.once': 'una vez',
|
||||
'rule.everyMinutes': 'Cada N minutos',
|
||||
'rule.everyHours': 'Cada N horas',
|
||||
@@ -564,16 +573,14 @@ export const es = {
|
||||
'card.openLabel': 'Abrir detalles de la tarea: {title}',
|
||||
'card.deleted': 'Eliminado',
|
||||
'host.chatCreate': 'Crear en una conversación',
|
||||
'host.closeCreate': 'Cerrar creación de tarea',
|
||||
'host.conflict': 'Esta tarea cambió en otro lugar. Carga la última versión antes de guardar.',
|
||||
'host.conflict': 'Esta tarea cambió en otro lugar. Revisa los valores actuales con tus cambios o descártalos.',
|
||||
'host.reapply': 'Revisar con mis cambios',
|
||||
'host.create': 'Crear',
|
||||
'host.createError': 'No se pudo crear la tarea. Tus datos se conservan; inténtalo de nuevo.',
|
||||
'host.createMethod': 'Elegir método de creación',
|
||||
'host.creating': 'Creando…',
|
||||
'host.currentConversation': 'Conversación vinculada actual',
|
||||
'host.customRule': 'Personalizar',
|
||||
'host.defaultProject': 'Espacio de trabajo predeterminado',
|
||||
'host.edit': 'Editar',
|
||||
'host.executionActive': 'Esta tarea está en cola o en ejecución. Adminístrala en la conversación.',
|
||||
'host.executionPending': 'Esta tarea está en cola, en ejecución o acaba de entregarse. Inténtalo más tarde.',
|
||||
'host.frequency.advanced': 'Personalizado',
|
||||
@@ -584,13 +591,14 @@ export const es = {
|
||||
'host.limitsError': 'No se pudo cargar el intervalo mínimo. Inténtalo de nuevo antes de guardar.',
|
||||
'host.limitsLoading': 'Cargando intervalo mínimo',
|
||||
'host.manualCreate': 'Crear manualmente',
|
||||
'host.closeCreate': 'Cerrar formulario de creación',
|
||||
'host.creating': 'Creando…',
|
||||
'host.monthDay': 'Día del mes',
|
||||
'host.newSessionInterval': 'Intervalo mínimo entre ejecuciones: {interval}',
|
||||
'host.notFuture': 'Elige una programación futura; edita el horario de la tarea antes de reanudarla.',
|
||||
'host.openDeliverySession': 'Abrir conversación',
|
||||
'host.pause': 'Pausar',
|
||||
'host.project': 'Espacio de trabajo vinculado',
|
||||
'host.reload': 'Cargar última versión',
|
||||
'host.resume': 'Reanudar',
|
||||
'host.run': 'Ejecutar ahora',
|
||||
'host.runAfterInterval': 'Aún no ha pasado el intervalo mínimo. Podrás ejecutar la tarea a las {time}.',
|
||||
@@ -651,7 +659,9 @@ export const fr = {
|
||||
'delivery.retentionBounds': "Chaque tâche conserve jusqu'à {records} enregistrements de livraison des derniers jours {days}.",
|
||||
'delivery.retentionExplanation': "Lorsqu'un nouvel enregistrement est enregistré, les enregistrements plus anciens en dehors de ces limites sont automatiquement effacés. La suppression des enregistrements n'arrête pas la tâche.",
|
||||
'detail.name': "Nom de la tâche d'automatisation",
|
||||
'detail.namePlaceholder': 'Ex. : résumé de lecture quotidien',
|
||||
'detail.instruction': "Instruction de tâche d'automatisation",
|
||||
'detail.instructionPlaceholder': 'Décrivez la tâche et le résultat.\nEx. : résumez les articles de ma liste avec leurs liens.',
|
||||
'detail.session': 'Session liée',
|
||||
'detail.openSession': 'Session liée : ouvrir la session liée',
|
||||
'detail.openSessionTitle': 'Session liée {title} : ouvrir la session liée',
|
||||
@@ -682,7 +692,8 @@ export const fr = {
|
||||
'rule.unsaved': 'Modifications non enregistrées',
|
||||
'rule.save': 'Enregistrer les modifications',
|
||||
'rule.saving': 'Sauvegarde…',
|
||||
'rule.cancel': 'Annuler',
|
||||
'rule.invalid': 'Vérifiez les champs obligatoires et la planification',
|
||||
'rule.cancel': 'Abandonner',
|
||||
'rule.once': 'Une fois',
|
||||
'rule.everyMinutes': 'Toutes les N minutes',
|
||||
'rule.everyHours': 'Toutes les N heures',
|
||||
@@ -715,16 +726,14 @@ export const fr = {
|
||||
'card.openLabel': 'Détails de la tâche ouverte : {title}',
|
||||
'card.deleted': 'Supprimé',
|
||||
'host.chatCreate': 'Créer dans une conversation',
|
||||
'host.closeCreate': 'Fermer la création de tâche',
|
||||
'host.conflict': 'Cette tâche a été modifiée ailleurs. Chargez la dernière version avant d’enregistrer.',
|
||||
'host.conflict': 'Cette tâche a été modifiée ailleurs. Vérifiez les valeurs actuelles avec vos modifications, ou abandonnez-les.',
|
||||
'host.reapply': 'Vérifier avec mes modifications',
|
||||
'host.create': 'Créer',
|
||||
'host.createError': 'Impossible de créer la tâche. Votre saisie est conservée ; réessayez.',
|
||||
'host.createMethod': 'Choisir le mode de création',
|
||||
'host.creating': 'Création…',
|
||||
'host.currentConversation': 'Conversation liée actuelle',
|
||||
'host.customRule': 'Personnaliser',
|
||||
'host.defaultProject': 'Espace de travail par défaut',
|
||||
'host.edit': 'Modifier',
|
||||
'host.executionActive': 'Cette tâche est en attente ou en cours. Gérez-la dans la conversation.',
|
||||
'host.executionPending': 'Cette tâche est en attente, en cours ou vient d’être transmise. Réessayez plus tard.',
|
||||
'host.frequency.advanced': 'Personnalisé',
|
||||
@@ -735,13 +744,14 @@ export const fr = {
|
||||
'host.limitsError': 'Impossible de charger l’intervalle minimal. Réessayez avant d’enregistrer.',
|
||||
'host.limitsLoading': 'Chargement de l’intervalle minimal',
|
||||
'host.manualCreate': 'Créer manuellement',
|
||||
'host.closeCreate': 'Fermer le formulaire de création',
|
||||
'host.creating': 'Création…',
|
||||
'host.monthDay': 'Jour du mois',
|
||||
'host.newSessionInterval': 'Intervalle minimal entre les exécutions : {interval}',
|
||||
'host.notFuture': 'Choisissez un horaire futur ; modifiez celui de la tâche avant de la reprendre.',
|
||||
'host.openDeliverySession': 'Ouvrir la conversation',
|
||||
'host.pause': 'Suspendre',
|
||||
'host.project': 'Espace de travail lié',
|
||||
'host.reload': 'Charger la dernière version',
|
||||
'host.resume': 'Reprendre',
|
||||
'host.run': 'Exécuter maintenant',
|
||||
'host.runAfterInterval': 'L’intervalle minimal n’est pas encore écoulé. L’exécution sera disponible à {time}.',
|
||||
@@ -802,7 +812,9 @@ export const de = {
|
||||
'delivery.retentionBounds': 'Jede Aufgabe verwaltet bis zu {records}-Lieferaufzeichnungen der letzten {days}-Tage.',
|
||||
'delivery.retentionExplanation': 'Wenn ein neuer Datensatz gespeichert wird, werden ältere Datensätze außerhalb dieser Grenzen automatisch gelöscht. Durch das Löschen von Datensätzen wird die Aufgabe nicht gestoppt.',
|
||||
'detail.name': 'Name der Automatisierungsaufgabe',
|
||||
'detail.namePlaceholder': 'Z. B. tägliche Leseübersicht',
|
||||
'detail.instruction': 'Anleitung zur Automatisierungsaufgabe',
|
||||
'detail.instructionPlaceholder': 'Beschreibe Aufgabe und Ergebnis.\nZ. B. fasse meine Leseliste mit Quellenlinks zusammen.',
|
||||
'detail.session': 'Verknüpfte Sitzung',
|
||||
'detail.openSession': 'Verknüpfte Sitzung: verknüpfte Sitzung öffnen',
|
||||
'detail.openSessionTitle': 'Verknüpfte Sitzung {title}: verknüpfte Sitzung öffnen',
|
||||
@@ -833,7 +845,8 @@ export const de = {
|
||||
'rule.unsaved': 'Nicht gespeicherte Änderungen',
|
||||
'rule.save': 'Änderungen speichern',
|
||||
'rule.saving': 'Speichern…',
|
||||
'rule.cancel': 'Abbrechen',
|
||||
'rule.invalid': 'Pflichtfelder und Zeitplan prüfen',
|
||||
'rule.cancel': 'Verwerfen',
|
||||
'rule.once': 'Einmal',
|
||||
'rule.everyMinutes': 'Alle N Minuten',
|
||||
'rule.everyHours': 'Alle N Stunden',
|
||||
@@ -866,16 +879,14 @@ export const de = {
|
||||
'card.openLabel': 'Aufgabendetails öffnen: {title}',
|
||||
'card.deleted': 'Gelöscht',
|
||||
'host.chatCreate': 'In einer Unterhaltung erstellen',
|
||||
'host.closeCreate': 'Aufgabenerstellung schließen',
|
||||
'host.conflict': 'Diese Aufgabe wurde andernorts geändert. Lade vor dem Speichern die neueste Version.',
|
||||
'host.conflict': 'Diese Aufgabe wurde andernorts geändert. Prüfe die aktuellen Werte mit deinen Änderungen oder verwirf sie.',
|
||||
'host.reapply': 'Mit meinen Änderungen prüfen',
|
||||
'host.create': 'Erstellen',
|
||||
'host.createError': 'Die Aufgabe konnte nicht erstellt werden. Deine Eingaben bleiben erhalten; versuche es erneut.',
|
||||
'host.createMethod': 'Erstellungsmethode wählen',
|
||||
'host.creating': 'Wird erstellt…',
|
||||
'host.currentConversation': 'Aktuell verknüpfte Unterhaltung',
|
||||
'host.customRule': 'Anpassen',
|
||||
'host.defaultProject': 'Standardarbeitsbereich',
|
||||
'host.edit': 'Bearbeiten',
|
||||
'host.executionActive': 'Diese Aufgabe wartet oder läuft gerade. Verwalte sie in der Unterhaltung.',
|
||||
'host.executionPending': 'Diese Aufgabe wartet, läuft oder wurde gerade zugestellt. Versuche es später erneut.',
|
||||
'host.frequency.advanced': 'Benutzerdefiniert',
|
||||
@@ -886,13 +897,14 @@ export const de = {
|
||||
'host.limitsError': 'Das Mindestintervall konnte nicht geladen werden. Versuche es vor dem Speichern erneut.',
|
||||
'host.limitsLoading': 'Mindestintervall wird geladen',
|
||||
'host.manualCreate': 'Manuell erstellen',
|
||||
'host.closeCreate': 'Erstellungsformular schließen',
|
||||
'host.creating': 'Erstellen…',
|
||||
'host.monthDay': 'Tag des Monats',
|
||||
'host.newSessionInterval': 'Mindestintervall zwischen Ausführungen: {interval}',
|
||||
'host.notFuture': 'Wählen Sie einen zukünftigen Ausführungszeitpunkt; ändern Sie den Zeitplan vor dem Fortsetzen.',
|
||||
'host.openDeliverySession': 'Unterhaltung öffnen',
|
||||
'host.pause': 'Pausieren',
|
||||
'host.project': 'Verknüpfter Arbeitsbereich',
|
||||
'host.reload': 'Neueste Version laden',
|
||||
'host.resume': 'Fortsetzen',
|
||||
'host.run': 'Jetzt ausführen',
|
||||
'host.runAfterInterval': 'Das Mindestintervall ist noch nicht verstrichen. Die Ausführung ist ab {time} möglich.',
|
||||
@@ -953,7 +965,9 @@ export const ru = {
|
||||
'delivery.retentionBounds': 'Каждая задача сохраняет записи о доставке до {records} за последние дни {days}.',
|
||||
'delivery.retentionExplanation': 'При сохранении новой записи более старые записи, выходящие за эти пределы, автоматически удаляются. Очистка записей не останавливает выполнение задачи.',
|
||||
'detail.name': 'Название задачи автоматизации',
|
||||
'detail.namePlaceholder': 'Например: ежедневная подборка статей',
|
||||
'detail.instruction': 'Инструкция по задаче автоматизации',
|
||||
'detail.instructionPlaceholder': 'Опишите задачу и результат.\nНапример: составьте обзор статей со ссылками на источники.',
|
||||
'detail.session': 'Связанный сеанс',
|
||||
'detail.openSession': 'Связанный сеанс: открыть связанный сеанс.',
|
||||
'detail.openSessionTitle': 'Связанный сеанс {title}: открыть связанный сеанс.',
|
||||
@@ -984,7 +998,8 @@ export const ru = {
|
||||
'rule.unsaved': 'Несохраненные изменения',
|
||||
'rule.save': 'Сохранить изменения',
|
||||
'rule.saving': 'Сохранение…',
|
||||
'rule.cancel': 'Отмена',
|
||||
'rule.invalid': 'Проверьте обязательные поля и расписание',
|
||||
'rule.cancel': 'Отменить',
|
||||
'rule.once': 'Однажды',
|
||||
'rule.everyMinutes': 'Каждые N минут',
|
||||
'rule.everyHours': 'Каждые N часов',
|
||||
@@ -1017,16 +1032,14 @@ export const ru = {
|
||||
'card.openLabel': 'Открыть сведения о задаче: {title}.',
|
||||
'card.deleted': 'Удалено',
|
||||
'host.chatCreate': 'Создать в беседе',
|
||||
'host.closeCreate': 'Закрыть создание задачи',
|
||||
'host.conflict': 'Задача изменена в другом месте. Загрузите последнюю версию перед сохранением.',
|
||||
'host.conflict': 'Задача изменена в другом месте. Проверьте актуальные значения со своими правками или отмените изменения.',
|
||||
'host.reapply': 'Проверить со своими правками',
|
||||
'host.create': 'Создать',
|
||||
'host.createError': 'Не удалось создать задачу. Введённые данные сохранены; попробуйте ещё раз.',
|
||||
'host.createMethod': 'Выбрать способ создания',
|
||||
'host.creating': 'Создание…',
|
||||
'host.currentConversation': 'Текущая связанная беседа',
|
||||
'host.customRule': 'Настроить',
|
||||
'host.defaultProject': 'Рабочее пространство по умолчанию',
|
||||
'host.edit': 'Изменить',
|
||||
'host.executionActive': 'Задача в очереди или выполняется. Управляйте ею в беседе.',
|
||||
'host.executionPending': 'Задача в очереди, выполняется или только что доставлена. Попробуйте позже.',
|
||||
'host.frequency.advanced': 'Произвольно',
|
||||
@@ -1037,13 +1050,14 @@ export const ru = {
|
||||
'host.limitsError': 'Не удалось загрузить минимальный интервал. Попробуйте ещё раз перед сохранением.',
|
||||
'host.limitsLoading': 'Загрузка минимального интервала',
|
||||
'host.manualCreate': 'Создать вручную',
|
||||
'host.closeCreate': 'Закрыть форму создания',
|
||||
'host.creating': 'Создание…',
|
||||
'host.monthDay': 'День месяца',
|
||||
'host.newSessionInterval': 'Минимальный интервал запусков: {interval}',
|
||||
'host.notFuture': 'Выберите расписание с будущим запуском; перед возобновлением измените время выполнения задачи.',
|
||||
'host.openDeliverySession': 'Открыть беседу',
|
||||
'host.pause': 'Приостановить',
|
||||
'host.project': 'Связанное рабочее пространство',
|
||||
'host.reload': 'Загрузить последнюю версию',
|
||||
'host.resume': 'Возобновить',
|
||||
'host.run': 'Запустить сейчас',
|
||||
'host.runAfterInterval': 'Минимальный интервал ещё не прошёл. Запуск будет доступен в {time}.',
|
||||
@@ -1104,7 +1118,9 @@ export const pt = {
|
||||
'delivery.retentionBounds': 'Cada tarefa mantém até {records} registros de entrega dos últimos {days} dias.',
|
||||
'delivery.retentionExplanation': 'Quando um novo registro é salvo, os registros mais antigos fora desses limites são apagados automaticamente. A limpeza de registros não interrompe a tarefa.',
|
||||
'detail.name': 'Nome da tarefa de automação',
|
||||
'detail.namePlaceholder': 'Ex.: resumo diário de leitura',
|
||||
'detail.instruction': 'Instrução de tarefa de automação',
|
||||
'detail.instructionPlaceholder': 'Descreva a tarefa e o resultado.\nEx.: resuma minha lista de leitura com links para as fontes.',
|
||||
'detail.session': 'Sessão vinculada',
|
||||
'detail.openSession': 'Sessão vinculada: abrir sessão vinculada',
|
||||
'detail.openSessionTitle': 'Sessão vinculada {title}: abrir sessão vinculada',
|
||||
@@ -1135,7 +1151,8 @@ export const pt = {
|
||||
'rule.unsaved': 'Alterações não salvas',
|
||||
'rule.save': 'Salvar alterações',
|
||||
'rule.saving': 'Salvando…',
|
||||
'rule.cancel': 'Cancelar',
|
||||
'rule.invalid': 'Verifique os campos obrigatórios e o agendamento',
|
||||
'rule.cancel': 'Descartar',
|
||||
'rule.once': 'Uma vez',
|
||||
'rule.everyMinutes': 'A cada N minutos',
|
||||
'rule.everyHours': 'A cada N horas',
|
||||
@@ -1168,16 +1185,14 @@ export const pt = {
|
||||
'card.openLabel': 'Detalhes da tarefa aberta: {title}',
|
||||
'card.deleted': 'Excluído',
|
||||
'host.chatCreate': 'Criar em uma conversa',
|
||||
'host.closeCreate': 'Fechar criação de tarefa',
|
||||
'host.conflict': 'Esta tarefa foi alterada em outro lugar. Carregue a versão mais recente antes de salvar.',
|
||||
'host.conflict': 'Esta tarefa foi alterada em outro lugar. Revise os valores atuais com suas alterações ou descarte-as.',
|
||||
'host.reapply': 'Revisar com minhas alterações',
|
||||
'host.create': 'Criar',
|
||||
'host.createError': 'Não foi possível criar a tarefa. Seus dados foram preservados; tente novamente.',
|
||||
'host.createMethod': 'Escolher método de criação',
|
||||
'host.creating': 'Criando…',
|
||||
'host.currentConversation': 'Conversa vinculada atual',
|
||||
'host.customRule': 'Personalizar',
|
||||
'host.defaultProject': 'Espaço de trabalho padrão',
|
||||
'host.edit': 'Editar',
|
||||
'host.executionActive': 'Esta tarefa está na fila ou em execução. Gerencie-a na conversa.',
|
||||
'host.executionPending': 'Esta tarefa está na fila, em execução ou acabou de ser entregue. Tente novamente mais tarde.',
|
||||
'host.frequency.advanced': 'Personalizado',
|
||||
@@ -1188,13 +1203,14 @@ export const pt = {
|
||||
'host.limitsError': 'Não foi possível carregar o intervalo mínimo. Tente novamente antes de salvar.',
|
||||
'host.limitsLoading': 'Carregando intervalo mínimo',
|
||||
'host.manualCreate': 'Criar manualmente',
|
||||
'host.closeCreate': 'Fechar formulário de criação',
|
||||
'host.creating': 'Criando…',
|
||||
'host.monthDay': 'Dia do mês',
|
||||
'host.newSessionInterval': 'Intervalo mínimo entre execuções: {interval}',
|
||||
'host.notFuture': 'Escolha um agendamento futuro; edite o horário da tarefa antes de retomá-la.',
|
||||
'host.openDeliverySession': 'Abrir conversa',
|
||||
'host.pause': 'Pausar',
|
||||
'host.project': 'Espaço de trabalho vinculado',
|
||||
'host.reload': 'Carregar versão mais recente',
|
||||
'host.resume': 'Retomar',
|
||||
'host.run': 'Executar agora',
|
||||
'host.runAfterInterval': 'O intervalo mínimo ainda não passou. A execução estará disponível às {time}.',
|
||||
|
||||
@@ -1,22 +1,24 @@
|
||||
// @vitest-environment jsdom
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { allowAllAccess, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { allowAllAccess, bindSnapshotSelector, contextMenuHook, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { ScheduleId, ScheduleCatalogEntry, ScheduleRecord } from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceId, WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import { TaskManagerPage, type TaskManagerPageProps } from '../src/client/TaskManagerPage.tsx'
|
||||
import type { HostTaskActions } from '../src/client/TaskDetail.tsx'
|
||||
import type { TaskCreateOutcome } from '../src/client/TaskCreateDialog.tsx'
|
||||
import type { TaskCreateOutcome } from '../src/client/TaskDetail.tsx'
|
||||
import { createEditorStore } from '../src/client/editor-store.ts'
|
||||
import type { CatalogSnapshot } from '../src/client/catalog-source.ts'
|
||||
import { timingFromRecord } from '../src/client/editor-timing.ts'
|
||||
import { createRRuleScheduleRecord } from '../../../schedule/schedule/src/domain.ts'
|
||||
import { ScheduleId as createScheduleId } from '../../../schedule/schedule/src/domain.ts'
|
||||
import { draftTarget, taskDraft } from '../src/client/TaskEditorFields.tsx'
|
||||
import { draftTarget, reapplyTaskDraft, taskDraft, taskDraftPatch, taskDraftValid } from '../src/client/TaskEditorFields.tsx'
|
||||
import { formatAvailableAt, formatScheduleFrequency, orderScheduleRecords, zoneLabel, zoneName } from '../src/client/schedule-format.ts'
|
||||
import { en, zh } from '../src/client/task-manager-locales.ts'
|
||||
import { en, zh, ja, es, fr, de, ru, pt } from '../src/client/task-manager-locales.ts'
|
||||
import { pinSystemZone } from './zone-fixture.ts'
|
||||
import css from '../src/client/TaskManagerPage.module.css'
|
||||
|
||||
const targetSession = 'existing-session' as SessionId
|
||||
const task: ScheduleCatalogEntry = { kind: 'rrule',
|
||||
@@ -52,10 +54,12 @@ function hostActions(overrides: Partial<HostTaskActions> = {}): HostTaskActions
|
||||
}
|
||||
|
||||
function mount(rows: readonly ScheduleCatalogEntry[] = [task], overrides: Partial<TaskManagerPageProps> = {}) {
|
||||
const editor = createEditorStore().create()
|
||||
let snapshot: CatalogSnapshot<ScheduleCatalogEntry> = {
|
||||
records: rows, status: 'ready', deleting: [], settled: true, readRequest: 1, readSettled: 1,
|
||||
}
|
||||
const props: TaskManagerPageProps = {
|
||||
useStore: bindSnapshotSelector(editor), actions: editor.actions,
|
||||
...allowAllAccess, useCatalog: select => select(snapshot), useSessions: select => select(sessions),
|
||||
useWorkspaces: select => select(workspaces), usePanelInfo: select => select({ activePanelId: null }),
|
||||
useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined,
|
||||
@@ -70,18 +74,17 @@ function mount(rows: readonly ScheduleCatalogEntry[] = [task], overrides: Partia
|
||||
t: makeTranslate(en), ...overrides,
|
||||
}
|
||||
const view = render(<TaskManagerPage {...props} />)
|
||||
return { props, view, update(records: readonly ScheduleCatalogEntry[]) {
|
||||
snapshot = { ...snapshot, records }; view.rerender(<TaskManagerPage {...props} />)
|
||||
return { props, view, editor, update(records: readonly ScheduleCatalogEntry[], status = snapshot.status, deleting = snapshot.deleting) {
|
||||
snapshot = { ...snapshot, records, status, deleting }; view.rerender(<TaskManagerPage {...props} />)
|
||||
} }
|
||||
}
|
||||
function openManual(): HTMLElement {
|
||||
fireEvent.click(screen.getByRole('button', { name: en['host.createMethod'] }))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: en['host.manualCreate'] }))
|
||||
return screen.getByRole('dialog', { name: en['host.manualCreate'] })
|
||||
return screen.getByRole('complementary')
|
||||
}
|
||||
function openEdit(): HTMLElement {
|
||||
fireEvent.click(screen.getByRole('button', { name: task.title }))
|
||||
fireEvent.click(screen.getByRole('button', { name: en['host.edit'] }))
|
||||
return screen.getByRole('complementary')
|
||||
}
|
||||
function chooseRepeat(detail: HTMLElement, label: string): void {
|
||||
@@ -116,14 +119,233 @@ beforeEach(() => {
|
||||
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers() })
|
||||
|
||||
describe('Host task editor on the existing manager', () => {
|
||||
it('closes manual creation on Escape without discarding the edited task', () => {
|
||||
it('keeps existing and new drafts when navigating through the shared editor', () => {
|
||||
mount()
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Unsaved title' } })
|
||||
const dialog = openManual()
|
||||
fireEvent.keyDown(within(dialog).getByRole('textbox', { name: en['detail.name'] }), { key: 'Escape' })
|
||||
const creation = openManual()
|
||||
fireEvent.change(within(creation).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'New draft' } })
|
||||
fireEvent.keyDown(within(creation).getByRole('textbox', { name: en['detail.name'] }), { key: 'Escape' })
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(within(openEdit()).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('Unsaved title')
|
||||
expect(within(openManual()).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('New draft')
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(within(detail).getByRole('textbox', { name: en['detail.name'] }).getAttribute('value')).toBe('Unsaved title')
|
||||
})
|
||||
|
||||
it('enables Save only for a meaningful valid change and restores actions after reverting', () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const saveButton = within(detail).getByRole('button', { name: en['rule.save'] })
|
||||
const title = within(detail).getByRole('textbox', { name: en['detail.name'] })
|
||||
const pause = within(detail).getByRole('button', { name: en['host.pause'] })
|
||||
expect(saveButton.hasAttribute('disabled')).toBe(true)
|
||||
expect(pause.hasAttribute('disabled')).toBe(false)
|
||||
fireEvent.change(title, { target: { value: ` ${task.title} ` } })
|
||||
expect(saveButton.hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.change(title, { target: { value: '' } })
|
||||
expect(saveButton.hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.change(title, { target: { value: 'Changed' } })
|
||||
expect(saveButton.hasAttribute('disabled')).toBe(false)
|
||||
expect(pause.hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.change(title, { target: { value: task.title } })
|
||||
expect(saveButton.hasAttribute('disabled')).toBe(true)
|
||||
expect(pause.hasAttribute('disabled')).toBe(false)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refreshes a pristine form and blocks stale saves until the user chooses a recovery action', async () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const refreshed = { ...task, title: 'Updated elsewhere', updatedAt: '2098-12-02T00:00:00.000Z' }
|
||||
h.update([refreshed])
|
||||
const title = within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] })
|
||||
expect(title.value).toBe(refreshed.title)
|
||||
fireEvent.change(title, { target: { value: 'My draft' } })
|
||||
const latest = { ...refreshed, prompt: 'Changed elsewhere', updatedAt: '2098-12-03T00:00:00.000Z' }
|
||||
h.update([latest])
|
||||
expect(title.value).toBe('My draft')
|
||||
expect(within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['detail.instruction'] }).value).toBe(task.prompt)
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.conflict'])
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.cancel'] }))
|
||||
expect(title.value).toBe(latest.title)
|
||||
expect(within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['detail.instruction'] }).value).toBe(latest.prompt)
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
fireEvent.change(title, { target: { value: 'Reviewed title' } })
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: latest.updatedAt, patch: { title: 'Reviewed title' } })
|
||||
})
|
||||
|
||||
it('restores the entry-owned draft after the page unmounts', () => {
|
||||
const h = mount()
|
||||
fireEvent.change(within(openEdit()).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Retained draft' } })
|
||||
h.view.unmount()
|
||||
render(<TaskManagerPage {...h.props} />)
|
||||
const detail = openEdit()
|
||||
expect(within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['detail.instruction'] }).value).toBe('Retained draft')
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.cancel'] }))
|
||||
expect(within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['detail.instruction'] }).value).toBe(task.prompt)
|
||||
expect(Object.hasOwn(h.editor.getSnapshot().drafts, `task:${task.id}`)).toBe(false)
|
||||
})
|
||||
|
||||
it.each([en, zh, ja, es, fr, de, ru, pt])('localizes empty field hints and lets an untouched form be discarded', (dictionary) => {
|
||||
const h = mount([], { t: makeTranslate(dictionary) })
|
||||
fireEvent.click(screen.getByRole('button', { name: dictionary['empty.action'] }))
|
||||
const detail = screen.getByRole('complementary', { name: dictionary['host.manualCreate'] })
|
||||
expect(within(detail).queryByRole('tabpanel')).toBeNull()
|
||||
for (const key of ['name', 'instruction'] as const) {
|
||||
const field = within(detail).getByRole<HTMLInputElement | HTMLTextAreaElement>('textbox', { name: dictionary[`detail.${key}`] })
|
||||
expect(field.placeholder).toBe(dictionary[`detail.${key}Placeholder`])
|
||||
if (key === 'instruction') expect(field.placeholder.split('\n')).toHaveLength(2)
|
||||
expect(field.required).toBe(false)
|
||||
expect(field.getAttribute('aria-required')).toBe('true')
|
||||
expect(field.validationMessage).toBe('')
|
||||
expect(field.value).toBe('')
|
||||
}
|
||||
const cancel = within(detail).getByRole('button', { name: dictionary['rule.cancel'] })
|
||||
expect(cancel.hasAttribute('disabled')).toBe(false)
|
||||
fireEvent.click(cancel)
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(h.props.onCreateTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the original blank creation baseline across a later remount', () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime('2026-10-14T08:00:00.000Z')
|
||||
mount([])
|
||||
const detail = openManual()
|
||||
const title = within(detail).getByRole('textbox', { name: en['detail.name'] })
|
||||
fireEvent.change(title, { target: { value: 'Temporary' } })
|
||||
fireEvent.change(title, { target: { value: '' } })
|
||||
fireEvent.keyDown(title, { key: 'Escape' })
|
||||
vi.setSystemTime('2026-10-14T10:00:00.000Z')
|
||||
expect(within(openManual()).queryByText(en['rule.unsaved'])).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps creation available while the catalog refreshes', () => {
|
||||
const h = mount([])
|
||||
const detail = openManual()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Draft' } })
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Review changes' } })
|
||||
h.update([], 'loading')
|
||||
expect(within(detail).getByRole('button', { name: en['host.create'] }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('clears a save failure on edit and reports a later action outcome', async () => {
|
||||
mount([task], { hostActions: hostActions({
|
||||
edit: vi.fn<HostTaskActions['edit']>(async () => ({ failed: 'host.saveError' })),
|
||||
run: vi.fn<HostTaskActions['run']>(async () => ({ failed: 'host.runError' })),
|
||||
}) })
|
||||
const detail = openEdit()
|
||||
const title = within(detail).getByRole('textbox', { name: en['detail.name'] })
|
||||
fireEvent.change(title, { target: { value: 'Changed' } })
|
||||
await save(detail)
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.saveError'])
|
||||
fireEvent.change(title, { target: { value: task.title } })
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['detail.more'] }))
|
||||
await act(async () => { fireEvent.click(screen.getByRole('menuitem', { name: en['host.run'] })) })
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.runError'])
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.cancel'] }))
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not re-anchor an existing interval when only switching to Custom', () => {
|
||||
mount([{ ...task, rrule: 'DTSTART;TZID=UTC:20261013T090000\nRRULE:FREQ=MINUTELY;INTERVAL=5' }])
|
||||
const detail = openEdit()
|
||||
chooseRepeat(detail, en['host.frequency.advanced'])
|
||||
expect(within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['host.customRule'] }).value)
|
||||
.toBe('DTSTART;TZID=UTC:20261013T090000\nRRULE:FREQ=MINUTELY;INTERVAL=5')
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('refreshes a reverted draft when the authoritative revision changes', () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const title = within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] })
|
||||
fireEvent.change(title, { target: { value: 'Temporary' } })
|
||||
fireEvent.change(title, { target: { value: task.title } })
|
||||
h.update([{ ...task, title: 'Updated elsewhere', updatedAt: '2098-12-02T00:00:00.000Z' }])
|
||||
expect(title.value).toBe('Updated elsewhere')
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('cancels a new draft without creating a task', () => {
|
||||
const h = mount()
|
||||
const editor = openManual()
|
||||
fireEvent.change(within(editor).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Discarded' } })
|
||||
fireEvent.click(within(editor).getByRole('button', { name: en['rule.cancel'] }))
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(within(openManual()).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('')
|
||||
expect(h.props.onCreateTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps historical timing and an existing Session target valid without rewriting them', () => {
|
||||
const { rrule: _rrule, ...common } = task
|
||||
const historical: ScheduleCatalogEntry = { ...common, kind: 'every', everySeconds: 60,
|
||||
target: { kind: 'session', sessionId: targetSession } }
|
||||
const draft = taskDraft(historical)
|
||||
expect(taskDraftValid(draft)).toBe(true)
|
||||
expect(draftTarget(draft, historical)).toEqual(historical.target)
|
||||
})
|
||||
|
||||
it.each(['once', 'advanced'] as const)('leaves future-occurrence validation to the Host for %s', (frequency) => {
|
||||
expect(taskDraftValid({ ...taskDraft(task), frequency, start: '2000-01-01T09:00:00', timeZone: 'UTC',
|
||||
rrule: 'DTSTART;TZID=UTC:20000101T090000\nRRULE:FREQ=DAILY;COUNT=1' })).toBe(true)
|
||||
})
|
||||
|
||||
it('does not normalize untouched legacy text when opening or editing another field', async () => {
|
||||
const historical = { ...task, title: ' Old title ', prompt: ' Old instruction\n ' }
|
||||
const h = mount([historical])
|
||||
fireEvent.click(screen.getByRole('button', { name: historical.title.trim() }))
|
||||
const detail = screen.getByRole('complementary')
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Renamed' } })
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: task.updatedAt, patch: { title: 'Renamed' } })
|
||||
})
|
||||
|
||||
it('does not write a Custom Cron change that only adds whitespace', () => {
|
||||
const h = mount([{ ...task, kind: 'cron', expression: '0 9 * * 1-5', timeZone: 'UTC' }])
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['host.customRule'] }), { target: { value: ' 0 9 * * 1-5 ' } })
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not write a Custom RRULE change that only adds line whitespace', () => {
|
||||
const rrule = 'DTSTART;TZID=UTC:20990101T090000\nRRULE:FREQ=WEEKLY;BYDAY=MO;COUNT=3'
|
||||
const h = mount([{ ...task, rrule }])
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['host.customRule'] }),
|
||||
{ target: { value: `\n ${rrule.replace('\n', ' \r\n ')} \n` } })
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['menu', 'empty'])('returns focus to the %s creation control when the editor closes', (source) => {
|
||||
mount([])
|
||||
const trigger = screen.getByRole('button', { name: source === 'menu' ? en['host.createMethod'] : en['empty.action'] })
|
||||
if (source === 'menu') openManual()
|
||||
else fireEvent.click(trigger)
|
||||
fireEvent.keyDown(screen.getByRole('complementary'), { key: 'Escape' })
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(document.activeElement).toBe(trigger)
|
||||
})
|
||||
|
||||
it('does not retain a deleted task after all local changes were reverted', () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const title = within(detail).getByRole('textbox', { name: en['detail.name'] })
|
||||
fireEvent.change(title, { target: { value: 'Temporary' } })
|
||||
fireEvent.change(title, { target: { value: task.title } })
|
||||
h.update([])
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['altKey', 'ctrlKey', 'metaKey', 'shiftKey'])('preserves modified detail navigation with %s', (modifier) => {
|
||||
@@ -171,7 +393,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
it.each([en, zh])('offers only new conversation strategies and registered workspaces, starting in the default one', (dictionary) => {
|
||||
mount([], { t: makeTranslate(dictionary), useWorkspaces: select => select(registered) })
|
||||
fireEvent.click(screen.getByRole('button', { name: dictionary['empty.action'] }))
|
||||
const modal = screen.getByRole('dialog')
|
||||
const modal = screen.getByRole('complementary')
|
||||
expect(within(modal).getByRole('button', { name: new RegExp('^' + dictionary['host.target'] + ' ') }).textContent).toContain(dictionary['host.targetNewOnce'])
|
||||
const project = within(modal).getByRole('button', { name: new RegExp('^' + dictionary['host.project'] + ' ') })
|
||||
expect(project.textContent).toContain(dictionary['host.defaultProject'])
|
||||
@@ -218,10 +440,42 @@ describe('Host task editor on the existing manager', () => {
|
||||
expect(within(detail).queryByRole('button', { name: en['detail.session'] })).toBeNull()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'New content' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
await screen.findByRole('button', { name: en['host.edit'] })
|
||||
await waitFor(() => { expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true) })
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledWith({ id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt, patch: { prompt: 'New content' } })
|
||||
})
|
||||
|
||||
it('can restore the current conversation without discarding edits to other fields', async () => {
|
||||
const current = { ...task, target: { kind: 'session' as const, sessionId: targetSession } }
|
||||
const h = mount([current], { useWorkspaces: select => select(registered) })
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Local title' } })
|
||||
for (const label of [en['host.targetNew'], en['host.currentConversation']]) {
|
||||
fireEvent.click(within(detail).getByRole('button', { name: new RegExp('^' + en['host.target'] + ' ') }))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: new RegExp('^' + label) }))
|
||||
}
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: task.updatedAt, patch: { title: 'Local title' } })
|
||||
})
|
||||
|
||||
it('restores the latest linked conversation after reapplying a local destination change', async () => {
|
||||
const current = { ...task, target: { kind: 'session' as const, sessionId: targetSession } }
|
||||
const h = mount([current])
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Local title' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: new RegExp('^' + en['host.target'] + ' ') }))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: new RegExp('^' + en['host.targetNewOnce']) }))
|
||||
const latest = { ...current, updatedAt: '2098-12-02T00:00:00.000Z',
|
||||
target: { kind: 'session' as const, sessionId: 'latest-session' as SessionId } }
|
||||
h.update([latest])
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['host.reapply'] }))
|
||||
fireEvent.click(within(detail).getByRole('button', { name: new RegExp('^' + en['host.target'] + ' ') }))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: en['host.currentConversation'] }))
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: latest.updatedAt, patch: { title: 'Local title' } })
|
||||
})
|
||||
|
||||
it('keeps a delayed name-only edit of a v1 Cron task free of a timing patch', async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime('2026-10-14T08:00:00.000Z')
|
||||
@@ -268,7 +522,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
expect(row.querySelector('time')?.dateTime).toBe(floor)
|
||||
fireEvent.click(row)
|
||||
expect(screen.getByRole('complementary').querySelector('time')?.dateTime).toBe(floor)
|
||||
expect(h.props.hostActions.loadNewSessionInterval).not.toHaveBeenCalled()
|
||||
expect(h.props.hostActions.loadNewSessionInterval).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('offers no message-level cancellation for a queued task sharing a batch receipt and points to its conversation', () => {
|
||||
@@ -359,7 +613,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
const h = mount([eachRun], { t: makeTranslate(dictionary) })
|
||||
await act(async () => { fireEvent.click(screen.getByRole('button', { name: task.title })) })
|
||||
const detail = screen.getByRole('complementary')
|
||||
expect(detail.querySelector('footer')).toBeNull()
|
||||
expect(detail.querySelector(`footer.${css.hostSessionFooter}`)).toBeNull()
|
||||
h.update([{ ...eachRun, lastDelivery: {
|
||||
scheduledAt: task.scheduledAt, deliveredAt: task.scheduledAt, targetSessionId: targetSession,
|
||||
messageId: 'delivered-run' as NonNullable<ScheduleCatalogEntry['lastDelivery']>['messageId'],
|
||||
@@ -381,7 +635,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'news' } })
|
||||
expect(screen.getByRole('status').textContent).toContain(dictionary['list.noMatches'])
|
||||
fireEvent.click(screen.getByRole('button', { name: dictionary['empty.action'] }))
|
||||
expect(screen.getByRole('dialog', { name: dictionary['host.manualCreate'] })).toBeDefined()
|
||||
expect(screen.getByRole('complementary')).toBeDefined()
|
||||
expect(h.props.onNewTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -419,11 +673,11 @@ describe('Host task editor on the existing manager', () => {
|
||||
const clock = screen.getByRole('dialog', { name: en['timing.time'] })
|
||||
fireEvent.keyDown(within(clock).getAllByRole('option')[0]!, { key: 'Escape' })
|
||||
expect(screen.queryByRole('dialog', { name: en['timing.time'] })).toBeNull()
|
||||
expect(screen.getByRole('dialog', { name: en['host.manualCreate'] })).toBe(modal)
|
||||
expect(screen.getByRole('complementary')).toBe(modal)
|
||||
expect(document.activeElement).toBe(trigger)
|
||||
})
|
||||
|
||||
it('dismisses a portaled field menu before the creation modal, even if focus stays elsewhere', () => {
|
||||
it('dismisses a portaled field menu before the creation editor, even if focus stays elsewhere', () => {
|
||||
mount([])
|
||||
const modal = openManual()
|
||||
const close = within(modal).getByRole('button', { name: en['host.closeCreate'] })
|
||||
@@ -432,7 +686,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
expect(screen.getByRole('menu')).toBeDefined()
|
||||
fireEvent.keyDown(close, { key: 'Escape' })
|
||||
expect(screen.queryByRole('menu')).toBeNull()
|
||||
expect(screen.getByRole('dialog', { name: en['host.manualCreate'] })).toBe(modal)
|
||||
expect(screen.getByRole('complementary')).toBe(modal)
|
||||
})
|
||||
|
||||
it('saves only changed content with the stored compare timestamp', async () => {
|
||||
@@ -440,7 +694,7 @@ describe('Host task editor on the existing manager', () => {
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Include links' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
await screen.findByRole('button', { name: en['host.edit'] })
|
||||
await waitFor(() => { expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true) })
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({
|
||||
id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt, patch: { prompt: 'Include links' },
|
||||
})
|
||||
@@ -451,13 +705,13 @@ describe('Host task editor on the existing manager', () => {
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Include links' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
await screen.findByRole('button', { name: en['host.edit'] })
|
||||
await waitFor(() => { expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true) })
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({
|
||||
id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt, patch: { prompt: 'Include links' },
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps conflicted content visible until the user reloads or cancels', async () => {
|
||||
it('keeps conflicted content visible until the user discards it', async () => {
|
||||
const h = mount([], { hostActions: hostActions({ edit: vi.fn<HostTaskActions['edit']>(async () => ({ failed: 'host.conflict' })) }) })
|
||||
h.update([task])
|
||||
const detail = openEdit()
|
||||
@@ -465,9 +719,124 @@ describe('Host task editor on the existing manager', () => {
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
await screen.findByText(en['host.conflict'])
|
||||
expect(within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('My draft')
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Still editing' } })
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.conflict'])
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it.each([en, zh])('reapplies local edits only on request, then saves with the reviewed revision', async (dictionary) => {
|
||||
const h = mount([task], { t: makeTranslate(dictionary) })
|
||||
const detail = openEdit()
|
||||
const name = within(detail).getByRole<HTMLInputElement>('textbox', { name: dictionary['detail.name'] })
|
||||
const prompt = within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: dictionary['detail.instruction'] })
|
||||
fireEvent.change(name, { target: { value: 'My draft' } })
|
||||
const latest = { ...task, prompt: 'Remote prompt', updatedAt: '2098-12-02T00:00:00.000Z' }
|
||||
h.update([latest])
|
||||
expect(name.value).toBe('My draft')
|
||||
expect(prompt.value).toBe(task.prompt)
|
||||
fireEvent.click(within(detail).getByRole('button', { name: dictionary['host.reapply'] }))
|
||||
expect(prompt.value).toBe(latest.prompt)
|
||||
expect(name.value).toBe('My draft')
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
expect(document.activeElement).toBe(detail)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
const newer = { ...latest, title: 'Remote title', updatedAt: '2098-12-03T00:00:00.000Z' }
|
||||
h.update([newer])
|
||||
expect(within(detail).getByRole('button', { name: dictionary['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.click(within(detail).getByRole('button', { name: dictionary['host.reapply'] }))
|
||||
await act(async () => { fireEvent.click(within(detail).getByRole('button', { name: dictionary['rule.save'] })) })
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledExactlyOnceWith({ id: task.id, action: 'update',
|
||||
expectedUpdatedAt: newer.updatedAt, patch: { title: 'My draft' } })
|
||||
})
|
||||
|
||||
it.each(['title', 'prompt', 'timing', 'target'] as const)('retains a locally changed %s group and adopts untouched remote groups', (group) => {
|
||||
const latest: ScheduleCatalogEntry = { ...task, title: 'Remote title', prompt: 'Remote prompt',
|
||||
kind: 'cron', expression: '0 10 * * *', timeZone: 'Asia/Shanghai',
|
||||
target: { kind: 'new', create: { cwd: '/remote' } } }
|
||||
const original = taskDraft(task)
|
||||
const local = { ...original,
|
||||
...(group === 'title' ? { title: 'Local title' } : {}),
|
||||
...(group === 'prompt' ? { prompt: 'Local prompt' } : {}),
|
||||
...(group === 'timing' ? { frequency: 'daily' as const, dailyTime: '11:00' } : {}),
|
||||
...(group === 'target' ? { target: 'new' as const, cwd: '/local' } : {}),
|
||||
}
|
||||
const changes = taskDraftPatch(local, task)
|
||||
expect(taskDraftPatch(reapplyTaskDraft(local, latest, changes), latest)).toEqual(changes)
|
||||
})
|
||||
|
||||
it('replaces timing groups without mixing retained historical timing into a changed rule', () => {
|
||||
const historical: ScheduleCatalogEntry = { ...task, kind: 'at', scheduledAt: '2099-01-06T09:00:00.000Z' }
|
||||
const local = { ...taskDraft(task), frequency: 'advanced' as const, rrule: '0 12 * * *', timeZone: 'UTC' }
|
||||
const changes = taskDraftPatch(local, task)
|
||||
const reapplied = reapplyTaskDraft(local, historical, changes)
|
||||
expect(reapplied.retainedTiming).toBeUndefined()
|
||||
expect(taskDraftPatch(reapplied, historical)).toEqual({ timing: { kind: 'cron', cron: { expression: '0 12 * * *', time_zone: 'UTC' } } })
|
||||
})
|
||||
|
||||
it('lets a user finish required text before reporting an invalid schedule', () => {
|
||||
mount([])
|
||||
const detail = openManual()
|
||||
const name = within(detail).getByRole('textbox', { name: en['detail.name'] })
|
||||
const prompt = within(detail).getByRole('textbox', { name: en['detail.instruction'] })
|
||||
expect(name.getAttribute('aria-required')).toBe('true')
|
||||
expect(prompt.getAttribute('aria-required')).toBe('true')
|
||||
fireEvent.change(name, { target: { value: 'My task' } })
|
||||
expect(within(detail).queryByRole('status')).toBeNull()
|
||||
expect(within(detail).getByRole('button', { name: en['host.create'] }).hasAttribute('disabled')).toBe(true)
|
||||
chooseRepeat(detail, en['host.frequency.advanced'])
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['host.customRule'] }), { target: { value: 'invalid' } })
|
||||
fireEvent.change(prompt, { target: { value: 'My instructions' } })
|
||||
expect(within(detail).getByRole('status').textContent).toBe(en['rule.invalid'])
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('holds fields during deletion and returns them after a failed deletion', () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const fields = within(detail).getByRole('textbox', { name: en['detail.name'] }).closest('fieldset')!
|
||||
h.update([task], 'ready', [task.id])
|
||||
expect(fields.disabled).toBe(true)
|
||||
expect(detail.getAttribute('aria-busy')).toBe('true')
|
||||
h.update([task], 'ready', [])
|
||||
expect(fields.disabled).toBe(false)
|
||||
expect(detail.getAttribute('aria-busy')).toBe('false')
|
||||
})
|
||||
|
||||
it.each(['run', 'pause'] as const)('does not label a pending %s as a save', async (action) => {
|
||||
const pending = Promise.withResolvers<undefined>()
|
||||
mount([task], { hostActions: hostActions({
|
||||
edit: vi.fn(async () => { await pending.promise; return 'saved' as const }),
|
||||
run: vi.fn(async () => { await pending.promise; return 'queued' as const }),
|
||||
}) })
|
||||
const detail = openEdit()
|
||||
if (action === 'run') {
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['detail.more'] }))
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: en['host.run'] }))
|
||||
} else fireEvent.click(within(detail).getByRole('button', { name: en['host.pause'] }))
|
||||
expect(within(detail).queryByRole('button', { name: en['rule.saving'] })).toBeNull()
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(detail.getAttribute('aria-busy')).toBe('true')
|
||||
await act(async () => { pending.resolve(undefined); await pending.promise })
|
||||
expect(detail.getAttribute('aria-busy')).toBe('false')
|
||||
})
|
||||
|
||||
it('explains a removed task while retaining an editable local draft and blocking writes', () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
const name = within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] })
|
||||
fireEvent.change(name, { target: { value: 'My draft' } })
|
||||
h.update([])
|
||||
expect(within(detail).getByRole('status').textContent).toBe(en['detail.missing'])
|
||||
expect(name.value).toBe('My draft')
|
||||
expect(name.closest('fieldset')!.disabled).toBe(false)
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.change(name, { target: { value: 'Recoverable draft' } })
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
h.update([task])
|
||||
expect(within(detail).queryByRole('status')).toBeNull()
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores a save acknowledgement after selection moves to another task', async () => {
|
||||
const pending = Promise.withResolvers<'saved'>()
|
||||
const other = { ...task, id: 'other-task' as ScheduleId, title: 'Other task' }
|
||||
@@ -481,6 +850,51 @@ describe('Host task editor on the existing manager', () => {
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('keeps a save pending across task navigation and releases the draft after failure', async () => {
|
||||
const pending = Promise.withResolvers<{ failed: 'host.saveError' }>()
|
||||
const other = { ...task, id: 'other-task' as ScheduleId, title: 'Other task' }
|
||||
const h = mount([task, other], { hostActions: hostActions({ edit: vi.fn<HostTaskActions['edit']>(() => pending.promise) }) })
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'My draft' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
fireEvent.click(screen.getByRole('button', { name: other.title }))
|
||||
fireEvent.click(screen.getByRole('button', { name: task.title }))
|
||||
const reopened = screen.getByRole('complementary')
|
||||
expect(within(reopened).getByRole('button', { name: en['rule.saving'] }).hasAttribute('disabled')).toBe(true)
|
||||
await act(async () => { pending.resolve({ failed: 'host.saveError' }); await pending.promise })
|
||||
expect(within(reopened).getByRole('alert').textContent).toBe(en['host.saveError'])
|
||||
expect(within(reopened).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('My draft')
|
||||
expect(within(reopened).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(false)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reports a newer revision even after an earlier save failure', async () => {
|
||||
const h = mount([task], { hostActions: hostActions({ edit: vi.fn<HostTaskActions['edit']>(async () => ({ failed: 'host.saveError' })) }) })
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'My draft' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
await screen.findByText(en['host.saveError'])
|
||||
h.update([{ ...task, prompt: 'Changed elsewhere', updatedAt: '2098-12-02T00:00:00.000Z' }])
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.conflict'])
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not report its own catalog refresh as a conflict while a save is pending', async () => {
|
||||
const pending = Promise.withResolvers<'saved'>()
|
||||
const h = mount([task], { hostActions: hostActions({ edit: vi.fn<HostTaskActions['edit']>(() => pending.promise) }) })
|
||||
const detail = openEdit()
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Saved title' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.save'] }))
|
||||
h.update([{ ...task, title: 'Saved title', updatedAt: '2098-12-02T00:00:00.000Z' }])
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
expect(within(detail).getByRole('button', { name: en['rule.saving'] }).hasAttribute('disabled')).toBe(true)
|
||||
await act(async () => { pending.resolve('saved'); await pending.promise })
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
expect(document.activeElement).toBe(detail)
|
||||
expect(within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe('Saved title')
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('allows pausing during the delivery interval but offers no queued-message cancellation', () => {
|
||||
mount([{ ...task, deliveryFloorEndsAt: '2099-01-05T10:00:00.000Z' }])
|
||||
fireEvent.click(screen.getByRole('button', { name: task.title }))
|
||||
@@ -579,8 +993,11 @@ describe('Host task editor on the existing manager', () => {
|
||||
fireEvent.change(within(modal).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Morning news' } })
|
||||
fireEvent.change(within(modal).getByRole('textbox', { name: en['detail.instruction'] }), { target: { value: 'Read news' } })
|
||||
fireEvent.click(within(modal).getByRole('button', { name: en['host.create'] }))
|
||||
expect(within(modal).getByRole('button', { name: en['host.creating'] }).hasAttribute('disabled')).toBe(true)
|
||||
fireEvent.click(within(modal).getByRole('button', { name: en['host.closeCreate'] }))
|
||||
expect(screen.getByRole('dialog', { name: en['host.manualCreate'] })).toBe(modal)
|
||||
expect(screen.getByRole('complementary')).toBe(modal)
|
||||
fireEvent.keyDown(within(modal).getByRole('textbox', { name: en['detail.name'] }), { key: 'Escape' })
|
||||
expect(screen.getByRole('complementary')).toBe(modal)
|
||||
await act(async () => { pending.resolve({ created: task }); await pending.promise })
|
||||
expect(screen.queryByRole('dialog', { name: en['host.manualCreate'] })).toBeNull()
|
||||
expect(within(screen.getByRole('complementary')).getByRole('heading', { name: task.title })).toBeDefined()
|
||||
@@ -663,12 +1080,12 @@ describe('Host task actions', () => {
|
||||
})
|
||||
|
||||
describe('rule editing', () => {
|
||||
it('saves an unchanged row so the Host can normalize its stored shape', async () => {
|
||||
it('does not write an unchanged row', async () => {
|
||||
const h = mount()
|
||||
const detail = openEdit()
|
||||
await save(detail)
|
||||
expect(within(detail).getByRole('button', { name: en['host.edit'] })).toBeDefined()
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledWith({ id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt, patch: { title: task.title } })
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('discards a staged change on Cancel', () => {
|
||||
@@ -677,7 +1094,6 @@ describe('rule editing', () => {
|
||||
fireEvent.change(within(detail).getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Renamed' } })
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['rule.cancel'] }))
|
||||
expect(within(detail).getByRole('heading', { name: task.title })).toBeDefined()
|
||||
fireEvent.click(within(detail).getByRole('button', { name: en['host.edit'] }))
|
||||
expect(within(detail).getByRole<HTMLInputElement>('textbox', { name: en['detail.name'] }).value).toBe(task.title)
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -753,17 +1169,18 @@ describe('rule editing', () => {
|
||||
expect(within(detail).getByRole<HTMLInputElement>('spinbutton', { name: en['host.monthDay'] }).value).toBe('15')
|
||||
})
|
||||
|
||||
it('keeps an empty Custom draft editable after Save reports its validation error', async () => {
|
||||
it('keeps an invalid Custom draft editable and disables Save until it is valid', async () => {
|
||||
const custom = 'DTSTART;TZID=UTC:20990101T090000\nRRULE:FREQ=WEEKLY;BYDAY=MO;COUNT=3'
|
||||
const h = mount([{ ...task, rrule: custom }])
|
||||
vi.mocked(h.props.hostActions.edit).mockResolvedValueOnce({ failed: 'host.invalidRule' })
|
||||
const detail = openEdit()
|
||||
const rule = within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['host.customRule'] })
|
||||
expect(rule.value).toBe(custom)
|
||||
fireEvent.change(rule, { target: { value: ' ' } })
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(false)
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
expect(within(detail).queryByRole('alert')).toBeNull()
|
||||
expect(within(detail).getByRole('status').textContent).not.toBe('')
|
||||
await save(detail)
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.invalidRule'])
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
expect(rule.value).toBe(' ')
|
||||
fireEvent.change(rule, { target: { value: custom.replace('COUNT=3', 'COUNT=5') } })
|
||||
await save(detail)
|
||||
@@ -811,14 +1228,13 @@ describe('rule editing', () => {
|
||||
it('edits Cron text without converting the expression or its zone into RRULE', async () => {
|
||||
const cron = { ...task, kind: 'cron' as const, expression: '0 9 * * 1-5', timeZone: 'Asia/Shanghai' }
|
||||
const h = mount([cron])
|
||||
vi.mocked(h.props.hostActions.edit).mockResolvedValueOnce({ failed: 'host.invalidRule' })
|
||||
const detail = openEdit()
|
||||
const text = within(detail).getByRole<HTMLTextAreaElement>('textbox', { name: en['host.customRule'] })
|
||||
expect(text.value).toBe(cron.expression)
|
||||
fireEvent.change(text, { target: { value: ' ' } })
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(false)
|
||||
expect(within(detail).getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
await save(detail)
|
||||
expect(within(detail).getByRole('alert').textContent).toBe(en['host.invalidRule'])
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
expect(text.value).toBe(' ')
|
||||
fireEvent.change(text, { target: { value: '0 10 * * 1-5' } })
|
||||
await save(detail)
|
||||
@@ -905,7 +1321,7 @@ describe('time zone menu', () => {
|
||||
fireEvent.click(within(menu).getByRole('menuitem'))
|
||||
expect(JSON.parse(localStorage.getItem(RECENT)!)).toEqual(['America/Toronto', 'Asia/Shanghai', 'UTC'])
|
||||
await save(detail)
|
||||
expect(h.props.hostActions.edit).toHaveBeenCalledWith({ id: task.id, action: 'update', expectedUpdatedAt: task.updatedAt, patch: { title: task.title } })
|
||||
expect(h.props.hostActions.edit).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('saves the zone whose id the search names exactly', async () => {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
/** The task tab renders the one task its navigation parameters name. */
|
||||
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import { bindSnapshotSelector, makeTranslate } from '@deepseek-ai/dsh-client-test-runtime'
|
||||
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client'
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/client'
|
||||
import type { PaneId, SidebarRightTabActions, SidebarRightTabInfo } from '@deepseek-ai/dsh-client-ui-sidebar-right/client'
|
||||
@@ -10,10 +10,10 @@ import type { ScheduleId, ScheduleCatalogEntry } from '@deepseek-ai/dsh-schedule
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import type { CatalogDeleteOutcome, CatalogSnapshot } from '../src/client/catalog-source.ts'
|
||||
import type { HostTaskActions } from '../src/client/TaskDetail.tsx'
|
||||
import { formatScheduleFrequency } from '../src/client/schedule-format.ts'
|
||||
import { ScheduleTaskTab, type ScheduleTaskTabProps } from '../src/client/ScheduleTaskTab.tsx'
|
||||
import { ScheduleTaskTabTitle, type ScheduleTaskTabTitleProps } from '../src/client/ScheduleTaskTabTitle.tsx'
|
||||
import { TaskTabBindings, type TaskTabPage } from '../src/client/task-tab-bindings.ts'
|
||||
import { createEditorStore } from '../src/client/editor-store.ts'
|
||||
import { en, zh } from '../src/client/task-manager-locales.ts'
|
||||
import css from '../src/client/TaskManagerPage.module.css'
|
||||
|
||||
@@ -87,6 +87,7 @@ function mount(
|
||||
sessionState: SessionListState = sessions,
|
||||
overrides: Partial<ScheduleTaskTabProps> = {},
|
||||
) {
|
||||
const editor = createEditorStore().create()
|
||||
// Model the source: a first read is unsettled, and only a successful read
|
||||
// settles the snapshot and advances its revision. A refresh and a failure keep
|
||||
// both, which is what separates "no answer yet" from "the last answer stands".
|
||||
@@ -99,6 +100,7 @@ function mount(
|
||||
}
|
||||
const info = params === RESTORED ? tabInfo(undefined, 0) : tabInfo(params)
|
||||
const props = {
|
||||
useStore: bindSnapshotSelector(editor), actions: editor.actions,
|
||||
sessionId: SESSION,
|
||||
useTabInfo: () => info,
|
||||
useSessions: <T,>(select: (value: SessionListState) => T): T => select(sessionState),
|
||||
@@ -178,9 +180,9 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task tab body in %s'
|
||||
expect(follows(tabs, name)).toBe(true)
|
||||
expect(follows(name, nextRun)).toBe(true)
|
||||
expect(nextRun.querySelector('time')?.dateTime).toBe(at.scheduledAt)
|
||||
expect(detail.querySelector(`.${css.readonlyPrompt}`)?.textContent).toBe(at.prompt)
|
||||
const rule = detail.querySelector<HTMLElement>(`.${css.ruleCard}`)!
|
||||
expect(rule.textContent).toContain(formatScheduleFrequency(at, makeTranslate(dictionary)))
|
||||
expect(detail.querySelector<HTMLTextAreaElement>('textarea')?.value).toBe(at.prompt)
|
||||
const rule = detail.querySelector<HTMLFieldSetElement>('fieldset')!
|
||||
expect(within(rule).getByRole('spinbutton', { name: dictionary['host.interval'] }).getAttribute('value')).toBe('5')
|
||||
expect(rule.textContent).toContain(dictionary['host.currentConversation'])
|
||||
expect(within(tabs).getAllByRole('tab')).toHaveLength(2)
|
||||
fireEvent.click(within(detail).getByRole('button', { name: dictionary['detail.more'] }))
|
||||
@@ -200,7 +202,7 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task tab body in %s'
|
||||
mount({ records: [named] })
|
||||
const detail = screen.getByRole('complementary', { name: en['detail.label'] })
|
||||
expect(within(detail).getByRole('heading', { level: 2 }).textContent).toBe('Metrics review')
|
||||
expect(detail.querySelector(`.${css.readonlyPrompt}`)?.textContent).toBe(named.prompt)
|
||||
expect(detail.querySelector<HTMLTextAreaElement>('textarea')?.value).toBe(named.prompt)
|
||||
})
|
||||
|
||||
it('labels the target Session with its catalog title instead of its id', () => {
|
||||
@@ -472,7 +474,6 @@ describe('task tab states', () => {
|
||||
const h = mount()
|
||||
const pending = Promise.withResolvers<Awaited<ReturnType<HostTaskActions['edit']>>>()
|
||||
vi.mocked(h.props.hostActions.edit).mockReturnValueOnce(pending.promise)
|
||||
fireEvent.click(screen.getByRole('button', { name: en['host.edit'] }))
|
||||
fireEvent.change(screen.getByRole('textbox', { name: en['detail.name'] }), { target: { value: 'Renamed' } })
|
||||
fireEvent.click(within(document.querySelector<HTMLElement>(`.${css.saveFooter}`)!)
|
||||
.getByRole('button', { name: en['rule.save'] }))
|
||||
|
||||
@@ -13,6 +13,7 @@ import type {
|
||||
} from '@deepseek-ai/dsh-schedule/client'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types'
|
||||
import { TaskManagerPage, type TaskManagerPageProps } from '../src/client/TaskManagerPage.tsx'
|
||||
import { createEditorStore } from '../src/client/editor-store.ts'
|
||||
import { TaskManagerIcon } from '../src/client/TaskManagerIcon.tsx'
|
||||
import type { HostTaskActions } from '../src/client/TaskDetail.tsx'
|
||||
import { createCatalogSource, type CatalogDeleteOutcome, type CatalogSnapshot } from '../src/client/catalog-source.ts'
|
||||
@@ -153,10 +154,12 @@ function mount(
|
||||
overrides: Partial<TaskManagerPageProps> = {},
|
||||
options: { startAtAll?: boolean } = {},
|
||||
) {
|
||||
const editor = createEditorStore().create()
|
||||
let snapshot: CatalogSnapshot<Entry> = {
|
||||
records, status: 'ready', deleting: [], settled: true, readRequest: 0, readSettled: 0, ...initial,
|
||||
}
|
||||
const props: TaskManagerPageProps = {
|
||||
useStore: bindSnapshotSelector(editor), actions: editor.actions,
|
||||
useCatalog: select => select(snapshot),
|
||||
useSessions: select => select(sessions),
|
||||
useWorkspaces: select => select(workspaces),
|
||||
@@ -301,9 +304,9 @@ function deliveryText(scheduledAt: string, dictionary: Dictionary): string {
|
||||
return formatScheduleNextRun(scheduledAt, dictionary['time.locale'], 'UTC')
|
||||
}
|
||||
|
||||
/** The detail's read-only instruction text, or undefined when the view shows none. */
|
||||
function readonlyPrompt(root: HTMLElement): string | null | undefined {
|
||||
return root.querySelector<HTMLElement>(`.${css.readonlyPrompt}`)?.textContent
|
||||
/** The editor's instruction text, or undefined while delivery records are shown. */
|
||||
function editorPrompt(root: HTMLElement): string | undefined {
|
||||
return root.querySelector<HTMLTextAreaElement>('textarea')?.value
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,7 +329,7 @@ function expectDetailOrder(detail: HTMLElement, dictionary: Dictionary, name: st
|
||||
expect(body.firstElementChild).toBe(heading)
|
||||
expect(heading?.contains(title)).toBe(true)
|
||||
expect(follows(title, nextRun)).toBe(true)
|
||||
expect(follows(nextRun, body.querySelector(`.${css.readonlyPrompt}`)!)).toBe(true)
|
||||
expect(follows(nextRun, body.querySelector('textarea')!)).toBe(true)
|
||||
}
|
||||
|
||||
/** Open the detail's overflow menu and return it. */
|
||||
@@ -348,9 +351,8 @@ function openDelete(dictionary: Dictionary = en): HTMLElement {
|
||||
}
|
||||
|
||||
/** Open one task's detail and enter its edit form. */
|
||||
function openEditor(name: string, dictionary: Dictionary = en): void {
|
||||
function openEditor(name: string): void {
|
||||
fireEvent.click(screen.getByRole('button', { name }))
|
||||
fireEvent.click(screen.getByRole('button', { name: dictionary['host.edit'] }))
|
||||
}
|
||||
|
||||
// The triggers are scoped to the rule card: an open panel carries the row's own
|
||||
@@ -502,10 +504,10 @@ describe('Task manager catalog', () => {
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
fireEvent.click(method)
|
||||
fireEvent.click(screen.getByRole('menuitem', { name: en['host.manualCreate'] }))
|
||||
const dialog = screen.getByRole('dialog', { name: en['host.manualCreate'] })
|
||||
const dialog = screen.getByRole('complementary')
|
||||
expect(h.props.onNewTask).toHaveBeenCalledTimes(2)
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: en['host.closeCreate'] }))
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(h.props.onCreateTask).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -573,18 +575,19 @@ describe('Task manager catalog', () => {
|
||||
const detail = screen.getByRole('complementary')
|
||||
// The detail names the task in its own heading, not through the list row's label.
|
||||
expect(within(detail).getByRole('heading', { level: 2 }).textContent).toBe('Release review')
|
||||
// The read-only view still shows the complete stored instruction.
|
||||
expect(readonlyPrompt(detail)).toBe(named.prompt)
|
||||
// The editable field still shows the complete stored instruction.
|
||||
expect(editorPrompt(detail)).toBe(named.prompt)
|
||||
})
|
||||
|
||||
it('uses shared exact frequency units in the list and selected detail', () => {
|
||||
it('uses exact frequency units in the list and matching editable controls in the detail', () => {
|
||||
const hourly = { ...every, rrule: 'DTSTART;TZID=UTC:20261001T093000\nRRULE:FREQ=HOURLY;INTERVAL=1' }
|
||||
const h = mount({ records: [hourly] })
|
||||
expect(screen.getByText('Every 1 hour')).toBeDefined()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check metrics' }))
|
||||
expect(within(screen.getByRole('complementary')).getByText('Every 1 hour')).toBeDefined()
|
||||
expect(within(screen.getByRole('complementary')).getByRole('button', { name: `${en['rule.repeat']} ${en['rule.everyHours']}` })).toBeDefined()
|
||||
expect(within(screen.getByRole('complementary')).getByRole('spinbutton', { name: en['host.interval'] }).getAttribute('value')).toBe('1')
|
||||
h.view.rerender(<TaskManagerPage {...h.props} t={makeTranslate(zh)} />)
|
||||
expect(within(screen.getByRole('complementary')).getByText('每 1 小时')).toBeDefined()
|
||||
expect(within(screen.getByRole('complementary')).getByRole('button', { name: `${zh['rule.repeat']} ${zh['rule.everyHours']}` })).toBeDefined()
|
||||
})
|
||||
|
||||
it('describes row frequency and next time without exposing its Session', () => {
|
||||
@@ -718,10 +721,10 @@ describe('Task manager catalog', () => {
|
||||
// The empty state's action opens manual creation instead of resetting the
|
||||
// filters the reader chose; closing the form leaves both in place.
|
||||
fireEvent.click(emptyNewTaskButton())
|
||||
const dialog = screen.getByRole('dialog', { name: en['host.manualCreate'] })
|
||||
const dialog = screen.getByRole('complementary')
|
||||
expect(h.props.onNewTask).not.toHaveBeenCalled()
|
||||
fireEvent.click(within(dialog).getByRole('button', { name: en['host.closeCreate'] }))
|
||||
expect(screen.queryByRole('dialog')).toBeNull()
|
||||
expect(screen.queryByRole('complementary')).toBeNull()
|
||||
expect(taskNames()).toEqual([])
|
||||
expect(screen.getByRole<HTMLInputElement>('searchbox').value).toBe('release')
|
||||
expect(within(statuses).getByRole('button', { name: en['status.ended'] }).getAttribute('aria-pressed')).toBe('true')
|
||||
@@ -791,7 +794,8 @@ describe('Task manager catalog', () => {
|
||||
expect(dailyRow.textContent).toContain(frequency)
|
||||
fireEvent.click(dailyRow)
|
||||
const detail = screen.getByRole('complementary', { name: dictionary['detail.label'] })
|
||||
expect(within(detail).getByText(frequency, { exact: true })).toBeDefined()
|
||||
expect(within(detail).getByRole('button', { name: `${dictionary['rule.repeat']} ${dictionary['rule.daily']}` })).toBeDefined()
|
||||
expect(within(detail).getByRole('button', { name: dictionary['timing.time'] }).textContent).toBe('23:00:00')
|
||||
expect(within(detail).queryByText(dictionary['frequency.once'], { exact: true })).toBeNull()
|
||||
})
|
||||
|
||||
@@ -1081,15 +1085,15 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task detail views in
|
||||
expectDetailOrder(detail, dictionary, 'Review release')
|
||||
const rules = expectDetailView(dictionary, 'rules')
|
||||
expect(h.props.loadHistory).not.toHaveBeenCalled()
|
||||
expect(readonlyPrompt(rules)).toBe(at.prompt)
|
||||
expect(editorPrompt(rules)).toBe(at.prompt)
|
||||
// One compact next-run line leads the scrolling area under the task name.
|
||||
expect(nextRunTime(detail)?.dateTime).toBe(at.scheduledAt)
|
||||
expect(nextRunTime(detail)?.textContent).toBe(absoluteNextRun(at.scheduledAt, dictionary))
|
||||
expect(relativeText(detail)).toBe(relativeNextRun(at.scheduledAt, dictionary))
|
||||
// The rule card names the recurrence and the conversation each run uses;
|
||||
// the status and the task ID stay out of the detail.
|
||||
const card = rules.querySelector<HTMLElement>(`.${css.ruleCard}`)!
|
||||
const ruleTexts = [dictionary['rule.repeat'], dictionary['frequency.once'], dictionary['host.target'], dictionary['host.currentConversation']]
|
||||
const card = rules.querySelector<HTMLFieldSetElement>('fieldset')!
|
||||
const ruleTexts = [dictionary['rule.repeat'], dictionary['rule.once'], dictionary['host.target'], dictionary['host.currentConversation']]
|
||||
for (const text of ruleTexts) {
|
||||
expect(visibleText(card, text)).toHaveLength(1)
|
||||
}
|
||||
@@ -1127,7 +1131,7 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task detail views in
|
||||
expect(visibleText(detail, dictionary['detail.nextRun'])).toHaveLength(0)
|
||||
expect(detail.querySelector(`.${css.readonlyName}`)).toBeNull()
|
||||
expect(detail.querySelector(`.${css.nextRun}`)).toBeNull()
|
||||
expect(readonlyPrompt(detail)).toBeUndefined()
|
||||
expect(editorPrompt(detail)).toBeUndefined()
|
||||
expect(recordPanel.textContent).not.toContain(at.prompt)
|
||||
expect(recordPanel.querySelectorAll('time')).toHaveLength(1)
|
||||
// The linked-Session footer stays under both views.
|
||||
@@ -1138,7 +1142,7 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task detail views in
|
||||
expectDetailView(dictionary, 'rules')
|
||||
expect(within(detail).queryByRole('region', { name: dictionary['delivery.label'] })).toBeNull()
|
||||
expect(visibleText(detail, delivery.messageId)).toHaveLength(0)
|
||||
expect(readonlyPrompt(detail)).toBe(at.prompt)
|
||||
expect(editorPrompt(detail)).toBe(at.prompt)
|
||||
})
|
||||
|
||||
it('drops the task name and next-run line on Records and restores them on Rules', async () => {
|
||||
@@ -1238,10 +1242,10 @@ describe.each([['English', en], ['Chinese', zh]] as const)('task detail views in
|
||||
fireEvent.click(screen.getByRole('tab', { name: labels.records }))
|
||||
expectDetailView(dictionary, 'records')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check metrics' }))
|
||||
expect(readonlyPrompt(expectDetailView(dictionary, 'rules'))).toBe(every.prompt)
|
||||
expect(editorPrompt(expectDetailView(dictionary, 'rules'))).toBe(every.prompt)
|
||||
fireEvent.click(screen.getByRole('tab', { name: labels.records }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Review release' }))
|
||||
expect(readonlyPrompt(expectDetailView(dictionary, 'rules'))).toBe(at.prompt)
|
||||
expect(editorPrompt(expectDetailView(dictionary, 'rules'))).toBe(at.prompt)
|
||||
for (const close of ['button', 'Escape'] as const) {
|
||||
fireEvent.click(screen.getByRole('tab', { name: labels.records }))
|
||||
if (close === 'button') fireEvent.click(screen.getByRole('button', { name: dictionary['detail.close'] }))
|
||||
@@ -1473,7 +1477,7 @@ describe('Task manager details', () => {
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check metrics' }))
|
||||
const detail = screen.getByRole('complementary')
|
||||
const rules = expectDetailView(dictionary, 'rules')
|
||||
const ruleCard = (root: HTMLElement): HTMLElement => root.querySelector<HTMLElement>(`.${css.ruleCard}`)!
|
||||
const ruleCard = (root: HTMLElement): HTMLElement => within(root).getByRole('region', { name: dictionary['rule.title'] })
|
||||
expect(nextRunTime(detail)?.dateTime).toBe(every.scheduledAt)
|
||||
expect(visibleText(ruleCard(rules), dictionary['rule.repeat'])).toHaveLength(1)
|
||||
fireEvent.click(within(detail).getByRole('tab', { name: labels.records }))
|
||||
@@ -1603,7 +1607,7 @@ describe('Task manager details', () => {
|
||||
expect(row.getAttribute('aria-controls')).toBe(detail.id)
|
||||
// The panel takes focus so the keyboard lands inside it.
|
||||
expect(document.activeElement).toBe(detail)
|
||||
expect(readonlyPrompt(detail)).toBe(at.prompt)
|
||||
expect(editorPrompt(detail)).toBe(at.prompt)
|
||||
const link = within(detail).getByRole('button', { name: en['detail.openSession'] })
|
||||
expect(link.textContent).toContain(alpha)
|
||||
expect(nextRunTime(detail)?.dateTime).toBe(at.scheduledAt)
|
||||
@@ -1655,7 +1659,7 @@ describe('Task manager details', () => {
|
||||
mount()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Review release' }))
|
||||
fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'metrics' } })
|
||||
expect(readonlyPrompt(screen.getByRole('complementary'))).toBe(at.prompt)
|
||||
expect(editorPrompt(screen.getByRole('complementary'))).toBe(at.prompt)
|
||||
fireEvent.click(screen.getByRole('button', { name: en['detail.close'] }))
|
||||
expect(document.activeElement).toBe(screen.getByRole('heading', { level: 1 }))
|
||||
})
|
||||
@@ -1668,7 +1672,8 @@ describe('Task manager details', () => {
|
||||
expect(within(statuses).getAllByRole('button')[0]?.textContent).toBe('已开启')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Check metrics' }))
|
||||
const detail = screen.getByRole('complementary', { name: '任务详情' })
|
||||
expect(within(detail).getByText(frequencyText(every, zh))).toBeDefined()
|
||||
expect(within(detail).getByRole('button', { name: `${zh['rule.repeat']} ${zh['rule.everyMinutes']}` })).toBeDefined()
|
||||
expect(within(detail).getByRole('spinbutton', { name: zh['host.interval'] }).getAttribute('value')).toBe('5')
|
||||
expect(nextRunTime(detail)?.textContent).toBe(absoluteNextRun(every.scheduledAt, zh))
|
||||
expect(relativeText(detail)).toBe(relativeNextRun(every.scheduledAt, zh))
|
||||
chooseDelete(zh)
|
||||
@@ -1713,7 +1718,8 @@ describe('Task manager details', () => {
|
||||
// The rule keeps stating its own zone where the zone belongs.
|
||||
const frequency = frequencyText(stored, en)
|
||||
expect(frequency).toContain(zoneLabel('America/New_York', makeTranslate(en)))
|
||||
expect(visibleText(detail, frequency)).toHaveLength(1)
|
||||
expect(within(detail).getByRole('button', { name: new RegExp('^' + en['timing.zone'] + ' ') }).textContent)
|
||||
.toContain(zoneLabel('America/New_York', makeTranslate(en)))
|
||||
})
|
||||
|
||||
/**
|
||||
@@ -2000,10 +2006,9 @@ describe('Mock detail metrics shared with the task list', () => {
|
||||
expect(stylesheet).toMatch(/@media \(max-width: 1100px\)\s*\{\s*\.detail\s*\{[^}]*--detail-gutter:\s*20px;/)
|
||||
expect(stylesheet).toMatch(/@media \(max-width: 400px\)\s*\{\s*\.detail\s*\{[^}]*--detail-gutter:\s*16px;/)
|
||||
expect(stylesheet).not.toMatch(/--detail-gutter:\s*18px;/)
|
||||
// The staged-save bar and its failure line consume the stepped gutter
|
||||
// instead of a literal, so the panel edge stays one column.
|
||||
// The footer uses the stepped gutter; feedback inherits the scroller's inset.
|
||||
expect(rule('saveFooter')).toMatch(/padding:\s*20px var\(--detail-gutter\);/)
|
||||
expect(rule('saveFailure')).toMatch(/padding:\s*12px var\(--detail-gutter\) 0;/)
|
||||
expect(rule('saveFailure')).toMatch(/padding:\s*12px 0 0;/)
|
||||
// The mock's `.automation-detail .detail-titlebar` narrows the strip's gap
|
||||
// at this width and closes the actions' group gap, while the strip above
|
||||
// the breakpoint keeps its 20px.
|
||||
@@ -2037,6 +2042,9 @@ describe('Task manager deletion', () => {
|
||||
expect(taskNames()).toEqual([])
|
||||
expect(screen.getByRole('status').textContent).toContain(en['list.empty'])
|
||||
expect(screen.getByRole('heading', { level: 2, name: 'Review release' })).toBeDefined()
|
||||
const detail = screen.getByRole('complementary')
|
||||
expect(within(detail).getByRole('textbox', { name: en['detail.name'] }).closest('fieldset')!.disabled).toBe(true)
|
||||
expect(within(detail).getByRole('button', { name: en['detail.close'] }).hasAttribute('disabled')).toBe(true)
|
||||
await act(async () => {
|
||||
pending.resolve('deleted')
|
||||
await pending.promise
|
||||
@@ -2275,9 +2283,8 @@ describe('timing pickers', () => {
|
||||
patch: { timing: { kind: 'rrule', rrule: 'DTSTART;TZID=UTC:20261001T090030\nRRULE:FREQ=DAILY;COUNT=1' } },
|
||||
})
|
||||
await act(async () => {})
|
||||
// The saved form gives way to the read-only view, and its Edit button takes the focus back.
|
||||
expect(screen.queryByRole('region', { name: en['rule.title'] })).toBeNull()
|
||||
expect(document.activeElement).toBe(screen.getByRole('button', { name: en['host.edit'] }))
|
||||
expect(screen.getByRole('region', { name: en['rule.title'] })).toBeDefined()
|
||||
expect(screen.getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('offers hours and minutes only for a daily rule and saves the picked minute', async () => {
|
||||
@@ -2398,7 +2405,8 @@ describe('timing pickers', () => {
|
||||
pending.resolve('saved')
|
||||
await pending.promise
|
||||
})
|
||||
expect(screen.queryByRole('region', { name: en['rule.title'] })).toBeNull()
|
||||
expect(screen.getByRole('region', { name: en['rule.title'] })).toBeDefined()
|
||||
expect(screen.getByRole('button', { name: en['rule.save'] }).hasAttribute('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
it('opens the month grid on the stored day, marks today, and stages a picked day', () => {
|
||||
@@ -2472,7 +2480,7 @@ describe('timing pickers', () => {
|
||||
|
||||
it.each([en, zh])('names every picker part in %s', (dictionary) => {
|
||||
mount({ records: [at] }, dictionary)
|
||||
openEditor('Review release', dictionary)
|
||||
openEditor('Review release')
|
||||
fireEvent.click(timeButton(dictionary))
|
||||
expect(screen.getByRole('dialog', { name: dictionary['timing.time'] })).toBeDefined()
|
||||
for (const key of ['timing.hour', 'timing.minute', 'timing.second'] as const) {
|
||||
|
||||
Generated
+3
@@ -5404,6 +5404,9 @@ importers:
|
||||
'@deepseek-ai/dsh-client-locale':
|
||||
specifier: workspace:*
|
||||
version: link:../locale
|
||||
'@deepseek-ai/dsh-client-store':
|
||||
specifier: workspace:*
|
||||
version: link:../store
|
||||
'@deepseek-ai/dsh-client-test-runtime':
|
||||
specifier: workspace:*
|
||||
version: link:../../test-support/client-runtime
|
||||
|
||||
Reference in new issue
Block a user