Merge pull request #8381 from deepseek-harness/feat/schedule-empty-recommendations

feat(ui-schedule): recommend tasks under the empty automation page
This commit is contained in:
Ziya authored and GitHub committed 2026-11-13 01:47:50 -08:00
commit f465541b32
17 files changed
+890 -16

No files matched your search

@@ -0,0 +1,17 @@
- region "Recommended":
- heading "Recommended" [level=2]
- list:
- listitem:
- button "Daily brief": Daily brief Recent changes in the workspace and what needs follow-up, with what to do first today. Weekdays at 9:00
- listitem:
- button "Issue scan": Issue scan Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply. Weekdays at {{clock}}
- listitem:
- button "Plugin compatibility check": Plugin compatibility check When a new DSH version ships, check whether installed and self-made plugins need changes. Daily at {{clock}}
- listitem:
- button "Topic and paper tracking": Topic and paper tracking Search for news and new arXiv papers on chosen topics and list the key points. Daily at 9:00
- listitem:
- button "Branch and worktree cleanup": Branch and worktree cleanup List local branches and worktrees whose pull requests merged or closed, and delete them after confirmation. Fridays at {{clock}}
- listitem:
- button "Weather and travel": Weather and travel Weather for today and the next three days, with a note when an umbrella or warmer clothes are needed. Daily at 7:30
- listitem:
- button "Weekly workout plan": Weekly workout plan Plan next week's workouts around your goals and training days. Sundays at {{clock}}
@@ -0,0 +1,17 @@
- region "推荐":
- heading "推荐" [level=2]
- list:
- listitem:
- button "每日简报": 每日简报 汇总工作区最近的变化和待跟进的事,列出今天先做什么。 工作日 9:00
- listitem:
- button "Issue 扫描": Issue 扫描 把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。 工作日 {{clock}}
- listitem:
- button "插件兼容检查": 插件兼容检查 DSH 出新版本时,检查已装的插件和自己做的插件要不要改。 每天 {{clock}}
- listitem:
- button "主题和论文追踪": 主题和论文追踪 搜索关注主题的新消息和 arXiv 新论文,各列几条要点。 每天 9:00
- listitem:
- button "分支和 worktree 清理": 分支和 worktree 清理 列出 PR 已合并或关闭的本地分支和 worktree,确认后再删。 周五 {{clock}}
- listitem:
- button "天气和出行": 天气和出行 今天和接下来三天的天气,要带伞或加衣时提一句。 每天 7:30
- listitem:
- button "一周运动计划": 一周运动计划 按目标和每周能练的日子排好下周的运动计划。 周日 {{clock}}
+94 -3
View File
@@ -1,9 +1,10 @@
/** Schedule creation, prompt prefill, and editing through the shipped Web composition. */
import { chromium } from 'playwright'
import { fileURLToPath } from 'node:url'
import { chromium, type Locator } from 'playwright'
import { expect, it } from 'vitest'
import type { ScheduleTiming } from '@deepseek-ai/dsh-schedule/client'
import { launchWebScaffold, watchConsole } from './scaffold.ts'
import { writeComposerDraft } from './support.ts'
import { captureStableAria, compareOrRefreshGolden, launchWebScaffold, watchConsole, webSnapshotMode } from './scaffold.ts'
import { revealNavigationDrawer, writeComposerDraft } from './support.ts'
it.each([
{ locale: 'en', panel: 'Automation tasks', create: 'New', menu: 'Choose a creation method', chat: 'Create in a session',
@@ -48,6 +49,96 @@ it.each([
}
})
it.each([
{ locale: 'en', panel: 'Automation tasks', heading: 'Recommended', title: 'Daily brief',
prompt: 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.' },
{ locale: 'zh', panel: '自动化任务', heading: '推荐', title: '每日简报',
prompt: '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。' },
])('prefills a recommended task request from the empty task page in $locale', async (copy) => {
const scaffold = await launchWebScaffold({ firstUse: true })
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
try {
browser = await chromium.launch()
const page = await browser.newPage({ viewport: { width: 1440, height: 960 }, locale: copy.locale })
await page.addInitScript((locale) => { localStorage.setItem('dsh.locale', locale) }, copy.locale)
const tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
const input = page.locator('[data-composer-input][contenteditable="true"]').first()
for (const draft of ['', 'Existing unsent draft']) {
await writeComposerDraft(page, input, draft)
await page.getByRole('button', { name: copy.panel, exact: true }).click()
const manager = page.getByTestId('task-manager-page')
const recommendations = manager.getByRole('region', { name: copy.heading, exact: true })
const recommendation = recommendations.getByRole('button', { name: copy.title, exact: true })
await recommendation.waitFor()
expect(await recommendations.getByRole('button').count()).toBe(7)
if (draft === '') {
expect(await recommendationColumns(recommendations)).toBe(2)
await compareOrRefreshGolden(
fileURLToPath(new URL(`./expected/schedule-recommendations-${copy.locale}.expected.md`, import.meta.url)),
await captureStableAria(page, '[data-testid="schedule-recommendations"]', scaffold.workspaceCwd),
webSnapshotMode(),
)
}
await recommendation.click()
await manager.waitFor({ state: 'detached' })
await input.getByText(copy.prompt, { exact: true }).waitFor()
expect(await input.evaluate(element => [...element.children].map(paragraph => paragraph.textContent).join('\n')))
.toBe(draft === '' ? copy.prompt : `${draft}\n${copy.prompt}`)
const events = scaffold.ctx.agents.list().flatMap(agent => agent.session.snapshotEvents())
expect(events.filter(event => event.type === 'user/message' || event.type === 'turn/start')).toEqual([])
expect(await scaffold.ctx.schedule.catalog()).toEqual([])
}
expect(tripwire.pageErrors).toEqual([])
} finally {
try { await browser?.close() } finally { await scaffold.close() }
}
})
/** Number of grid tracks the recommendation list lays its tiles in. */
async function recommendationColumns(recommendations: Locator): Promise<number> {
return recommendations.getByRole('list').evaluate(list => getComputedStyle(list).gridTemplateColumns.split(' ').length)
}
it.each([
{ locale: 'en', panel: 'Automation tasks', title: 'Daily brief' },
{ locale: 'de', panel: 'Automatisierungsaufgaben', title: 'Tagesüberblick' },
] as const)('shows every recommendation title and description in full on phone and desktop widths in $locale', async (copy) => {
const scaffold = await launchWebScaffold({ firstUse: true })
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
try {
browser = await chromium.launch()
// 680px puts the list just above the 600px column breakpoint, where each column is narrowest.
for (const { width, columns } of [{ width: 390, columns: 1 }, { width: 680, columns: 2 }, { width: 1440, columns: 2 }]) {
const phone = width < 600
const page = await browser.newPage({ viewport: { width, height: 900 }, isMobile: phone, hasTouch: phone, locale: copy.locale })
await page.addInitScript((locale) => { localStorage.setItem('dsh.locale', locale) }, copy.locale)
const tripwire = watchConsole(page)
await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' })
await revealNavigationDrawer(page, copy.locale)
await page.getByRole('button', { name: copy.panel, exact: true }).click()
const recommendations = page.getByTestId('schedule-recommendations')
await recommendations.getByRole('button', { name: copy.title, exact: true }).waitFor()
await page.evaluate(() => document.fonts.ready)
expect(await recommendationColumns(recommendations)).toBe(columns)
// The title carries the button's name and the first description reference is the description; neither clips.
expect(await recommendations.getByRole('button').evaluateAll(buttons => buttons.flatMap((button) => {
const name = button.getAttribute('aria-label')!
const title = [...button.querySelectorAll('span')].find(span => span.textContent === name)!
const description = document.getElementById(button.getAttribute('aria-describedby')!.split(' ')[0]!)!
return [
...title.scrollWidth > title.clientWidth ? [`title: ${name}`] : [],
...description.scrollHeight > description.clientHeight ? [`description: ${name}`] : [],
]
}))).toEqual([])
expect(tripwire.pageErrors).toEqual([])
await page.close()
}
} finally {
try { await browser?.close() } finally { await scaffold.close() }
}
})
it('opens stored timing fields immediately without selecting another repeat option', async () => {
const scaffold = await launchWebScaffold({ firstUse: true })
let browser: Awaited<ReturnType<typeof chromium.launch>> | undefined
+2 -2
View File
@@ -308,14 +308,14 @@ export function probeFreePort(): Promise<number> {
* @param page - browser page with the mounted sidebar.
* @param locale - current UI language.
*/
export async function revealNavigationDrawer(page: Page, locale: 'en' | 'zh' | 'ja'): Promise<void> {
export async function revealNavigationDrawer(page: Page, locale: 'en' | 'zh' | 'ja' | 'de'): Promise<void> {
const drawer = await page.evaluate(() => window.innerWidth < 768
&& !document.documentElement.hasAttribute('data-windows-titlebar'))
await page.waitForFunction(expected => Boolean(document.querySelector('[data-sidebar-drawer]')) === expected, drawer)
const closed = page.locator('[data-sidebar-drawer][data-sidebar-collapsed]')
if (await closed.count() === 0) return
await page.locator('[data-shell-leading]').getByRole('button', {
name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く' }[locale], exact: true,
name: { en: 'Open sidebar', zh: '打开侧边栏', ja: 'サイドバーを開く', de: 'Seitenleiste öffnen' }[locale], exact: true,
}).click()
await closed.waitFor({ state: 'detached' })
}
+4 -4
View File
@@ -15,8 +15,8 @@
en: d152484eb41ac6b4
zh: 405b30feaf48c087
/deepseek-ai-dsh-client-ui-schedule/use-this-package:
en: 68526e7df25338d4
zh: 3bfdfa01dc9afaec
en: 330bf974a2f6d305
zh: 3efbe98ff08058b1
/deepseek-ai-dsh-client-ui-schedule/use-this-package/time-zone-data-source:
en: 4005b800e930f581
zh: ccb9318dad7f7e8f
@@ -27,8 +27,8 @@
en: 2fd968202916b197
zh: f1ab66194846562b
/deepseek-ai-dsh-client-ui-schedule/model-experience:
en: 6f528a72fe45af1b
zh: 8272529f6e324315
en: b75d2a967fdce99c
zh: f1464a27481329f2
/deepseek-ai-dsh-client-ui-schedule/model-experience/kv-cache-effect:
en: 52239e5688dfebe1
zh: 37343f5dbde010e8
+2 -2
View File
@@ -27,7 +27,7 @@ The Automation tasks page and right Sidebar task tab use the same editor for tas
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 and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers 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.
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 and the adjacent menu's Create in a session action both open a new conversation with a short task-creation prompt in the current UI language, ready for the user to complete and send. When a blank conversation is reused, the prompt is appended on a new line, preserving its text, inline references, and attachments. The same menu offers 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. Below the empty Enabled and All views, seven built-in recommended tasks appear in two columns, each with a glyph, title, description, and default run time. Choosing one opens a new conversation with that task's request prefilled in the same way. Each glyph tile takes the empty-state artwork's background color, and its glyph is drawn in blue with a light blue fill.
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.
@@ -74,7 +74,7 @@ Sidebar layout records omit opener parameters. `TaskTabBindings` therefore persi
<a id="model-experience"></a>
## Model Experience
None, as this browser package registers no model tools or automatic messages; the creation prompt stays an unsent draft.
None, as this browser package registers no model tools or automatic messages; the creation prompt and recommended-task requests stay unsent drafts.
#### KV Cache effect
+2 -2
View File
@@ -27,7 +27,7 @@ kind: "package-reference"
宽度小于 768px 时,任务列表使用 20px 的左右内边距,与插件页一致。
发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。
发布的 Web 组合将 `ui-schedule` 与宿主 Schedule 一起挂载。自动化任务侧栏入口打开任务列表,不选择或激活会话。“新建”和相邻菜单的“在会话中创建”都会进入新会话,按当前界面语言预填简短的任务创建提示,供用户补充并发送。若复用空白会话,提示会另起一行追加,保留原有文本、行内引用和附件。该菜单还提供“手动创建”。手动创建与已有任务打开同一编辑页,校验必填项并保存任务,不启动 Agent 或发送指令。请求失败时保留表单和已填内容。空态显示装饰性的文档与时钟插图,其颜色随主题变化。“已开启”和“全部”的空态下方以两列列出七个内置推荐任务,每项显示图标、标题、说明和默认运行时间。点击其中一项会同样进入新会话,并预填该任务的请求。推荐图标块使用空态插图的背景色,图标为蓝色线条加浅蓝填充。
“已开启”“已暂停”“已结束”“全部”筛选结合标题、指令和关联会话 id 搜索,默认显示已开启任务。搜索行菜单在确认后清除全部已结束任务,保留已开启和已暂停任务。选择任务直接打开可编辑的“规则 / 任务运行记录”页面。只有字段有效且有实际修改时才能保存;保存只发送变更字段及 `expectedUpdatedAt`,存储版本缺失时发送 `null`。保存后字段保持可编辑。切换任务或离开页面时保留未保存的草稿。冲突保留整份草稿并禁用保存。“保留修改并复核”将改过的字段组应用到最新值,供保存前复核;“放弃”用最新存储值替换草稿。对于新任务,“放弃”关闭编辑页。迟到响应不会改变其他任务详情。粗指针设备的搜索、指令和时间字段使用 16px 字号,避免 iOS Safari 聚焦时缩放。
@@ -74,7 +74,7 @@ Peer 可读取 `schedule/catalog` 时,插件注册现有 `schedules` 主面板
<a id="model-experience"></a>
## 模型体验
无:本浏览器包不注册模型工具或自动消息;创建提示保留为未发送的草稿。
无:本浏览器包不注册模型工具或自动消息;创建提示和推荐任务的请求都保留为未发送的草稿。
#### KV Cache 影响
@@ -0,0 +1,137 @@
/**
* Tile glyphs for recommended tasks: a 20px grid drawn 1:1 at 20px with 1.25px
* `currentColor` strokes, the shared icons' Regular weight (one unit on their
* 16-unit grid) at this size, with round caps and round joins. Each glyph marks
* its main shape with `data-fill`; the page stylesheet supplies that fill color.
*/
import type { ReactNode } from 'react'
/** Props every tile glyph accepts. */
export interface TileGlyphProps {
readonly className?: string | undefined
}
function Glyph({ className, children }: TileGlyphProps & { readonly children: ReactNode }): ReactNode {
return (
<svg className={className} width={20} height={20} viewBox="0 0 20 20" fill="none" stroke="currentColor"
strokeWidth={1.25} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
{children}
</svg>
)
}
/**
* Half sun over a horizon: a morning brief.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function SunriseGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<path data-fill="" d="M5 14A5 5 0 0 1 15 14Z" />
<path d="M2.5 14H17.5" />
<path d="M6.5 17H13.5" />
<path d="M10 4.75V6.75" />
<path d="M3.92 7.92L5.19 9.19" />
<path d="M16.08 7.92L14.81 9.19" />
</Glyph>
)
}
/**
* Open-issue mark: a ring with a center dot.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function IssueGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<circle data-fill="" cx="10" cy="10" r="7" />
<circle cx="10" cy="10" r="1.75" fill="currentColor" stroke="none" />
</Glyph>
)
}
/**
* Puzzle piece with a check: plugins that still fit.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function PluginCheckGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<path data-fill="" d="M4.5 6.5H7A2 2 0 1 1 11 6.5H13.5A1 1 0 0 1 14.5 7.5V10A2 2 0 1 1 14.5 14V16.5A1 1 0 0 1 13.5 17.5H4.5A1 1 0 0 1 3.5 16.5V7.5A1 1 0 0 1 4.5 6.5Z" />
<path d="M6.5 12.25L8.25 14L11.5 10.5" />
</Glyph>
)
}
/**
* Newspaper page: an image block, short headlines and a body line.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function NewspaperGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<path data-fill="" d="M4.5 3.5H15.5A2 2 0 0 1 17.5 5.5V14.5A2 2 0 0 1 15.5 16.5H4.5A2 2 0 0 1 2.5 14.5V5.5A2 2 0 0 1 4.5 3.5Z" />
<path data-fill="" d="M5.5 6.75H9.25V10.25H5.5Z" />
<path d="M11.75 7H14.5" />
<path d="M11.75 10H14.5" />
<path d="M5.5 13.25H14.5" />
</Glyph>
)
}
/**
* Branch: a trunk with a side branch joining it.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function BranchGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<circle data-fill="" cx="6" cy="4.5" r="2" />
<circle data-fill="" cx="6" cy="15.5" r="2" />
<circle data-fill="" cx="14" cy="6.5" r="2" />
<path d="M6 6.5V13.5" />
<path d="M14 8.5V9A4.5 4.5 0 0 1 9.5 13.5H6" />
</Glyph>
)
}
/**
* Sun partly behind a cloud: weather.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function CloudSunGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<path d="M10.43 8.12A3 3 0 1 0 6.62 10.37" />
<path d="M7.5 1.9V3.1" />
<path d="M1.9 7.5H3.1" />
<path d="M3.54 3.54L4.39 4.39" />
<path d="M11.46 3.54L10.61 4.39" />
<path d="M3.54 11.46L4.39 10.61" />
<path data-fill="" d="M7 16.5H14.5A3 3 0 0 0 14.5 10.5A4.5 4.5 0 0 0 6.2 12.4A2.1 2.1 0 0 0 7 16.5Z" />
</Glyph>
)
}
/**
* Dumbbell: a bar between two plates and two collars.
* @param props - class of the root SVG.
* @returns the glyph.
*/
export function DumbbellGlyph(props: TileGlyphProps): ReactNode {
return (
<Glyph {...props}>
<path d="M7.5 10H12.5" />
<path data-fill="" d="M6 4.5H7.5V15.5H6A1.5 1.5 0 0 1 4.5 14V6A1.5 1.5 0 0 1 6 4.5Z" />
<path data-fill="" d="M14 4.5H12.5V15.5H14A1.5 1.5 0 0 0 15.5 14V6A1.5 1.5 0 0 0 14 4.5Z" />
<path d="M4.5 7H3A1 1 0 0 0 2 8V12A1 1 0 0 0 3 13H4.5" />
<path d="M15.5 7H17A1 1 0 0 1 18 8V12A1 1 0 0 1 17 13H15.5" />
</Glyph>
)
}
@@ -0,0 +1,74 @@
/** Built-in task recommendations under the empty task catalog; choosing one prefills a new Session. */
import { useId, type ReactNode } from 'react'
import { Button, IconClockOutlineRegular, IconPlusOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives'
import type { TaskManagerKey } from './task-manager-locales.ts'
import {
BranchGlyph, CloudSunGlyph, DumbbellGlyph, IssueGlyph, NewspaperGlyph, PluginCheckGlyph,
SunriseGlyph, type TileGlyphProps,
} from './RecommendationArtwork.tsx'
import css from './TaskManagerPage.module.css'
const RECOMMENDATIONS = [
{ id: 'dailyBrief', Glyph: SunriseGlyph },
{ id: 'issueScan', Glyph: IssueGlyph },
{ id: 'pluginCompat', Glyph: PluginCheckGlyph },
{ id: 'topicTracking', Glyph: NewspaperGlyph },
{ id: 'branchCleanup', Glyph: BranchGlyph },
{ id: 'weather', Glyph: CloudSunGlyph },
{ id: 'workout', Glyph: DumbbellGlyph },
] as const satisfies readonly { readonly id: string; readonly Glyph: (props: TileGlyphProps) => ReactNode }[]
/** Props of the recommendation section. */
export interface ScheduleRecommendationsProps {
/** Task-manager copy. */
readonly t: (key: TaskManagerKey) => string
/**
* Start a new Session with a recommendation's request prefilled.
* @param prompt - the recommendation's localized request.
*/
readonly onUse: (prompt: string) => void
}
/**
* Render the built-in recommendations as a two-column grid of tiles, each with
* its title, description, and default run time.
* @param props - copy and the prefill action.
* @returns the section listing every recommendation.
*/
export function ScheduleRecommendations({ t, onUse }: ScheduleRecommendationsProps): ReactNode {
const baseId = useId()
return (
<section className={css.recommendations} aria-labelledby={`${baseId}-heading`} data-testid="schedule-recommendations">
<h2 id={`${baseId}-heading`} className={css.recommendationsHeading}>{t('recommend.heading')}</h2>
<ul className={css.recommendationGrid}>
{RECOMMENDATIONS.map(({ id, Glyph }) => (
<li key={id}>
<Button
className={css.recommendation}
aria-label={t(`recommend.${id}.title`)}
aria-describedby={`${baseId}-${id}-description ${baseId}-${id}-schedule`}
onClick={() => { onUse(t(`recommend.${id}.prompt`)) }}
>
<span className={css.tile}>
<Glyph className={css.tileGlyph} />
<IconPlusOutlineRegular className={css.tilePlus} size={18} />
</span>
<span className={css.recommendationContent}>
<span className={css.recommendationTitle}>{t(`recommend.${id}.title`)}</span>
<span className={css.recommendationDetails}>
<span id={`${baseId}-${id}-description`} className={css.recommendationDescription}>
{t(`recommend.${id}.description`)}
</span>
<span id={`${baseId}-${id}-schedule`} className={css.recommendationWhen}>
<IconClockOutlineRegular className={css.whenGlyph} size={14} />
{t(`recommend.${id}.schedule`)}
</span>
</span>
</span>
</Button>
</li>
))}
</ul>
</section>
)
}
@@ -1441,3 +1441,136 @@
font-size: 16px;
}
}
/* Recommended tasks under the empty Enabled and All views: a two-column grid,
one column below 600px of content width. The heading starts on the tiles'
12px inset. */
.recommendations {
container-type: inline-size;
margin-top: 8px;
}
.recommendationsHeading {
margin: 0 0 6px;
padding: 0 12px;
color: var(--dsw-alias-label-tertiary);
font-size: 13px;
line-height: 20px;
font-weight: 500;
}
.recommendationGrid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 4px 16px;
margin: 0;
padding: 0;
list-style: none;
}
@container (max-width: 600px) {
.recommendationGrid {
grid-template-columns: minmax(0, 1fr);
}
}
.recommendation {
display: flex;
align-items: flex-start;
justify-content: flex-start;
gap: 14px;
width: 100%;
height: auto;
padding: 12px;
border-radius: var(--dsw-radius-lg);
text-align: left;
white-space: normal;
}
/* Tiles take the empty illustration's background. Glyphs draw in the blue
accent, and each glyph's main shape takes a 16% tint of that blue, which
stays visible against the tile in both themes. */
.tile {
display: flex;
flex: none;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
border-radius: var(--dsw-radius-md);
background: var(--dsw-alias-illustration-background);
color: var(--dsw-alias-state-business-primary);
}
.tile [data-fill] {
fill: currentColor;
fill-opacity: 0.16;
}
.tileGlyph {
flex: none;
width: 20px;
height: 20px;
}
.tilePlus {
display: none;
flex: none;
}
.recommendation:focus-visible .tileGlyph {
display: none;
}
.recommendation:focus-visible .tilePlus {
display: block;
}
@media (hover: hover) {
.recommendation:hover .tileGlyph {
display: none;
}
.recommendation:hover .tilePlus {
display: block;
}
}
.recommendationContent,
.recommendationDetails {
display: flex;
flex-direction: column;
min-width: 0;
}
.recommendationContent {
flex: 1;
}
.recommendationTitle {
font-weight: 500;
line-height: 22px;
}
.recommendationDescription {
margin-top: 2px;
color: var(--dsw-alias-label-secondary);
font-size: 13px;
line-height: 20px;
}
.recommendationWhen {
display: flex;
align-items: center;
gap: 6px;
margin-top: 6px;
color: var(--dsw-alias-label-tertiary);
font-size: 13px;
line-height: 20px;
}
.whenGlyph {
flex: none;
width: 14px;
height: 14px;
}
@@ -20,6 +20,7 @@ import { useRelativeClock } from './relative-clock.ts'
import { formatScheduleFrequency, nextRunParts, taskName, zoneLabel } from './schedule-format.ts'
import type { FrequencyZone } from './schedule-format.ts'
import { ScheduleEmptyIllustration } from './ScheduleEmptyIllustration.tsx'
import { ScheduleRecommendations } from './ScheduleRecommendations.tsx'
import css from './TaskManagerPage.module.css'
/** Injected catalog and task actions for the management page. */
@@ -31,6 +32,12 @@ export interface TaskManagerInjected extends TaskDetailInjected {
* schedule it, using the existing new-conversation action.
*/
readonly onNewTask: () => void
/**
* Start a new Session with a recommended task's request prefilled, through
* the same new-conversation action as `onNewTask`.
* @param prompt - the recommendation's localized request.
*/
readonly onUseRecommendation: (prompt: string) => void
/**
* Remove every ended Host task, after this page has confirmed the action.
*
@@ -59,7 +66,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, t } = props
const { useCatalog, onNewTask, onUseRecommendation, onClearEnded, onRetry, onCreateTask, t } = props
const [createMenuOpen, setCreateMenuOpen] = useState(false)
const [manualOpen, setManualOpen] = useState(false)
const catalog = useCatalog(snapshot => snapshot)
@@ -101,6 +108,8 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
), [records, statusFilter])
const rows = useMemo(() => rowIndex.search(search), [rowIndex, search])
const showRecommendations = status === 'ready' && rows.length === 0 && search.trim() === ''
&& (statusFilter === 'active' || statusFilter === 'all')
const emptyTitle = search.trim() !== '' ? 'list.noMatches'
: statusFilter === 'paused' ? 'list.emptyPaused'
: statusFilter === 'ended' ? 'list.emptyInactive'
@@ -285,6 +294,7 @@ export function TaskManagerPage(props: TaskManagerPageProps) {
{t('empty.action')}
</Button>
</div>}
{showRecommendations && <ScheduleRecommendations t={t} onUse={onUseRecommendation} />}
<ul className={css.listRows} aria-label={t('list.label')} aria-busy={status === 'loading'}>
{rows.map((record) => {
// One pair per row: the same absolute stamp and distance reach
@@ -215,6 +215,11 @@ export function apply(ctx: ClientContext): void {
locale: MANAGER_NS,
inject: (): ScheduleTaskCatalogInjected & ScheduleTaskBindingInjected => ({ hooks: detail.hooks, taskBindings }),
}, ScheduleTaskTabTitle))
// New and every recommendation open a new conversation with a request in its
// composer, appended to the draft of a reused blank conversation.
const startWithPrompt = (prompt: string): void => {
ctx.uiWorkspace.startSession(undefined, { prompt, whenDraftExists: 'append' })
}
yield ctx.slots.inject('main', () => ctx.slots.register({
name: 'main',
key: PANEL_ID,
@@ -222,7 +227,8 @@ export function apply(ctx: ClientContext): void {
store: createEditorStore(),
inject: (): TaskManagerInjected => ({
...detail,
onNewTask: () => { ctx.uiWorkspace.startSession(undefined, { prompt: t('host.createPrompt'), whenDraftExists: 'append' }) },
onNewTask: () => { startWithPrompt(t('host.createPrompt')) },
onUseRecommendation: startWithPrompt,
onClearEnded: async () => {
const outcome = await clearEnded()
deleteToast.reportClear(outcome)
@@ -0,0 +1,265 @@
/** Copy for the recommended tasks shown in the empty task catalog. */
/** English recommendation copy. */
export const recommendationEn = {
'recommend.heading': 'Recommended',
'recommend.dailyBrief.title': 'Daily brief',
'recommend.dailyBrief.description': 'Recent changes in the workspace and what needs follow-up, with what to do first today.',
'recommend.dailyBrief.schedule': 'Weekdays at 9:00',
'recommend.dailyBrief.prompt': 'Create an automation task named "Daily brief": every weekday at 9:00, review the last 24 hours of changes in the current workspace and list what needs my follow-up and what to do first today; when the workspace is a code repository, also cover new commits, pull requests awaiting my review, and failing CI.',
'recommend.issueScan.title': 'Issue scan',
'recommend.issueScan.description': 'Sort new issues into bugs, requests, and questions, and flag duplicates and ones that need a reply.',
'recommend.issueScan.schedule': 'Weekdays at 10:00',
'recommend.issueScan.prompt': 'Create an automation task named "Issue scan": every weekday at 10:00, scan new issues in the current workspace repository, sort them into bugs, requests, and questions, and flag duplicates and ones that need my reply. Summarize here only; do not reply on GitHub.',
'recommend.pluginCompat.title': 'Plugin compatibility check',
'recommend.pluginCompat.description': 'When a new DSH version ships, check whether installed and self-made plugins need changes.',
'recommend.pluginCompat.schedule': 'Daily at 10:00',
'recommend.pluginCompat.prompt': 'Create an automation task named "Plugin compatibility check": every day at 10:00, check whether a new DSH version is available; if so, read its upgrade guide, check whether each non-official or self-made plugin I have installed is affected, and list what to change and how.',
'recommend.topicTracking.title': 'Topic and paper tracking',
'recommend.topicTracking.description': 'Search for news and new arXiv papers on chosen topics and list the key points.',
'recommend.topicTracking.schedule': 'Daily at 9:00',
'recommend.topicTracking.prompt': 'Create an automation task named "Topic and paper tracking": every day at 9:00, search for new articles and arXiv papers on the topics I follow and list a few key points for each. Before creating it, ask me for the topics, keywords, and sources.',
'recommend.branchCleanup.title': 'Branch and worktree cleanup',
'recommend.branchCleanup.description': 'List local branches and worktrees whose pull requests merged or closed, and delete them after confirmation.',
'recommend.branchCleanup.schedule': 'Fridays at 17:00',
'recommend.branchCleanup.prompt': 'Create an automation task named "Branch and worktree cleanup": every Friday at 17:00, list local branches and worktrees in the current workspace whose pull requests are merged or closed, and delete them only after I confirm.',
'recommend.weather.title': 'Weather and travel',
'recommend.weather.description': 'Weather for today and the next three days, with a note when an umbrella or warmer clothes are needed.',
'recommend.weather.schedule': 'Daily at 7:30',
'recommend.weather.prompt': 'Create an automation task named "Weather and travel": every day at 7:30, tell me the weather in my city for today and the next three days, and call out when I should bring an umbrella, dress warmer, or expect travel disruption. Before creating it, ask me for my city.',
'recommend.workout.title': 'Weekly workout plan',
'recommend.workout.description': 'Plan next week\'s workouts around your goals and training days.',
'recommend.workout.schedule': 'Sundays at 20:00',
'recommend.workout.prompt': 'Create an automation task named "Weekly workout plan": every Sunday at 20:00, plan my workouts for next week around my goals and the days I can train, without asking me anything when it runs. Before creating it, ask me about my goals, how many days a week I can train, which days I am free, and where I train.',
} as const
/** Simplified Chinese recommendation copy. */
export const recommendationZh: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': '推荐',
'recommend.dailyBrief.title': '每日简报',
'recommend.dailyBrief.description': '汇总工作区最近的变化和待跟进的事,列出今天先做什么。',
'recommend.dailyBrief.schedule': '工作日 9:00',
'recommend.dailyBrief.prompt': '创建一个名为「每日简报」的自动化任务:每个工作日 9:00 查看当前工作区过去 24 小时的变化,列出需要我跟进的事和今天先做的事;工作区是代码仓库时,也看新提交、待我评审的 PR 和失败的 CI。',
'recommend.issueScan.title': 'Issue 扫描',
'recommend.issueScan.description': '把新开的 issue 分成 bug、需求、提问,标出重复的和需要回复的。',
'recommend.issueScan.schedule': '工作日 10:00',
'recommend.issueScan.prompt': '创建一个名为「Issue 扫描」的自动化任务:每个工作日 10:00 扫描当前工作区仓库新开的 issue,分成 bug、需求、提问,标出重复的和需要我回复的,只在这里汇总,不在 GitHub 上回复。',
'recommend.pluginCompat.title': '插件兼容检查',
'recommend.pluginCompat.description': 'DSH 出新版本时,检查已装的插件和自己做的插件要不要改。',
'recommend.pluginCompat.schedule': '每天 10:00',
'recommend.pluginCompat.prompt': '创建一个名为「插件兼容检查」的自动化任务:每天 10:00 检查 DSH 有没有新版本;有的话读这个版本的升级指引,逐个检查我装的非官方插件和自己做的插件会不会受影响,列出要改的地方和改法。',
'recommend.topicTracking.title': '主题和论文追踪',
'recommend.topicTracking.description': '搜索关注主题的新消息和 arXiv 新论文,各列几条要点。',
'recommend.topicTracking.schedule': '每天 9:00',
'recommend.topicTracking.prompt': '创建一个名为「主题和论文追踪」的自动化任务:每天 9:00 搜索我关注主题的新消息和 arXiv 新论文,各列几条要点。创建前先问我主题、关键词和来源。',
'recommend.branchCleanup.title': '分支和 worktree 清理',
'recommend.branchCleanup.description': '列出 PR 已合并或关闭的本地分支和 worktree,确认后再删。',
'recommend.branchCleanup.schedule': '周五 17:00',
'recommend.branchCleanup.prompt': '创建一个名为「分支和 worktree 清理」的自动化任务:每周五 17:00 列出当前工作区里 PR 已合并或关闭的本地分支和 worktree,我确认后再删。',
'recommend.weather.title': '天气和出行',
'recommend.weather.description': '今天和接下来三天的天气,要带伞或加衣时提一句。',
'recommend.weather.schedule': '每天 7:30',
'recommend.weather.prompt': '创建一个名为「天气和出行」的自动化任务:每天 7:30 告诉我所在城市今天和接下来三天的天气,要带伞、加衣或出行受影响时单独提一句。创建前先问我城市。',
'recommend.workout.title': '一周运动计划',
'recommend.workout.description': '按目标和每周能练的日子排好下周的运动计划。',
'recommend.workout.schedule': '周日 20:00',
'recommend.workout.prompt': '创建一个名为「一周运动计划」的自动化任务:每周日 20:00 按我的目标和每周能练的日子排好下周的运动计划,运行时不再问我。创建前先问我目标、每周能练几天、哪几天有空、在哪练。',
}
/** Japanese recommendation copy. */
export const recommendationJa: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'おすすめ',
'recommend.dailyBrief.title': 'デイリーブリーフィング',
'recommend.dailyBrief.description': 'ワークスペースの最近の変化とフォローが必要なことをまとめ、今日最初にやることを挙げます。',
'recommend.dailyBrief.schedule': '平日 9:00',
'recommend.dailyBrief.prompt': '「デイリーブリーフィング」という名前の自動化タスクを作成してください。平日は毎日 9:00 に、現在のワークスペースの過去24時間の変化を確認し、私がフォローすべきことと今日最初にやることを挙げてください。ワークスペースがコードリポジトリの場合は、新しいコミット、私のレビュー待ちのプルリクエスト、失敗した CI も確認してください。',
'recommend.issueScan.title': 'Issue スキャン',
'recommend.issueScan.description': '新しい Issue をバグ・要望・質問に分類し、重複しているものと返信が必要なものを指摘します。',
'recommend.issueScan.schedule': '平日 10:00',
'recommend.issueScan.prompt': '「Issue スキャン」という名前の自動化タスクを作成してください。平日は毎日 10:00 に、現在のワークスペースのリポジトリで新しい Issue をスキャンし、バグ・要望・質問に分類して、重複しているものと私の返信が必要なものを指摘してください。まとめはここでだけ行い、GitHub では返信しないでください。',
'recommend.pluginCompat.title': 'プラグイン互換性チェック',
'recommend.pluginCompat.description': 'DSH の新しいバージョンが出たら、インストール済みのプラグインや自作のプラグインに変更が必要か確認します。',
'recommend.pluginCompat.schedule': '毎日 10:00',
'recommend.pluginCompat.prompt': '「プラグイン互換性チェック」という名前の自動化タスクを作成してください。毎日 10:00 に DSH の新しいバージョンが出ているか確認し、出ていればそのアップグレードガイドを読んで、私がインストールした非公式プラグインや自作プラグインが影響を受けるかを一つずつ調べ、変更が必要な箇所と変更方法を挙げてください。',
'recommend.topicTracking.title': 'トピックと論文の追跡',
'recommend.topicTracking.description': '選んだトピックのニュースと arXiv の新しい論文を検索し、要点を挙げます。',
'recommend.topicTracking.schedule': '毎日 9:00',
'recommend.topicTracking.prompt': '「トピックと論文の追跡」という名前の自動化タスクを作成してください。毎日 9:00 に、私がフォローしているトピックについて新しい記事と arXiv の新しい論文を検索し、それぞれ要点をいくつか挙げてください。作成する前に、トピック、キーワード、情報源を私に聞いてください。',
'recommend.branchCleanup.title': 'ブランチと worktree の整理',
'recommend.branchCleanup.description': 'プルリクエストがマージまたはクローズされたローカルブランチと worktree を一覧にし、確認後に削除します。',
'recommend.branchCleanup.schedule': '毎週金曜日 17:00',
'recommend.branchCleanup.prompt': '「ブランチと worktree の整理」という名前の自動化タスクを作成してください。毎週金曜日の 17:00 に、現在のワークスペースで、プルリクエストがマージ済みまたはクローズ済みのローカルブランチと worktree を一覧にし、削除は私が確認してから行ってください。',
'recommend.weather.title': '天気とお出かけ',
'recommend.weather.description': '今日と今後3日間の天気を伝え、傘や暖かい服装が必要なときはひと言添えます。',
'recommend.weather.schedule': '毎日 7:30',
'recommend.weather.prompt': '「天気とお出かけ」という名前の自動化タスクを作成してください。毎日 7:30 に、私のいる都市の今日と今後3日間の天気を教えてください。傘を持っていくべきとき、暖かい服装にすべきとき、交通の乱れが予想されるときは、そのことをひと言添えてください。作成する前に、私のいる都市を聞いてください。',
'recommend.workout.title': '1週間の運動プラン',
'recommend.workout.description': '目標と運動できる曜日に合わせて、翌週の運動プランを立てます。',
'recommend.workout.schedule': '毎週日曜日 20:00',
'recommend.workout.prompt': '「1週間の運動プラン」という名前の自動化タスクを作成してください。毎週日曜日の 20:00 に、私の目標と運動できる曜日に合わせて翌週の運動プランを立ててください。実行時には私に質問しないでください。作成する前に、目標、週に何日運動できるか、何曜日が空いているか、どこで運動するかを私に聞いてください。',
}
/** Spanish recommendation copy. */
export const recommendationEs: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'Recomendadas',
'recommend.dailyBrief.title': 'Resumen diario',
'recommend.dailyBrief.description': 'Cambios recientes en el espacio de trabajo y pendientes de seguimiento, con lo primero que hacer hoy.',
'recommend.dailyBrief.schedule': 'De lunes a viernes a las 9:00',
'recommend.dailyBrief.prompt': 'Crea una tarea de automatización llamada «Resumen diario»: de lunes a viernes a las 9:00, revisa los cambios de las últimas 24 horas en el espacio de trabajo actual y enumera lo que requiere mi seguimiento y lo primero que debo hacer hoy; si el espacio de trabajo es un repositorio de código, incluye también los commits nuevos, los pull requests pendientes de mi revisión y los fallos de CI.',
'recommend.issueScan.title': 'Revisión de issues',
'recommend.issueScan.description': 'Clasifica los issues nuevos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan respuesta.',
'recommend.issueScan.schedule': 'De lunes a viernes a las 10:00',
'recommend.issueScan.prompt': 'Crea una tarea de automatización llamada «Revisión de issues»: de lunes a viernes a las 10:00, revisa los issues nuevos del repositorio del espacio de trabajo actual, clasifícalos en bugs, solicitudes y preguntas, y señala los duplicados y los que necesitan mi respuesta. Haz el resumen solo aquí; no respondas en GitHub.',
'recommend.pluginCompat.title': 'Compatibilidad de complementos',
'recommend.pluginCompat.description': 'Cuando sale una nueva versión de DSH, comprueba si los complementos instalados y los que has creado necesitan cambios.',
'recommend.pluginCompat.schedule': 'Diariamente a las 10:00',
'recommend.pluginCompat.prompt': 'Crea una tarea de automatización llamada «Compatibilidad de complementos»: todos los días a las 10:00, comprueba si hay una nueva versión de DSH; si la hay, lee su guía de actualización, revisa uno por uno si los complementos no oficiales o creados por mí que tengo instalados se ven afectados, y enumera qué hay que cambiar y cómo.',
'recommend.topicTracking.title': 'Seguimiento de temas y artículos',
'recommend.topicTracking.description': 'Busca noticias y artículos nuevos de arXiv sobre los temas elegidos y enumera los puntos clave.',
'recommend.topicTracking.schedule': 'Diariamente a las 9:00',
'recommend.topicTracking.prompt': 'Crea una tarea de automatización llamada «Seguimiento de temas y artículos»: todos los días a las 9:00, busca noticias y artículos nuevos de arXiv sobre los temas que sigo y enumera algunos puntos clave de cada uno. Antes de crearla, pregúntame por los temas, las palabras clave y las fuentes.',
'recommend.branchCleanup.title': 'Limpieza de ramas y worktrees',
'recommend.branchCleanup.description': 'Enumera las ramas locales y los worktrees cuyos pull requests se fusionaron o cerraron, y los elimina previa confirmación.',
'recommend.branchCleanup.schedule': 'Los viernes a las 17:00',
'recommend.branchCleanup.prompt': 'Crea una tarea de automatización llamada «Limpieza de ramas y worktrees»: todos los viernes a las 17:00, enumera las ramas locales y los worktrees del espacio de trabajo actual cuyos pull requests están fusionados o cerrados, y elimínalos solo después de que yo lo confirme.',
'recommend.weather.title': 'Clima y desplazamientos',
'recommend.weather.description': 'El clima de hoy y de los próximos tres días, con un aviso cuando haga falta paraguas o más abrigo.',
'recommend.weather.schedule': 'Diariamente a las 7:30',
'recommend.weather.prompt': 'Crea una tarea de automatización llamada «Clima y desplazamientos»: todos los días a las 7:30, dime el clima de mi ciudad para hoy y los próximos tres días, y avísame cuando deba llevar paraguas, abrigarme más o esperar problemas en los desplazamientos. Antes de crearla, pregúntame cuál es mi ciudad.',
'recommend.workout.title': 'Plan de entrenamiento semanal',
'recommend.workout.description': 'Planifica los entrenamientos de la próxima semana según tus objetivos y tus días de entrenamiento.',
'recommend.workout.schedule': 'Los domingos a las 20:00',
'recommend.workout.prompt': 'Crea una tarea de automatización llamada «Plan de entrenamiento semanal»: todos los domingos a las 20:00, planifica mis entrenamientos de la próxima semana según mis objetivos y los días en que puedo entrenar, sin preguntarme nada cuando se ejecute. Antes de crearla, pregúntame por mis objetivos, cuántos días a la semana puedo entrenar, qué días tengo libres y dónde entreno.',
}
/** French recommendation copy. */
export const recommendationFr: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'Recommandées',
'recommend.dailyBrief.title': 'Résumé quotidien',
'recommend.dailyBrief.description': 'Changements récents dans l\'espace de travail et points à suivre, avec les priorités du jour.',
'recommend.dailyBrief.schedule': 'Du lundi au vendredi à 9:00',
'recommend.dailyBrief.prompt': 'Crée une tâche d\'automatisation nommée « Résumé quotidien » : du lundi au vendredi à 9:00, passe en revue les changements des dernières 24 heures dans l\'espace de travail actuel et liste ce qui demande mon suivi et ce que je dois faire en premier aujourd\'hui ; si l\'espace de travail est un dépôt de code, couvre aussi les nouveaux commits, les pull requests en attente de ma revue et les échecs de CI.',
'recommend.issueScan.title': 'Analyse des issues',
'recommend.issueScan.description': 'Trie les nouvelles issues en bugs, demandes et questions, et signale les doublons et celles qui nécessitent une réponse.',
'recommend.issueScan.schedule': 'Du lundi au vendredi à 10:00',
'recommend.issueScan.prompt': 'Crée une tâche d\'automatisation nommée « Analyse des issues » : du lundi au vendredi à 10:00, analyse les nouvelles issues du dépôt de l\'espace de travail actuel, trie-les en bugs, demandes et questions, et signale les doublons et celles qui nécessitent ma réponse. Fais le résumé ici uniquement ; ne réponds pas sur GitHub.',
'recommend.pluginCompat.title': 'Compatibilité des plugins',
'recommend.pluginCompat.description': 'Quand une nouvelle version de DSH sort, vérifie si les plugins installés et ceux faits maison doivent être modifiés.',
'recommend.pluginCompat.schedule': 'Tous les jours à 10:00',
'recommend.pluginCompat.prompt': 'Crée une tâche d\'automatisation nommée « Compatibilité des plugins » : tous les jours à 10:00, vérifie si une nouvelle version de DSH est disponible ; si oui, lis son guide de mise à niveau, examine pour chaque plugin non officiel ou fait maison que j\'ai installé s\'il est concerné, et liste ce qu\'il faut modifier et comment.',
'recommend.topicTracking.title': 'Suivi de sujets et d\'articles',
'recommend.topicTracking.description': 'Recherche les actualités et les nouveaux articles arXiv sur les sujets choisis, et liste les points clés.',
'recommend.topicTracking.schedule': 'Tous les jours à 9:00',
'recommend.topicTracking.prompt': 'Crée une tâche d\'automatisation nommée « Suivi de sujets et d\'articles » : tous les jours à 9:00, recherche les actualités et les nouveaux articles arXiv sur les sujets que je suis, et liste quelques points clés pour chacun. Avant de la créer, demande-moi les sujets, les mots-clés et les sources.',
'recommend.branchCleanup.title': 'Nettoyage des branches et worktrees',
'recommend.branchCleanup.description': 'Liste les branches et worktrees locaux dont les pull requests sont fusionnées ou fermées, et les supprime après confirmation.',
'recommend.branchCleanup.schedule': 'Le vendredi à 17:00',
'recommend.branchCleanup.prompt': 'Crée une tâche d\'automatisation nommée « Nettoyage des branches et worktrees » : tous les vendredis à 17:00, liste les branches locales et les worktrees de l\'espace de travail actuel dont les pull requests sont fusionnées ou fermées, et ne les supprime qu\'après ma confirmation.',
'recommend.weather.title': 'Météo et déplacements',
'recommend.weather.description': 'Météo du jour et des trois prochains jours, avec un rappel s\'il faut un parapluie ou des vêtements plus chauds.',
'recommend.weather.schedule': 'Tous les jours à 7:30',
'recommend.weather.prompt': 'Crée une tâche d\'automatisation nommée « Météo et déplacements » : tous les jours à 7:30, donne-moi la météo de ma ville pour aujourd\'hui et les trois prochains jours, et préviens-moi quand je dois prendre un parapluie, me couvrir davantage ou m\'attendre à des perturbations dans les transports. Avant de la créer, demande-moi ma ville.',
'recommend.workout.title': 'Plan d\'entraînement hebdomadaire',
'recommend.workout.description': 'Planifie les entraînements de la semaine prochaine selon tes objectifs et tes jours d\'entraînement.',
'recommend.workout.schedule': 'Le dimanche à 20:00',
'recommend.workout.prompt': 'Crée une tâche d\'automatisation nommée « Plan d\'entraînement hebdomadaire » : tous les dimanches à 20:00, planifie mes entraînements de la semaine suivante en fonction de mes objectifs et des jours où je peux m\'entraîner, sans me poser de question pendant l\'exécution. Avant de la créer, demande-moi mes objectifs, combien de jours par semaine je peux m\'entraîner, quels jours je suis libre et où je m\'entraîne.',
}
/** German recommendation copy. */
export const recommendationDe: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'Empfohlen',
'recommend.dailyBrief.title': 'Tagesüberblick',
'recommend.dailyBrief.description': 'Aktuelle Änderungen im Arbeitsbereich und offene Punkte, dazu, was heute zuerst ansteht.',
'recommend.dailyBrief.schedule': 'Mo–Fr um 9:00',
'recommend.dailyBrief.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Tagesüberblick“: Prüfe montags bis freitags um 9:00 Uhr die Änderungen der letzten 24 Stunden im aktuellen Arbeitsbereich und liste auf, was ich nachverfolgen muss und was heute zuerst ansteht; ist der Arbeitsbereich ein Code-Repository, berücksichtige auch neue Commits, auf mein Review wartende Pull Requests und fehlgeschlagene CI-Läufe.',
'recommend.issueScan.title': 'Issue-Sichtung',
'recommend.issueScan.description': 'Sortiert neue Issues in Bugs, Feature-Wünsche und Fragen und hebt Duplikate sowie Issues hervor, die eine Antwort brauchen.',
'recommend.issueScan.schedule': 'Mo–Fr um 10:00',
'recommend.issueScan.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Issue-Sichtung“: Sichte montags bis freitags um 10:00 Uhr die neuen Issues im Repository des aktuellen Arbeitsbereichs, sortiere sie in Bugs, Feature-Wünsche und Fragen und hebe Duplikate sowie Issues hervor, die meine Antwort brauchen. Fasse alles nur hier zusammen; antworte nicht auf GitHub.',
'recommend.pluginCompat.title': 'Plugin-Kompatibilitätsprüfung',
'recommend.pluginCompat.description': 'Prüft, sobald eine neue DSH-Version erscheint, ob installierte und selbst erstellte Plugins angepasst werden müssen.',
'recommend.pluginCompat.schedule': 'Täglich um 10:00',
'recommend.pluginCompat.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Plugin-Kompatibilitätsprüfung“: Prüfe täglich um 10:00 Uhr, ob eine neue DSH-Version verfügbar ist; falls ja, lies die zugehörige Upgrade-Anleitung, prüfe für jedes nicht offizielle oder selbst erstellte Plugin, das ich installiert habe, ob es betroffen ist, und liste auf, was zu ändern ist und wie.',
'recommend.topicTracking.title': 'Themen- und Paper-Tracking',
'recommend.topicTracking.description': 'Sucht Neuigkeiten und neue arXiv-Paper zu ausgewählten Themen und listet die wichtigsten Punkte auf.',
'recommend.topicTracking.schedule': 'Täglich um 9:00',
'recommend.topicTracking.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Themen- und Paper-Tracking“: Suche täglich um 9:00 Uhr neue Artikel und arXiv-Paper zu den Themen, die ich verfolge, und liste zu jedem ein paar Kernpunkte auf. Frag mich vor dem Erstellen nach den Themen, Stichwörtern und Quellen.',
'recommend.branchCleanup.title': 'Branch- und Worktree-Bereinigung',
'recommend.branchCleanup.description': 'Listet lokale Branches und Worktrees mit gemergten oder geschlossenen Pull Requests auf und löscht sie nach Bestätigung.',
'recommend.branchCleanup.schedule': 'Freitags um 17:00',
'recommend.branchCleanup.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Branch- und Worktree-Bereinigung“: Liste freitags um 17:00 Uhr die lokalen Branches und Worktrees im aktuellen Arbeitsbereich auf, deren Pull Requests gemergt oder geschlossen sind, und lösche sie erst, nachdem ich es bestätigt habe.',
'recommend.weather.title': 'Wetter und Verkehr',
'recommend.weather.description': 'Das Wetter für heute und die nächsten drei Tage, mit Hinweis, wenn ein Schirm oder wärmere Kleidung nötig ist.',
'recommend.weather.schedule': 'Täglich um 7:30',
'recommend.weather.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wetter und Verkehr“: Sag mir täglich um 7:30 Uhr das Wetter in meiner Stadt für heute und die nächsten drei Tage und weise mich darauf hin, wenn ich einen Schirm mitnehmen, mich wärmer anziehen oder mit Verkehrsbehinderungen rechnen sollte. Frag mich vor dem Erstellen nach meiner Stadt.',
'recommend.workout.title': 'Wöchentlicher Trainingsplan',
'recommend.workout.description': 'Plant die Trainingseinheiten der nächsten Woche passend zu deinen Zielen und Trainingstagen.',
'recommend.workout.schedule': 'Sonntags um 20:00',
'recommend.workout.prompt': 'Erstelle eine Automatisierungsaufgabe namens „Wöchentlicher Trainingsplan“: Plane sonntags um 20:00 Uhr meine Trainingseinheiten für die nächste Woche passend zu meinen Zielen und den Tagen, an denen ich trainieren kann, ohne mich bei der Ausführung etwas zu fragen. Frag mich vor dem Erstellen nach meinen Zielen, wie viele Tage pro Woche ich trainieren kann, an welchen Tagen ich frei bin und wo ich trainiere.',
}
/** Russian recommendation copy. */
export const recommendationRu: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'Рекомендуемые',
'recommend.dailyBrief.title': 'Ежедневная сводка',
'recommend.dailyBrief.description': 'Недавние изменения в рабочей области и то, что требует внимания, а также первоочередные дела на сегодня.',
'recommend.dailyBrief.schedule': 'По будням в 9:00',
'recommend.dailyBrief.prompt': 'Создай задачу автоматизации под названием «Ежедневная сводка»: по будням в 9:00 просматривай изменения в текущей рабочей области за последние 24 часа и перечисляй, что требует моего внимания и с чего начать сегодня; если рабочая область — репозиторий кода, учитывай также новые коммиты, пул-реквесты, ожидающие моего ревью, и сбои CI.',
'recommend.issueScan.title': 'Обзор issues',
'recommend.issueScan.description': 'Делит новые issues на баги, пожелания и вопросы и выделяет дубликаты и те, на которые нужно ответить.',
'recommend.issueScan.schedule': 'По будням в 10:00',
'recommend.issueScan.prompt': 'Создай задачу автоматизации под названием «Обзор issues»: по будням в 10:00 просматривай новые issues в репозитории текущего рабочего пространства, дели их на баги, пожелания и вопросы и выделяй дубликаты и те, на которые нужен мой ответ. Сводку пиши только здесь; на GitHub не отвечай.',
'recommend.pluginCompat.title': 'Проверка совместимости плагинов',
'recommend.pluginCompat.description': 'При выходе новой версии DSH проверяет, нужно ли изменить установленные и созданные вами плагины.',
'recommend.pluginCompat.schedule': 'Ежедневно в 10:00',
'recommend.pluginCompat.prompt': 'Создай задачу автоматизации под названием «Проверка совместимости плагинов»: ежедневно в 10:00 проверяй, вышла ли новая версия DSH; если да, прочитай её руководство по обновлению, выясни, затронут ли каждый установленный у меня неофициальный или созданный мной плагин, и перечисли, что и как нужно изменить.',
'recommend.topicTracking.title': 'Отслеживание тем и статей',
'recommend.topicTracking.description': 'Ищет новости и новые статьи на arXiv по выбранным темам и перечисляет ключевые моменты.',
'recommend.topicTracking.schedule': 'Ежедневно в 9:00',
'recommend.topicTracking.prompt': 'Создай задачу автоматизации под названием «Отслеживание тем и статей»: ежедневно в 9:00 ищи новости и новые статьи на arXiv по темам, за которыми я слежу, и перечисляй по каждой несколько ключевых моментов. Перед созданием спроси у меня темы, ключевые слова и источники.',
'recommend.branchCleanup.title': 'Очистка веток и worktrees',
'recommend.branchCleanup.description': 'Перечисляет локальные ветки и worktrees, чьи пул-реквесты слиты или закрыты, и удаляет их после подтверждения.',
'recommend.branchCleanup.schedule': 'По пятницам в 17:00',
'recommend.branchCleanup.prompt': 'Создай задачу автоматизации под названием «Очистка веток и worktrees»: по пятницам в 17:00 перечисляй локальные ветки и worktrees в текущем рабочем пространстве, чьи пул-реквесты слиты или закрыты, и удаляй их только после моего подтверждения.',
'recommend.weather.title': 'Погода и поездки',
'recommend.weather.description': 'Погода на сегодня и ближайшие три дня, с пометкой, когда нужен зонт или одежда потеплее.',
'recommend.weather.schedule': 'Ежедневно в 7:30',
'recommend.weather.prompt': 'Создай задачу автоматизации под названием «Погода и поездки»: ежедневно в 7:30 сообщай мне погоду в моём городе на сегодня и ближайшие три дня и отдельно предупреждай, если стоит взять зонт, одеться теплее или ожидать проблем с транспортом. Перед созданием спроси у меня, в каком я городе.',
'recommend.workout.title': 'План тренировок на неделю',
'recommend.workout.description': 'Составляет план тренировок на следующую неделю с учётом целей и дней для тренировок.',
'recommend.workout.schedule': 'По воскресеньям в 20:00',
'recommend.workout.prompt': 'Создай задачу автоматизации под названием «План тренировок на неделю»: по воскресеньям в 20:00 составляй мне план тренировок на следующую неделю с учётом моих целей и дней, когда я могу тренироваться, ничего не спрашивая у меня во время запуска. Перед созданием спроси у меня о целях, сколько дней в неделю я могу тренироваться, в какие дни я свободен и где тренируюсь.',
}
/** Portuguese recommendation copy. */
export const recommendationPt: Record<keyof typeof recommendationEn, string> = {
'recommend.heading': 'Recomendadas',
'recommend.dailyBrief.title': 'Resumo diário',
'recommend.dailyBrief.description': 'Mudanças recentes no espaço de trabalho e o que precisa de acompanhamento, com o que fazer primeiro hoje.',
'recommend.dailyBrief.schedule': 'Segunda a sexta às 9:00',
'recommend.dailyBrief.prompt': 'Crie uma tarefa de automação chamada “Resumo diário”: de segunda a sexta às 9:00, revise as mudanças das últimas 24 horas no espaço de trabalho atual e liste o que precisa do meu acompanhamento e o que fazer primeiro hoje; se o espaço de trabalho for um repositório de código, inclua também os novos commits, os pull requests aguardando minha revisão e as falhas de CI.',
'recommend.issueScan.title': 'Varredura de issues',
'recommend.issueScan.description': 'Classifica as novas issues em bugs, solicitações e perguntas e destaca as duplicadas e as que precisam de resposta.',
'recommend.issueScan.schedule': 'Segunda a sexta às 10:00',
'recommend.issueScan.prompt': 'Crie uma tarefa de automação chamada “Varredura de issues”: de segunda a sexta às 10:00, faça uma varredura nas novas issues do repositório do espaço de trabalho atual, classifique-as em bugs, solicitações e perguntas e destaque as duplicadas e as que precisam da minha resposta. Faça o resumo só aqui; não responda no GitHub.',
'recommend.pluginCompat.title': 'Compatibilidade de plug-ins',
'recommend.pluginCompat.description': 'Quando sai uma nova versão do DSH, verifica se os plug-ins instalados e os criados por você precisam de ajustes.',
'recommend.pluginCompat.schedule': 'Diariamente às 10:00',
'recommend.pluginCompat.prompt': 'Crie uma tarefa de automação chamada “Compatibilidade de plug-ins”: todos os dias às 10:00, verifique se há uma nova versão do DSH; se houver, leia o guia de atualização dessa versão, confira um a um se os plug-ins não oficiais ou criados por mim que tenho instalados são afetados e liste o que mudar e como.',
'recommend.topicTracking.title': 'Acompanhamento de temas e artigos',
'recommend.topicTracking.description': 'Busca notícias e novos artigos do arXiv sobre os temas escolhidos e lista os pontos principais.',
'recommend.topicTracking.schedule': 'Diariamente às 9:00',
'recommend.topicTracking.prompt': 'Crie uma tarefa de automação chamada “Acompanhamento de temas e artigos”: todos os dias às 9:00, busque notícias e novos artigos do arXiv sobre os temas que eu acompanho e liste alguns pontos principais de cada um. Antes de criá-la, me pergunte quais são os temas, as palavras-chave e as fontes.',
'recommend.branchCleanup.title': 'Limpeza de branches e worktrees',
'recommend.branchCleanup.description': 'Lista as branches locais e os worktrees cujos pull requests foram mesclados ou fechados e os exclui após confirmação.',
'recommend.branchCleanup.schedule': 'Sextas às 17:00',
'recommend.branchCleanup.prompt': 'Crie uma tarefa de automação chamada “Limpeza de branches e worktrees”: toda sexta-feira às 17:00, liste as branches locais e os worktrees do espaço de trabalho atual cujos pull requests foram mesclados ou fechados, e exclua-os só depois que eu confirmar.',
'recommend.weather.title': 'Clima e deslocamentos',
'recommend.weather.description': 'O clima de hoje e dos próximos três dias, com um aviso quando for preciso guarda-chuva ou mais agasalho.',
'recommend.weather.schedule': 'Diariamente às 7:30',
'recommend.weather.prompt': 'Crie uma tarefa de automação chamada “Clima e deslocamentos”: todos os dias às 7:30, me diga o clima da minha cidade para hoje e os próximos três dias e avise quando eu precisar levar guarda-chuva, me agasalhar mais ou me preparar para problemas nos deslocamentos. Antes de criá-la, me pergunte qual é a minha cidade.',
'recommend.workout.title': 'Plano de treino semanal',
'recommend.workout.description': 'Planeja os treinos da próxima semana de acordo com seus objetivos e dias de treino.',
'recommend.workout.schedule': 'Domingos às 20:00',
'recommend.workout.prompt': 'Crie uma tarefa de automação chamada “Plano de treino semanal”: todo domingo às 20:00, planeje meus treinos da próxima semana de acordo com meus objetivos e os dias em que posso treinar, sem me perguntar nada durante a execução. Antes de criá-la, me pergunte quais são meus objetivos, quantos dias por semana posso treinar, quais dias tenho livres e onde treino.',
}
@@ -1,4 +1,8 @@
/** Copy for the retained-reminder task manager's `schedule.manager` namespace. */
import {
recommendationDe, recommendationEn, recommendationEs, recommendationFr, recommendationJa, recommendationPt, recommendationRu,
recommendationZh,
} from './recommendation-locales.ts'
import { frequencyEn, frequencyJa, frequencyEs, frequencyFr, frequencyDe, frequencyRu, frequencyPt, frequencyZh } from './frequency-locales.ts'
/** English task-manager dictionary and key domain. */
@@ -102,6 +106,7 @@ export const en = {
'frequency.once': 'Once',
'frequency.every': 'Every {value} {unit}',
...frequencyEn,
...recommendationEn,
'timing.date': 'Date',
'timing.time': 'Time',
'timing.hour': 'Hour',
@@ -268,6 +273,7 @@ export const zh: Record<TaskManagerKey, string> = {
'frequency.once': '仅一次',
'frequency.every': '每 {value} {unit}',
...frequencyZh,
...recommendationZh,
'timing.date': '日期',
'timing.time': '时间',
'timing.hour': '时',
@@ -331,6 +337,7 @@ export const zh: Record<TaskManagerKey, string> = {
/** Japanese copy, checked against the English keys. */
export const ja = {
...frequencyJa,
...recommendationJa,
'host.create': '作成',
'host.createMethod': '作成方法を選択',
'host.chatCreate': '会話で作成',
@@ -544,6 +551,7 @@ export const es = {
'frequency.once': 'una vez',
'frequency.every': 'Cada {value} {unit}',
...frequencyEs,
...recommendationEs,
'timing.date': 'Fecha',
'timing.time': 'tiempo',
'timing.hour': 'Hora',
@@ -705,6 +713,7 @@ export const fr = {
'frequency.once': 'Une fois',
'frequency.every': 'Chaque {value} {unit}',
...frequencyFr,
...recommendationFr,
'timing.date': 'Date',
'timing.time': 'Temps',
'timing.hour': 'Heure',
@@ -866,6 +875,7 @@ export const de = {
'frequency.once': 'Einmal',
'frequency.every': 'Jeder {value} {unit}',
...frequencyDe,
...recommendationDe,
'timing.date': 'Datum',
'timing.time': 'Zeit',
'timing.hour': 'Stunde',
@@ -1027,6 +1037,7 @@ export const ru = {
'frequency.once': 'Однажды',
'frequency.every': 'Каждый {value} {unit}',
...frequencyRu,
...recommendationRu,
'timing.date': 'Дата',
'timing.time': 'Время',
'timing.hour': 'Час',
@@ -1188,6 +1199,7 @@ export const pt = {
'frequency.once': 'Uma vez',
'frequency.every': 'A cada {value} {unit}',
...frequencyPt,
...recommendationPt,
'timing.date': 'Data',
'timing.time': 'Hora',
'timing.hour': 'Hora',
@@ -443,6 +443,53 @@ describe('ui-schedule browser half', () => {
}
})
it('starts each recommendation in a new conversation with its single-line request in every language', async () => {
const sidebar = sidebarStubs()
const ctx = await baseContext(undefined, sidebar)
const owner = ctx.slots.register({
name: 'root',
children: {
'sidebar.right.pane.tab': { kind: 'keyed', scope: 'session' },
'sidebar.right.pane.tab.title': { kind: 'keyed', scope: 'session' },
main: { kind: 'keyed', scope: 'root' },
},
} as never, Empty)
const startSession = vi.spyOn(ctx.uiWorkspace, 'startSession')
const fiber = ctx.plugin({ inject: [...inject], apply })
await fiber.await()
try {
const panel = injectedFace(ctx.slots.entries('main')[0]!, undefined as never) as TaskManagerInjected
for (const dictionary of Object.values(managerLocales)) {
const prompts = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.prompt'))
expect(prompts).toHaveLength(7)
for (const [, prompt] of prompts) {
expect(prompt).not.toContain('\n')
panel.onUseRecommendation(prompt)
expect(startSession).toHaveBeenLastCalledWith(undefined, { prompt, whenDraftExists: 'append' })
}
}
expect(startSession).toHaveBeenCalledTimes(56)
} finally {
await fiber.dispose()
owner()
await ctx.fiber.dispose()
}
})
it('states each recommendation\'s shown run time in its request in every language', () => {
for (const dictionary of Object.values(managerLocales)) {
const schedules = Object.entries(dictionary).filter(([key]) => key.startsWith('recommend.') && key.endsWith('.schedule'))
expect(schedules).toHaveLength(7)
for (const [key, schedule] of schedules) {
const times = schedule.match(/\d{1,2}:\d{2}/g)
expect(times).toHaveLength(1)
// A digit boundary keeps 0:00 from matching inside 20:00.
expect(dictionary[key.replace(/schedule$/, 'prompt') as keyof typeof dictionary])
.toMatch(new RegExp(`(?<!\\d)${times![0]}(?!\\d)`))
}
}
})
it('opens the task tab with the entry Session and the chosen task id', async () => {
const sidebar = sidebarStubs()
const ctx = await baseContext(undefined, sidebar)
@@ -67,7 +67,7 @@ function mount(rows: readonly ScheduleCatalogEntry[] = [task], overrides: Partia
useSessionStatus: select => select(new Map()), useSessionRetainInfo: () => undefined,
useResource: () => { throw new Error('Task editor loads no document resources') },
useContextMenu: contextMenuHook(),
onNewTask: vi.fn(), onClearEnded: vi.fn(async () => {}),
onNewTask: vi.fn(), onUseRecommendation: vi.fn(), onClearEnded: vi.fn(async () => {}),
onCreateTask: vi.fn<TaskManagerPageProps['onCreateTask']>(async () => ({ created: task })),
onDelete: vi.fn<TaskManagerPageProps['onDelete']>(async () => 'deleted'), onRetry: vi.fn(async () => {}), onOpenSession: vi.fn(),
hostActions: hostActions(),
@@ -172,6 +172,7 @@ function mount(
onDelete: vi.fn<TaskManagerPageProps['onDelete']>(async () => 'deleted'),
onRetry: vi.fn(async () => {}),
onNewTask: vi.fn(),
onUseRecommendation: vi.fn(),
onClearEnded: vi.fn(async () => {}),
onCreateTask: vi.fn<TaskManagerPageProps['onCreateTask']>(async () => ({ created: at })),
onOpenSession: vi.fn(),
@@ -839,6 +840,70 @@ describe('Task manager catalog', () => {
expect(emptyNewTaskButton().textContent).toBe(en['empty.action'])
})
const RECOMMENDATION_IDS = ['dailyBrief', 'issueScan', 'pluginCompat', 'topicTracking', 'branchCleanup',
'weather', 'workout'] as const
function recommendations(dictionary: Dictionary = en): HTMLElement | null {
return screen.queryByRole('region', { name: dictionary['recommend.heading'] })
}
it('lists the built-in recommendations under the empty Enabled view and prefills each request', () => {
const h = mount({ records: [] }, en, {}, { startAtAll: false })
const buttons = within(recommendations()!).getAllByRole('button')
expect(buttons.map(button => button.getAttribute('aria-label')))
.toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`]))
for (const [index, id] of RECOMMENDATION_IDS.entries()) {
const button = buttons[index]!
// The description and the run time are separate references, so a screen reader pauses between them.
expect(button.getAttribute('aria-describedby')!.split(' ').map(ref => document.getElementById(ref)?.textContent))
.toEqual([en[`recommend.${id}.description`], en[`recommend.${id}.schedule`]])
expect(button.querySelectorAll('svg[aria-hidden="true"]')).toHaveLength(3)
fireEvent.click(button)
expect(h.props.onUseRecommendation).toHaveBeenLastCalledWith(en[`recommend.${id}.prompt`])
}
expect(h.props.onUseRecommendation).toHaveBeenCalledTimes(RECOMMENDATION_IDS.length)
expect(h.props.onNewTask).not.toHaveBeenCalled()
expect(emptyNewTaskButton().textContent).toBe(en['empty.action'])
})
it('shows the recommendations under the empty All view in the active language', () => {
mount({ records: [] }, zh)
const section = recommendations(zh)!
expect(within(section).getByRole('button', { name: zh['recommend.weather.title'] })).toBeDefined()
expect(section.textContent).toContain(zh['recommend.weather.schedule'])
})
it.each([
['paused', 'list.emptyPaused'],
['ended', 'list.emptyInactive'],
] as const)('omits the recommendations from the empty %s view', (status, title) => {
mount({ records: [] })
const statuses = screen.getByRole('group', { name: en['statusFilter.label'] })
fireEvent.click(within(statuses).getByRole('button', { name: en[`status.${status}`] }))
expect(screen.getByRole('status').textContent).toContain(en[title])
expect(recommendations()).toBeNull()
})
it('omits the recommendations while rows are listed, a search matches nothing, or the catalog loads', () => {
const h = mount({ records })
expect(recommendations()).toBeNull()
fireEvent.change(screen.getByRole('searchbox', { name: en['search.label'] }), { target: { value: 'no such task' } })
expect(screen.getByRole('status').textContent).toContain(en['list.noMatches'])
expect(recommendations()).toBeNull()
h.view.unmount()
mount({ records: [], status: 'loading' })
expect(recommendations()).toBeNull()
})
it('lists every recommendation under the empty Enabled view while paused and ended tasks use their titles', () => {
mount({ records: [
{ ...paused, title: en['recommend.dailyBrief.title'] },
{ ...ended, title: en['recommend.weather.title'] },
] }, en, {}, { startAtAll: false })
expect(within(recommendations()!).getAllByRole('button').map(button => button.getAttribute('aria-label')))
.toEqual(RECOMMENDATION_IDS.map(id => en[`recommend.${id}.title`]))
})
it('distinguishes an empty catalog, loading, and a failed read', () => {
const h = mount({ records: [], status: 'loading' })
expect(screen.getByRole('status', { name: en['list.loading'] }).textContent).toBe('')