fix(scheduler-ui): preserve seconds in local one-time timestamps (#8627)

* fix(scheduler-ui): preserve seconds in local one-time timestamps

* fix(readability): preserve links in fallback without source URL

* fix(readability): distinguish document wrappers from SVG titles

* fix(scheduler-ui): accept fractional timestamps without seconds
This commit is contained in:
杰尼龟 2026-11-25 23:24:51 +08:00 committed by GitHub
parent f3dfb55110
commit aa9913c4cc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
8 changed files with 188 additions and 83 deletions

View File

@ -100,12 +100,21 @@ class Article:
_BASE_TAG_RE = re.compile(r"<base", re.IGNORECASE)
# A successful Readability.js extraction always strips <body> and <title>;
# their presence in the content signals the subprocess returned the raw document.
_UNEXTRACTED_DOC_RE = re.compile(r"<body\b[^>]*>|<title\b[^>]*>", re.IGNORECASE)
_DOCUMENT_WRAPPER_RE = re.compile(r"<(?:html|head|body)\b", re.IGNORECASE)
_BODY_INNER_RE = re.compile(r"<body[^>]*>(.*)</body>", re.DOTALL | re.IGNORECASE)
def _has_document_wrapper(content: str) -> bool:
# html.parser preserves explicit wrappers without synthesizing them for
# fragments. SVG titles, comments and script examples are not documents.
if not _DOCUMENT_WRAPPER_RE.search(content):
return False
# The Python extractor can enclose a surviving body in a div. Ignore
# foreign content, where document-like tags can belong to a chart.
wrappers = BeautifulSoup(content, "html.parser").find_all(["html", "head", "body"])
return any(wrapper.find_parent(["svg", "math"]) is None for wrapper in wrappers)
def _resolve_html_urls(html: str, url: str) -> str:
"""Resolve destinations before extraction can discard the document's base tag."""
# A base element requires a literal start-tag prefix. False positives in
@ -227,13 +236,13 @@ class ReadabilityExtractor:
if not html_content or not str(html_content).strip():
html_content = "No content could be extracted from this page"
# Detect silent Readability.js degradation: a successful extraction always
# strips <body> and <title> from the content. Their presence means the
# subprocess returned the raw document (e.g. on Windows where the node
# bridge may not produce real output). When detected, use the resolved
# HTML's <body> content so that <a> destinations survive.
if url and html and _UNEXTRACTED_DOC_RE.search(html_content):
logger.info("Readability.js returned the unextracted document; using resolved HTML body")
# Detect whole-document extraction results through explicit document
# wrappers; an extracted chart can legitimately contain an SVG title.
# When detected, use the resolved
# HTML's <body> content so that <a> destinations survive. Apply the
# same fallback without a source URL, preserving relative destinations.
if html and _has_document_wrapper(html_content):
logger.info("Readability extraction returned the unextracted document; using HTML body")
body_match = _BODY_INNER_RE.search(html)
html_content = body_match.group(1) if body_match else html

View File

@ -4,6 +4,7 @@ import importlib
from ipaddress import ip_address
from types import SimpleNamespace
from unittest.mock import AsyncMock
from urllib.parse import urljoin
import pytest
@ -65,7 +66,9 @@ def test_extract_article_resolves_images_and_relative_document_base():
assert "![Chart](https://example.com/assets/images/chart.png)" in markdown
def test_extract_article_without_url_preserves_legacy_relative_links():
def test_extract_article_without_url_preserves_legacy_relative_links(monkeypatch):
# Exercise the real Python fallback even on hosts with a working Node bridge.
monkeypatch.setattr("deerflow.utils.readability._readability_js_available", lambda: False)
article = ReadabilityExtractor().extract_article(_article('<a href="../next">Next</a>'))
assert "[Next](../next)" in article.to_markdown()
@ -215,10 +218,9 @@ def test_base_precheck_false_positives_do_not_override_page_url(head):
assert '<a href="https://example.com/next">Next</a>' in _resolve_html_urls(html, PAGE_URL)
def test_falls_back_when_extraction_returns_unextracted_document(monkeypatch):
"""When Readability.js returns the raw document instead of the extracted
article (e.g. on Windows), the resolved HTML's <body> content is used so
that <a> destinations survive."""
@pytest.mark.parametrize("url", [None, PAGE_URL])
def test_falls_back_when_extraction_returns_unextracted_document(monkeypatch, url):
"""A raw extraction result uses the source body with or without a URL."""
import deerflow.utils.readability as R
monkeypatch.setattr(
@ -226,23 +228,25 @@ def test_falls_back_when_extraction_returns_unextracted_document(monkeypatch):
"simple_json_from_html_string",
lambda html, use_readability=True: {"title": "Guide", "content": html},
)
article = R.ReadabilityExtractor().extract_article(_article('<a href="../next">Next</a> <a href="/reference">Reference</a>'), url=PAGE_URL)
article = R.ReadabilityExtractor().extract_article(_article('<a href="../next">Next</a> <a href="/reference">Reference</a>'), url=url)
md = article.to_markdown()
assert "[Next](https://example.com/next)" in md
assert "[Reference](https://example.com/reference)" in md
assert md.count("Guide") == 1
assert f"[Next]({urljoin(url or '', '../next')})" in md
assert f"[Reference]({urljoin(url or '', '/reference')})" in md
def test_link_free_article_with_link_bearing_chrome_does_not_fall_back(monkeypatch):
@pytest.mark.parametrize("url", [None, PAGE_URL])
@pytest.mark.parametrize("decoration", ["", "<svg><title>Chart</title></svg>", "<!-- <body>Example</body> -->", '<script>const example = "<body>";</script>', "<svg><foreignObject><body>Chart</body></foreignObject></svg>"])
def test_link_free_article_with_link_bearing_chrome_does_not_fall_back(monkeypatch, url, decoration):
"""A legitimately link-free article whose page chrome has links must NOT
trigger the unextracted-document fallback — Readability correctly strips
the chrome, and the article body genuinely has no links."""
import deerflow.utils.readability as R
prose = "Long enough prose for the readability extractor to retain this as content. "
html = f'<html><head><title>Guide</title></head><body><nav><a href="/home">Home</a> <a href="/about">About</a></nav><article><p>{prose * 4}</p></article></body></html>'
url = PAGE_URL
html = f'<html><head><title>Guide</title></head><body><nav><a href="/home">Home</a> <a href="/about">About</a></nav><article><p>{prose * 4}</p>{decoration}</article></body></html>'
extracted_content = f"<div><p>{prose * 4}</p></div>"
extracted_content = f"<div><p>{prose * 4}</p>{decoration}</div>"
def fake_extract(html, use_readability=True):
return {"title": "Guide", "content": extracted_content}

View File

@ -6,6 +6,11 @@ Editing a one-time task's title or prompt preserves its original execution time,
An unchanged one-time execution time can still be saved within `scheduler.min_once_delay_seconds` of its run. New execution times and reactivated finished tasks must satisfy that minimum delay.
One-time local timestamps saved through chat or the API retain their seconds
and fractional seconds when the Web UI resolves them in the task's timezone.
This includes stored timestamps such as `2026-12-07T09:00.5`, which the
scheduler interprets as `09:00:00.5` in that timezone.
Current MVP capabilities:
- Manage tasks at `/workspace/scheduled-tasks`

View File

@ -506,6 +506,12 @@ repeatedly starting a missing toolchain. A non-zero extraction exit falls back
only for that document, because malformed or oversized input can fail while
the toolchain remains healthy. The fallback keeps resolved article links in
the returned Markdown.
When extraction returns a whole document, the fallback uses the source HTML
body consistently with or without a source URL. Calls without a source URL
retain relative link destinations and do not repeat the document title.
Only explicit document-level wrappers trigger that fallback. An inline SVG
chart's title or a document-tag example in a comment or script leaves the
successfully extracted article intact.
Chat tool-step titles accept leading blank lines and up to three spaces before
a page's first H1 heading. Indented code, including mixed spaces and tabs, is
not used as a title; the tool step falls back to the URL.

View File

@ -624,12 +624,24 @@ export function onceRunAtInstant(runAt: string, timezone: string): string {
if (!value || /(?:Z|[+-]\d{2}(?::?\d{2})?)$/i.test(value)) {
return value;
}
const local = /^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})/.exec(value);
const local =
/^(\d{4}-\d{2}-\d{2})[T ](\d{2}:\d{2})(?::([0-5]\d))?([.,]\d+)?$/.exec(
value,
);
if (!local) {
return value;
}
try {
return zonedLocalToUtcIso(`${local[1]}T${local[2]}`, timezone || "UTC");
const minute = zonedLocalToUtcIso(
`${local[1]}T${local[2]}`,
timezone || "UTC",
);
// Offset selection uses the wall minute; retain the stored sub-minute
// precision rather than rounding API/chat-created execution times down.
return minute.replace(
/:00\+00:00$/,
`:${local[3] ?? "00"}${local[4]?.replace(",", ".") ?? ""}+00:00`,
);
} catch {
return value;
}

View File

@ -6,63 +6,78 @@ import { mockLangGraphAPI } from "./utils/mock-api";
// UTC or the browser zone shows up as a wrong time.
test.use({ timezoneId: "Asia/Shanghai" });
test("a date-only run_at shows and edits as midnight in the task's zone", async ({
page,
}) => {
const patches: Record<string, unknown>[] = [];
page.on("request", (request) => {
if (
request.method() === "PATCH" &&
new URL(request.url()).pathname.includes("/api/scheduled-tasks")
) {
patches.push(request.postDataJSON() as Record<string, unknown>);
}
for (const { runAt, time, nextRunAt } of [
{ runAt: "2027-12-07", time: "00:00", nextRunAt: "2027-12-07T05:00:00Z" },
{
runAt: "2027-12-07T09:00.5",
time: "09:00",
nextRunAt: "2027-12-07T14:00:00.500Z",
},
{
runAt: "2027-12-07T09:00,5",
time: "09:00",
nextRunAt: "2027-12-07T14:00:00.500Z",
},
]) {
test(`stored run_at ${runAt} shows and edits in the task's zone`, async ({
page,
}) => {
const patches: Record<string, unknown>[] = [];
page.on("request", (request) => {
if (
request.method() === "PATCH" &&
new URL(request.url()).pathname.includes("/api/scheduled-tasks")
) {
patches.push(request.postDataJSON() as Record<string, unknown>);
}
});
mockLangGraphAPI(page, {
threads: [],
scheduledTasks: [
{
id: "date-only-task",
thread_id: null,
title: "Date-only task",
prompt: "Summarize",
schedule_type: "once",
// Preserve the chat/API format while showing its task-zone wall time.
schedule_spec: { run_at: runAt },
timezone: "America/New_York",
status: "enabled",
next_run_at: nextRunAt,
last_run_at: null,
last_run_id: null,
last_error: null,
run_count: 0,
created_at: "2026-09-01T00:00:00Z",
updated_at: "2026-09-01T00:00:00Z",
},
],
});
// The schedule line drops the year inside the current year and turns
// relative ("Tomorrow") in the final week, so pin "now" well before the run.
await page.clock.setFixedTime(new Date("2026-10-01T00:00:00Z"));
await page.goto("/workspace/scheduled-tasks");
const detail = page.getByTestId("scheduled-task-detail");
// The schedule line itself, read from run_at. The separate next-run line
// comes from the server's next_run_at and was right even before.
await expect(
detail.getByText(`Once, Dec 7, 2027 ${time} (America/New_York)`, {
exact: true,
}),
).toBeVisible();
await detail.getByRole("button", { name: "Edit", exact: true }).click();
const form = page.getByTestId("scheduled-task-form");
await expect(form.getByLabel("Run at")).toHaveValue(`2027-12-07T${time}`);
await form.getByLabel("Title", { exact: true }).fill("Renamed task");
await form
.getByRole("button", { name: "Save changes", exact: true })
.click();
await expect.poll(() => patches.length).toBe(1);
// Only the title changed, so the stored run_at is not rewritten.
expect(patches[0]).not.toHaveProperty("schedule_spec");
});
mockLangGraphAPI(page, {
threads: [],
scheduledTasks: [
{
id: "date-only-task",
thread_id: null,
title: "Date-only task",
prompt: "Summarize",
schedule_type: "once",
// As a chat-created task can store it; the server runs it at
// 2027-12-07 00:00 America/New_York.
schedule_spec: { run_at: "2027-12-07" },
timezone: "America/New_York",
status: "enabled",
next_run_at: "2027-12-07T05:00:00Z",
last_run_at: null,
last_run_id: null,
last_error: null,
run_count: 0,
created_at: "2026-09-01T00:00:00Z",
updated_at: "2026-09-01T00:00:00Z",
},
],
});
// The schedule line drops the year inside the current year and turns
// relative ("Tomorrow") in the final week, so pin "now" well before the run.
await page.clock.setFixedTime(new Date("2026-10-01T00:00:00Z"));
await page.goto("/workspace/scheduled-tasks");
const detail = page.getByTestId("scheduled-task-detail");
// The schedule line itself, read from run_at. The separate next-run line
// comes from the server's next_run_at and was right even before.
await expect(
detail.getByText("Once, Dec 7, 2027 00:00 (America/New_York)", {
exact: true,
}),
).toBeVisible();
await detail.getByRole("button", { name: "Edit", exact: true }).click();
const form = page.getByTestId("scheduled-task-form");
await expect(form.getByLabel("Run at")).toHaveValue("2027-12-07T00:00");
await form.getByLabel("Title", { exact: true }).fill("Renamed task");
await form.getByRole("button", { name: "Save changes", exact: true }).click();
await expect.poll(() => patches.length).toBe(1);
// Only the title changed, so the stored run_at is not rewritten.
expect(patches[0]).not.toHaveProperty("schedule_spec");
});
}

View File

@ -10,6 +10,31 @@ import { I18nProvider } from "@/core/i18n/context";
afterEach(cleanup);
describe("ScheduledTaskScheduleInput", () => {
test.each(["2026-12-07T09:00.5", "2026-12-07T09:00,5"])(
"opens a stored fractional timestamp without seconds: %s",
(runAt) => {
const emitted: ScheduleValue[] = [];
const { container } = render(
<I18nProvider initialLocale="en-US">
<ScheduledTaskScheduleInput
initial={{
schedule_type: "once",
schedule_spec: { run_at: runAt },
timezone: "Asia/Shanghai",
}}
onChange={(value) => emitted.push(value)}
/>
</I18nProvider>,
);
expect(
container.querySelector<HTMLInputElement>(
'input[type="datetime-local"]',
)?.value,
).toBe("2026-12-07T09:00");
expect(emitted.at(-1)?.schedule_spec.run_at).toBe(runAt);
},
);
async function selectPreset(name: string) {
fireEvent.keyDown(screen.getByTestId("schedule-preset"), {
key: "ArrowDown",

View File

@ -559,6 +559,35 @@ describe("zonedLocalToUtcIso DST transitions", () => {
});
describe("onceRunAtInstant", () => {
test.each([
["2026-12-07T09:00.5", "Asia/Shanghai", "2026-12-07T01:00:00.5+00:00"],
["2026-12-07T09:00,5", "Asia/Shanghai", "2026-12-07T01:00:00.5+00:00"],
[
"2026-12-07T09:00:45,123",
"Asia/Shanghai",
"2026-12-07T01:00:45.123+00:00",
],
["2026-11-01T01:30.5", "America/New_York", "2026-11-01T05:30:00.5+00:00"],
[
"2026-12-07T09:00:45.123456",
"Asia/Shanghai",
"2026-12-07T01:00:45.123456+00:00",
],
["2026-12-07 09:00:45", "Asia/Shanghai", "2026-12-07T01:00:45+00:00"],
[
"2026-11-01T01:30:45.123",
"America/New_York",
"2026-11-01T05:30:45.123+00:00",
],
[
"2026-03-08T02:30:45.123",
"America/New_York",
"2026-03-08T07:30:45.123+00:00",
],
])("preserves sub-minute precision for %s in %s", (value, zone, expected) => {
expect(onceRunAtInstant(value, zone)).toBe(expected);
});
test("a run_at without an offset is wall-clock time in the task's zone", () => {
expect(onceRunAtInstant("2026-10-07T09:00:00", "Asia/Shanghai")).toBe(
"2026-10-07T01:00:00+00:00",