diff --git a/changelog.d/3114-scheduled-task-time-zone.added.md b/changelog.d/3114-scheduled-task-time-zone.added.md new file mode 100644 index 000000000..27c7e4b23 --- /dev/null +++ b/changelog.d/3114-scheduled-task-time-zone.added.md @@ -0,0 +1 @@ +A scheduled task's form now names the time zone its rule runs in: "Every day at 09:00" carries the zone it was saved with instead of silently meaning this device's zone, a Once task's date and time are read in that zone, and the row and the edit form name the same one ([#3114](https://github.com/ThinkFlowLab/FlyBot/issues/3114)). diff --git a/core/client.js b/core/client.js index f5f7dc0f5..ff49f69e9 100644 --- a/core/client.js +++ b/core/client.js @@ -1258,6 +1258,7 @@ var ZH = { "What for": "用途", Activity: "活跃度", "Time range": "时间范围", + "Time zone": "时区", "All usage": "全部用量", "Group usage by": "用量分组", "By Bot": "按 Bot", @@ -3943,6 +3944,59 @@ function useSchedules(actions) { } var schedulesReadFailure = (failure) => typeof failure === "string" && failure !== "" ? t("The scheduled tasks could not be read: {reason}", { reason: failure }) : null; var localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone; +function timeZoneOptions(current) { + const supported = typeof Intl.supportedValuesOf === "function" ? Intl.supportedValuesOf("timeZone") : []; + const zone = String(current ?? "").trim(); + const list = supported.length > 0 ? ["UTC", ...supported] : ["UTC", "Asia/Shanghai"]; + if (zone !== "") list.unshift(zone); + return [...new Set(list.filter(Boolean))]; +} +function zoneParts(ms, timeZone) { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: timeZone || "UTC", + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit" + }).formatToParts(new Date(ms)); + const value = (type) => Number(parts.find((part) => part.type === type)?.value); + return Date.UTC(value("year"), value("month") - 1, value("day"), value("hour"), value("minute"), value("second")); +} +function wallClockInput(ms, timeZone) { + const at = Number(ms); + if (!Number.isFinite(at)) return ""; + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: String(timeZone ?? "").trim() || localZone(), + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" + }).formatToParts(new Date(at)); + const value = (type) => parts.find((part) => part.type === type)?.value; + return value("year") ? `${value("year")}-${value("month")}-${value("day")}T${value("hour")}:${value("minute")}` : ""; +} +function instantFromWallClock(wall, timeZone) { + const match = String(wall ?? "").match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/); + if (!match) throw new Error("Pick a date and time"); + const asUtc = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] ?? 0)); + const zone = String(timeZone ?? "").trim() || "UTC"; + let instant2 = asUtc; + for (let pass = 0; pass < 3; pass += 1) { + const shown = zoneParts(instant2, zone); + if (shown === asUtc) break; + instant2 -= shown - asUtc; + } + if (zoneParts(instant2, zone) === asUtc) return new Date(instant2).toISOString(); + for (const probe of [instant2 - 36e5, instant2 + 36e5, instant2 - 72e5, instant2 + 72e5]) { + if (zoneParts(probe, zone) === asUtc) return new Date(probe).toISOString(); + } + throw new Error("Pick a date and time"); +} var clock2 = (time) => String(time ?? "").slice(0, 5); var when = (ms, options) => new Intl.DateTimeFormat(dateLocale(), options).format(ms); function dayAndTime(ms) { @@ -4117,10 +4171,6 @@ function inAnHour() { } var KINDS = [["at", "Once"], ["daily", "Every day"], ["weekly", "Every week"], ["every", "Repeat"]]; var UNITS = [["seconds", 1, "second", "seconds"], ["minutes", 60, "minute", "minutes"], ["hours", 3600, "hour", "hours"], ["days", 86400, "day", "days"]]; -function localInput(ms) { - const date = new Date(ms); - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`; -} function formStart(task) { const seconds = task?.kind === "every" ? Number(task.everySeconds) : 3600; const [unit, size] = seconds % 86400 === 0 ? ["days", 86400] : seconds % 3600 === 0 ? ["hours", 3600] : seconds % 60 === 0 ? ["minutes", 60] : ["seconds", 1]; @@ -4129,7 +4179,7 @@ function formStart(task) { title: task?.title ?? "", prompt: task?.prompt ?? "", kind: once ? "at" : task?.kind ?? "daily", - at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? localInput(Date.parse(task.scheduledAt)) : inAnHour(), + at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? wallClockInput(Date.parse(task.scheduledAt), task?.timeZone || localZone()) : inAnHour(), time: task?.time ? clock2(task.time) : "09:00", weekdays: task?.kind === "weekly" && Array.isArray(task.weekdays) ? task.weekdays : [1, 2, 3, 4, 5], count: Math.max(1, Math.round(seconds / size)), @@ -4137,6 +4187,13 @@ function formStart(task) { timeZone: task?.timeZone || localZone() }; } +function whenFromForm({ kind, at, time, weekdays, timeZone, count, unit } = {}) { + const zone = String(timeZone ?? "").trim() || localZone(); + if (kind === "cron") return { kind: "keep" }; + if (kind === "at") return { kind, at: instantFromWallClock(at, zone), timeZone: zone }; + if (kind === "every") return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) }; + return { kind, time, timeZone: zone, ...kind === "weekly" ? { weekdays } : {} }; +} function TaskForm({ roster, actions, start, task, onDone, onCancel }) { const first = formStart(task); const [target, setTarget] = (0, import_react4.useState)(task ? task.botId ?? task.roomId : start ?? ""); @@ -4148,14 +4205,10 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) { const [weekdays, setWeekdays] = (0, import_react4.useState)(first.weekdays); const [count, setCount] = (0, import_react4.useState)(first.count); const [unit, setUnit] = (0, import_react4.useState)(first.unit); + const [timeZone, setTimeZone] = (0, import_react4.useState)(first.timeZone); const [busy, setBusy] = (0, import_react4.useState)(false); const [error, setError] = (0, import_react4.useState)(""); - const timing = () => { - if (kind === "cron") return { kind: "keep" }; - if (kind === "at") return { kind, at: new Date(at).toISOString(), timeZone: first.timeZone }; - if (kind === "every") return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) }; - return { kind, time, timeZone: first.timeZone, ...kind === "weekly" ? { weekdays } : {} }; - }; + const timing = () => whenFromForm({ kind, at, time, weekdays, timeZone, count, unit }); const submit = (event) => { event.preventDefault(); if (busy || target === "") return; @@ -4234,6 +4287,20 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) { ) : null ) ), + // Which 09:00 this is: only the rules DSH keeps a zone for show it — a repeat interval has + // none, and a cron rule is kept as stored unless the kind changes (#3110). + kind === "at" || kind === "daily" || kind === "weekly" ? (0, import_react4.createElement)( + "label", + { className: "bt-set-row bt-bs-row" }, + (0, import_react4.createElement)("span", { className: "bt-set-copy" }, (0, import_react4.createElement)("span", { className: "bt-bs-label" }, t("Time zone"))), + (0, import_react4.createElement)("select", { + className: "bt-select bt-task-timezone", + "data-flybot": "task-timezone", + value: timeZone, + "aria-label": t("Time zone"), + onChange: (event) => setTimeZone(event.target.value) + }, timeZoneOptions(timeZone).map((zone) => (0, import_react4.createElement)("option", { key: zone, value: zone }, zone))) + ) : null, error ? (0, import_react4.createElement)("div", { className: "bt-set-row" }, (0, import_react4.createElement)("span", { className: "bt-danger bt-set-hint", role: "alert" }, error)) : null, (0, import_react4.createElement)( "div", diff --git a/core/src/client/i18n.js b/core/src/client/i18n.js index 22bf12e40..2cd30355d 100644 --- a/core/src/client/i18n.js +++ b/core/src/client/i18n.js @@ -1212,6 +1212,7 @@ const ZH = { 'What for': '用途', Activity: '活跃度', 'Time range': '时间范围', + 'Time zone': '时区', 'All usage': '全部用量', 'Group usage by': '用量分组', 'By Bot': '按 Bot', diff --git a/core/src/client/schedules.js b/core/src/client/schedules.js index e36c4dbc4..3f6ac6a95 100644 --- a/core/src/client/schedules.js +++ b/core/src/client/schedules.js @@ -52,6 +52,63 @@ export const schedulesReadFailure = failure => (typeof failure === 'string' && f : null) const localZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone + +// The form sends an IANA zone with the rules that carry one (#3110). This runtime's own list is +// the choices; a zone already on the task stays listed even when the runtime omits it. +export function timeZoneOptions(current) { + const supported = typeof Intl.supportedValuesOf === 'function' ? Intl.supportedValuesOf('timeZone') : [] + const zone = String(current ?? '').trim() + const list = supported.length > 0 ? ['UTC', ...supported] : ['UTC', 'Asia/Shanghai'] + if (zone !== '') list.unshift(zone) + return [...new Set(list.filter(Boolean))] +} + +// The wall clock a zone shows for an instant, as the parts of a datetime-local value. +function zoneParts(ms, timeZone) { + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: timeZone || 'UTC', hourCycle: 'h23', year: 'numeric', month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', second: '2-digit', + }).formatToParts(new Date(ms)) + const value = type => Number(parts.find(part => part.type === type)?.value) + return Date.UTC(value('year'), value('month') - 1, value('day'), value('hour'), value('minute'), value('second')) +} + +// A stored instant as a datetime-local value in the zone the task keeps (#3110), not this device's. +export function wallClockInput(ms, timeZone) { + const at = Number(ms) + if (!Number.isFinite(at)) return '' + const parts = new Intl.DateTimeFormat('en-US', { + timeZone: String(timeZone ?? '').trim() || localZone(), hourCycle: 'h23', + year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', + }).formatToParts(new Date(at)) + const value = type => parts.find(part => part.type === type)?.value + return value('year') ? `${value('year')}-${value('month')}-${value('day')}T${value('hour')}:${value('minute')}` : '' +} + +// The instant a wall clock names in a zone (#3110). DSH stores the instant; a wall clock the zone +// skips (a DST gap) is refused rather than moved to another hour. +export function instantFromWallClock(wall, timeZone) { + const match = String(wall ?? '').match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?$/) + if (!match) throw new Error('Pick a date and time') + const asUtc = Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]), Number(match[4]), Number(match[5]), Number(match[6] ?? 0)) + const zone = String(timeZone ?? '').trim() || 'UTC' + let instant = asUtc + // Two passes settle the offset: the first guess is read back in the zone, and the difference + // between what it shows and what we meant is the offset to remove. + for (let pass = 0; pass < 3; pass += 1) { + const shown = zoneParts(instant, zone) + if (shown === asUtc) break + instant -= shown - asUtc + } + if (zoneParts(instant, zone) === asUtc) return new Date(instant).toISOString() + // A clock the zone gains (a DST gap) has no instant: refuse it, as the host refuses a time it + // cannot run. + for (const probe of [instant - 3_600_000, instant + 3_600_000, instant - 7_200_000, instant + 7_200_000]) { + if (zoneParts(probe, zone) === asUtc) return new Date(probe).toISOString() + } + throw new Error('Pick a date and time') +} + const clock = time => String(time ?? '').slice(0, 5) const when = (ms, options) => new Intl.DateTimeFormat(dateLocale(), options).format(ms) function dayAndTime(ms) { @@ -221,11 +278,6 @@ const KINDS = [['at', 'Once'], ['daily', 'Every day'], ['weekly', 'Every week'], // The form says one unit with one count ("1 minute"), so each unit carries both words. const UNITS = [['seconds', 1, 'second', 'seconds'], ['minutes', 60, 'minute', 'minutes'], ['hours', 3600, 'hour', 'hours'], ['days', 86400, 'day', 'days']] -// A stored instant as the value of a datetime-local input, in this browser's zone. -function localInput(ms) { - const date = new Date(ms) - return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}` -} // What the form starts with: a new task's defaults, or the edited task's own values. // A cron rule has no control here, so it is kept unless another kind is picked. export function formStart(task) { @@ -236,7 +288,7 @@ export function formStart(task) { title: task?.title ?? '', prompt: task?.prompt ?? '', kind: once ? 'at' : task?.kind ?? 'daily', - at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? localInput(Date.parse(task.scheduledAt)) : inAnHour(), + at: once && !Number.isNaN(Date.parse(task.scheduledAt)) ? wallClockInput(Date.parse(task.scheduledAt), task?.timeZone || localZone()) : inAnHour(), time: task?.time ? clock(task.time) : '09:00', weekdays: task?.kind === 'weekly' && Array.isArray(task.weekdays) ? task.weekdays : [1, 2, 3, 4, 5], count: Math.max(1, Math.round(seconds / size)), @@ -245,6 +297,17 @@ export function formStart(task) { } } +// The form's timing as the host takes it (#3110): the zone the form shows is the one a daily or +// weekly rule carries, and the one a Once task's wall clock is read in. A repeat interval is a +// duration, so it carries no zone at all. +export function whenFromForm({ kind, at, time, weekdays, timeZone, count, unit } = {}) { + const zone = String(timeZone ?? '').trim() || localZone() + if (kind === 'cron') return { kind: 'keep' } + if (kind === 'at') return { kind, at: instantFromWallClock(at, zone), timeZone: zone } + if (kind === 'every') return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) } + return { kind, time, timeZone: zone, ...(kind === 'weekly' ? { weekdays } : {}) } +} + function TaskForm({ roster, actions, start, task, onDone, onCancel }) { // A task goes to a Bot's chat or to a group chat, where it reads as your message. const first = formStart(task) @@ -259,19 +322,10 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) { const [weekdays, setWeekdays] = useState(first.weekdays) const [count, setCount] = useState(first.count) const [unit, setUnit] = useState(first.unit) + const [timeZone, setTimeZone] = useState(first.timeZone) const [busy, setBusy] = useState(false) const [error, setError] = useState('') - const timing = () => { - if (kind === 'cron') return { kind: 'keep' } - // A once task is an instant; the host reads its wall clock in this zone when quiet - // hours are on (#1166). The others carry their zone with the time itself. - if (kind === 'at') return { kind, at: new Date(at).toISOString(), timeZone: first.timeZone } - // Seconds, not minutes: DSH takes any interval of 60s or more, so a 90s repeat must - // survive the form instead of being rounded to two minutes (#1651). - if (kind === 'every') return { kind, seconds: Math.round(Number(count) * UNITS.find(([id]) => id === unit)[1]) } - // An edited task keeps its own time zone; a new one takes this browser's. - return { kind, time, timeZone: first.timeZone, ...(kind === 'weekly' ? { weekdays } : {}) } - } + const timing = () => whenFromForm({ kind, at, time, weekdays, timeZone, count, unit }) const submit = (event) => { event.preventDefault() if (busy || target === '') return @@ -313,6 +367,19 @@ function TaskForm({ roster, actions, start, task, onDone, onCancel }) { h('input', { className: 'bt-input bt-task-count', type: 'number', min: 1, value: count, 'aria-label': t('How many'), onChange: event => setCount(event.target.value) }), h('select', { className: 'bt-select bt-task-unit', value: unit, 'aria-label': t('Unit'), onChange: event => setUnit(event.target.value) }, UNITS.map(([id, , one, many]) => h('option', { key: id, value: id }, t(Number(count) === 1 ? one : many))))) : null)), + // Which 09:00 this is: only the rules DSH keeps a zone for show it — a repeat interval has + // none, and a cron rule is kept as stored unless the kind changes (#3110). + kind === 'at' || kind === 'daily' || kind === 'weekly' + ? h('label', { className: 'bt-set-row bt-bs-row' }, + h('span', { className: 'bt-set-copy' }, h('span', { className: 'bt-bs-label' }, t('Time zone'))), + h('select', { + className: 'bt-select bt-task-timezone', + 'data-flybot': 'task-timezone', + value: timeZone, + 'aria-label': t('Time zone'), + onChange: event => setTimeZone(event.target.value), + }, timeZoneOptions(timeZone).map(zone => h('option', { key: zone, value: zone }, zone)))) + : null, error ? h('div', { className: 'bt-set-row' }, h('span', { className: 'bt-danger bt-set-hint', role: 'alert' }, error)) : null, h('div', { className: 'bt-set-row bt-task-foot' }, h('button', { type: 'button', className: 'bt-soft bt-soft-sm', onClick: onCancel }, t('Cancel')), diff --git a/core/test/schedules-client.test.js b/core/test/schedules-client.test.js index 8498e8bd3..d45a13f2c 100644 --- a/core/test/schedules-client.test.js +++ b/core/test/schedules-client.test.js @@ -791,7 +791,7 @@ test('#2232: Quiet hours and the form announce a refusal, not only print it', as const start = formStart(ACTIVE) seeded.push( { available: true, tasks: [] }, true, null, false, '', '22:00', '07:00', - 'b1', start.title, start.prompt, start.kind, start.at, start.time, start.weekdays, start.count, start.unit, false, sentence, + 'b1', start.title, start.prompt, start.kind, start.at, start.time, start.weekdays, start.count, start.unit, start.timeZone, false, sentence, ) const formShown = render(SchedulesPage({ roster: ROSTER, actions: formActions, start: 'b1' })) const formAlerts = alertsOf(formShown) diff --git a/core/test/schedules-timezone.test.js b/core/test/schedules-timezone.test.js new file mode 100644 index 000000000..45e6d2bb4 --- /dev/null +++ b/core/test/schedules-timezone.test.js @@ -0,0 +1,137 @@ +// #3110: a scheduled task's rule is a wall clock in a zone. The form had no zone control, so +// "Every day at 09:00" always meant this device's zone, and the zone an already stored task keeps +// (the row prints it: `Every day at 09:00 (Asia/Tokyo)`) was invisible in the one place that edits +// it. A Once task is the same problem in the other direction: its `datetime-local` is a wall clock, +// and reading it in the device's zone stores an instant hours away from the zone the form shows. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { fileURLToPath } from 'node:url' +import { runInNewContext } from 'node:vm' +import { build } from 'esbuild' + +// The component tree is built with the same shim `schedules-client.test.js` uses: a hook runtime +// that hands out the states a test seeds, in hook order, and never re-renders. +const { outputFiles } = await build({ + stdin: { + // A star re-export keeps a missing name a runtime `undefined` in one test instead of a build + // failure that would hide which case is red (#2039). + contents: "export * from './src/client/schedules.js'", + resolveDir: fileURLToPath(new URL('..', import.meta.url)), + }, + bundle: true, format: 'cjs', platform: 'browser', write: false, logLevel: 'silent', + external: ['react', 'react-dom', '@deepseek-ai/dsh-client-ui-primitives'], +}) +const h = (type, props, ...children) => ({ type, props: { ...props, children } }) +const OFF = { available: false, tasks: [] } +const seeded = [] +const sets = [] +const react = { createElement: h, Fragment: Symbol('F'), useEffect() {}, useLayoutEffect() {}, useState: v => [seeded.length > 0 ? seeded.shift() : v === null ? OFF : v, next => { sets.push(next) }], useMemo: f => f(), useRef: current => ({ current }), useCallback: f => f, useSyncExternalStore: (_s, get) => get() } +const module = { exports: {} } +runInNewContext(outputFiles[0].text, { + module, exports: module.exports, document: { hidden: false }, navigator: { language: 'en' }, localStorage: { getItem: () => null, setItem() {} }, + requestAnimationFrame: run => run(), + require: (name) => { + if (name === 'react') return react + if (name === 'react-dom') return { createPortal: node => node } + if (name === '@deepseek-ai/dsh-client-ui-primitives') return {} + throw new Error(`Unexpected platform module ${name}`) + }, +}) +const { SchedulesPage, BotSchedules, timingText, formStart, whenFromForm, wallClockInput, instantFromWallClock } = module.exports + +// Every node and string under a tree; an array (what a page returns) is walked too. +const all = (node, out = []) => { + if (Array.isArray(node)) { for (const item of node) all(item, out); return out } + if (typeof node === 'string') out.push(node) + else if (node && typeof node === 'object') { out.push(node); all(node.props?.children, out) } + return out +} +const text = node => all(node).filter(item => typeof item === 'string') +const render = (node) => { + if (Array.isArray(node)) return node.map(render) + if (!node || typeof node !== 'object') return node + if (typeof node.type === 'function') return render(node.type(node.props)) + return { ...node, props: { ...node.props, children: render(node.props?.children) } } +} +const tick = () => new Promise(resolve => setImmediate(resolve)) +const spy = () => { + const log = [] + return { log, closeSettings: () => log.push('closeSettings'), selectPanel: id => log.push(`selectPanel ${id}`), openSettings: () => log.push('openSettings') } +} + +const ACTIVE = { id: 's1', sessionId: 'chat-b1', botId: 'b1', title: 'Briefing', prompt: 'Sum up', kind: 'daily', time: '09:00:00', timeZone: 'Asia/Shanghai', scheduledAt: '2030-01-01T01:00:00.000Z', status: 'active' } +const ROSTER = { bots: [{ id: 'b1', name: 'B' }], rooms: [], byId: {}, roomsById: {} } +// This device's zone: the form's default, and the value the stored task does NOT use. +const device = Intl.DateTimeFormat().resolvedOptions().timeZone +// The one control this cut adds, found the way a reader finds it: a labelled zone selector. +const zoneSelects = tree => all(tree).filter(node => node.type === 'select' && node.props['aria-label'] === 'Time zone') +const optionsOf = select => all(select).filter(node => node.type === 'option') + +// The settings page's states, in the order the shim hands them out: the view, `adding`, `editing`, +// then the Quiet hours card's four, then the create form's own (the shape #1334's test documents). +const openNewTaskForm = (overrides = []) => { + seeded.push({ available: true, tasks: [] }, true, null, false, '', '22:00', '07:00', 'b1', 'Briefing', 'Sum up', ...overrides) + const page = render(SchedulesPage({ roster: ROSTER, actions: spy(), start: null })) + return all(page).find(node => node.type === 'form') +} + +test('#3110: the scheduled-task form draws a Time zone control for a rule that carries one, and none for a repeat interval', () => { + const form = openNewTaskForm() + assert.ok(form, 'the new-task form is open') + const zone = zoneSelects(form)[0] + assert.ok(zone, `the form draws no Time zone control: ${JSON.stringify(text(form))}`) + assert.equal(zone.props['data-flybot'], 'task-timezone', 'the control is addressable as the zone selector') + assert.equal(zone.props.value, device, 'a new task opens in this device\'s zone') + const options = optionsOf(zone) + assert.equal(options[0].props.value, device, 'the opening zone is listed first') + assert.ok(options.length > 5, `the control offers IANA zones, saw ${options.length}`) + // A repeat interval is a duration, not a wall clock: it carries no zone in DSH, so the form + // must not pretend to send one. + const repeat = openNewTaskForm(['every']) + assert.ok(repeat, 'the repeat form is open') + assert.equal(zoneSelects(repeat).length, 0, 'a repeat interval draws no zone control') + assert.equal(zoneSelects(openNewTaskForm(['weekly'])).length, 1, 'a weekly rule keeps the control') +}) + +test('#3110: an edited daily task shows its own zone, saves it, and its row names the same zone', async () => { + const sent = [] + const actions = { ...spy(), scheduleUpdate: async (task) => { sent.push(task); return OFF } } + seeded.push({ available: true, tasks: [ACTIVE] }, ACTIVE) + const card = render(BotSchedules({ bot: { id: 'b1' }, roster: ROSTER, actions })) + const form = all(card).find(node => node.type === 'form') + assert.ok(form, 'the edited row is a form') + const zone = zoneSelects(form)[0] + assert.ok(zone, 'the edit form names the zone its task keeps') + assert.equal(zone.props.value, 'Asia/Shanghai', 'the form shows the task\'s zone, not this device\'s') + assert.equal(optionsOf(zone)[0].props.value, 'Asia/Shanghai', 'a zone already on the task stays listed, and first') + // The row and the form must agree about which 09:00 this is. + const row = timingText(ACTIVE) + assert.ok(row.includes('(Asia/Shanghai)'), `the row names the zone, saw ${row}`) + form.props.onSubmit({ preventDefault() {} }) + await tick() + const [saved] = JSON.parse(JSON.stringify(sent)) + assert.deepEqual(saved.when, { kind: 'daily', time: '09:00', timeZone: 'Asia/Shanghai' }) +}) + +test('#3110: a Once task\'s wall clock is read in the form\'s zone, not this device\'s', () => { + // A Once task is an instant built from a wall clock. With a zone control, that wall clock is the + // one in the chosen zone: 07:05 in Tokyo is 22:05Z the day before, not 07:05Z. + assert.equal(typeof instantFromWallClock, 'function', 'the form converts a wall clock in its zone') + assert.equal(instantFromWallClock('2030-01-02T07:05', 'Asia/Tokyo'), '2030-01-01T22:05:00.000Z') + assert.equal(wallClockInput(Date.parse('2030-01-01T22:05:00.000Z'), 'Asia/Tokyo'), '2030-01-02T07:05', 'editing it shows the same wall clock back') + // The bundle answers from its own realm, so the payload is compared as plain data. + const same = value => JSON.parse(JSON.stringify(value)) + assert.deepEqual( + same(whenFromForm({ kind: 'at', at: '2030-01-02T07:05', time: '07:05', timeZone: 'Asia/Tokyo' })), + { kind: 'at', at: '2030-01-01T22:05:00.000Z', timeZone: 'Asia/Tokyo' }, + ) + // A duration carries no zone, and a wall clock the zone skips (a DST gap) is refused rather than + // silently moved to another hour. + assert.deepEqual(same(whenFromForm({ kind: 'every', count: 2, unit: 'hours' })), { kind: 'every', seconds: 7200 }) + assert.throws(() => instantFromWallClock('2030-03-10T02:30', 'America/New_York'), /Pick a date and time/) + // The form's own opening state reads a Once task in the zone it keeps, so opening Edit and + // saving without touching the time does not move the task. + const once = { ...ACTIVE, kind: 'at', timeZone: 'Asia/Tokyo', scheduledAt: '2030-01-01T22:05:00.000Z' } + const start = formStart(once) + assert.deepEqual(same([start.kind, start.at, start.timeZone]), ['at', '2030-01-02T07:05', 'Asia/Tokyo']) +}) diff --git a/docs/subsystems/core-client.md b/docs/subsystems/core-client.md index bd5118ac9..a0baa11e1 100644 --- a/docs/subsystems/core-client.md +++ b/docs/subsystems/core-client.md @@ -49,7 +49,7 @@ The browser side of the patched `ds-bot` core (`core/`): sources in `core/src/cl | `core/src/client/panes.js` | `PANE_MIN_WIDTH_CSS` (#705): every pane the multi-pane row flexes gets `min-width:0`, the conversation column is matched by its DSH class fragment, and the panel's long values (About text, `4.1M tok · Cache hit …`) wrap with `overflow-wrap:anywhere`, so a value that cannot wrap never widens the panel past the space reserved for it. The same sheet clips horizontal overflow on the document, the conversation column and the app frame (`overflow-x:clip`, #1086), and `watchShellLevel` / `levelShell` put a leftover `scrollLeft` back, so an error toast or dialog cannot leave the window shifted. Tests: `core/test/shell-level.test.js`. | | `core/src/shared/approval-waiting.js` | The one rule for "this hold still waits for the owner's decision" (#734, #754): `isApprovalWaiting(status)` is true for `pending` and `pending_approval` and false for every settled spelling (`approved`, `auto`, `failed`, `rejected`, `stale`, missing). The host writes `pending`; Bot Social's own outbound hold arrives as `pending_approval`. Host and client both import this one file — the held-reply card, the approvals overlay and the chat bubble on this side, `hooks.js` (`decide()`, `heldOf()`, the cap, the in-flight filter, the cleanup) and `channel.js` (a row's wait badge) on the other — and the overlay asks the host for `[...WAITING_STATUSES, 'failed']`, so the two spellings cannot drift apart again on one side only. Tests: `core/test/approval-waiting.test.js`, `core/test/host-approval-status.test.js`. | | `core/src/shared/held-retry.js` | The one rule for "this failure can still be retried" (#968): `canRetry(record)` is false for `retry: false`, for `noRetry: true`, and for a record whose stored `error`/`code` names a terminal reason (`no such remote bot` / `is not shared with your Bots` / `is no longer shared with you` / `has not granted chat.public` / `bot_not_shared` / `bot_not_found`; a bare `capability_not_granted` is not one, #988), true otherwise. The host states the same answer in two spellings (`noRetry` on an approval, `retry: false` on a held reply), so both cards and Bot Social's own dock ask this one function instead of keeping a copy each; a hold written before the flag existed is read from its stored sentence at render time, with no state migration. Tests: `core/test/held-retry.test.js`. | -| `core/src/client/schedules.js` | Settings → Scheduled tasks, a Bot's card and the details line. Each row has **Edit** (pencil; the row turns into the same form that creates a task, filled in, with **Save changes**; a new task opens with no target chosen — **Send to** reads "Pick a Bot or group chat" and **Create task** stays disabled until one is picked, so one click cannot create the task for the first Bot (#1334); an edited task keeps its time zone, a cron rule it cannot show is kept), **Copy** (`CopyRow`, #1287: the row turns into the create form's target picker, minus the chat the task already runs in, and **Copy** posts `schedule-create` with `copyFrom: { sessionId, id }` — the host writes the row, so the copy keeps the source's next run) and **Pause** / **Resume**; a paused row reads **Paused** (#354). A row with a recorded run adds one line under it: "Running since …", "Last run …", "Last run … · Stopped" or, in red, "Last run … · Failed: "; a failed run of a task that is not paused gets **Retry**, and any other task the host will run on demand — active, with no run in flight — gets **Run now**; both call the same `actions.scheduleRetry` and run the task once now without moving DSH's own next time (#473, #2507). With Automation tasks off, the hint reads "Switch on Automation tasks on the Plugins page." and the button **Open Plugins** closes the Settings dialog and opens DSH's Plugins panel (`actions.selectPanel('plugins')`); the Harness settings dialog has no such switch (#378). The page opens with the team's **Quiet hours** card (#1166): **Off** with a **Turn on** button, or **On, 22:00–07:00** with the window's two time fields and **Save window** (the settings write refuses an invalid window, and the host's named refusal appears on the form's error line, as a `role="alert"` so it is announced and not only printed (#2232)). While quiet hours are on and an `every`/`cron` task exists, the view's `quietUnchecked` flag draws one line saying such a task can still run inside the window: that flag is the only place the rule is computed — the page does not scan the task list itself (#1199) — and it asks for the view again right after the settings write, so the line does not wait for the 30-second poll. Never a silent claim of silence, and no suppressed count. A repeat whose interval is not a whole number of minutes is stated as seconds (`Every 90 seconds`, #1651): the edit form opens holding that exact value in the **seconds** unit, and saving a task whose repeat was not touched sends the stored interval back unchanged instead of a rounded number of minutes. A 60-second repeat — the shortest interval DSH allows — reads `Every minute` instead of `Every 1 minutes`, and the form names a single unit in the singular (`1 minute`) in both locales (#2979). The details panel's line (`ScheduleSummary`) lists every task of that Bot, paused and finished ones included, because a Bot whose tasks are all paused has tasks while a Bot with none is the only empty state; each row answers when — `Next: