Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(ui): 「需要处理」按能否原地修好分按钮与链接

longmeidao4a2765cd3bab
diff --git a/frontend/src/react/activity/background-issues.tsx b/frontend/src/react/activity/background-issues.tsx
index 3ce5a5dec..d8cd65a24 100644
--- a/frontend/src/react/activity/background-issues.tsx
+++ b/frontend/src/react/activity/background-issues.tsx
@@ -2,8 +2,9 @@
*
* 这些是持续状态(调度连续失败、公网入口断开、网络不通),不是跑过的一轮,所以不进任务表;
* 数据来自 `/api/background-issues`,服务端每次现读各服务的快照,问题消失这一行就不在了。
- * 一行只写是什么、从什么时候开始,加一个去处理的入口;原因只在入口指向的那个设置位置讲,
- * 这里不复述。能一键重试的(两个调度)多给一个「立即重试」。
+ * 一行只写是什么、从什么时候开始,加一个写明去处的链接(文案由服务端给);原因只在链接
+ * 指向的那个设置位置讲,这里不复述。原地重跑就可能修好的(网络、调度、amane 桥)多给一个
+ * 「立即重试」,排在链接左边;要改设置、填凭据的只有链接。
*
* 时间分两种:服务自己记下的起点写「自 … 起」;服务不记失败时刻的,写这一次运行里第一次
* 读到它的时刻「发现于 …」,两者不混用。没有问题时整段不画,取数失败也不画:服务连不上时
@@ -27,6 +28,8 @@ export interface BackgroundIssue {
key: string;
title: string;
href: string;
+ /** 链接文案,写具体去处,例如「打开推送设置」。 */
+ link_label: string;
/** 服务自己记下的起点;不记的服务是 null。 */
since: string | null;
/** 这一次运行里第一次读到这一项的时刻。 */
@@ -68,7 +71,7 @@ function IssueRow({ issue }: { issue: BackgroundIssue }) {
? <Button variant="secondary" size="small" disabled={!issue.retry_available}
{...busyProps(retry.isPending)} onClick={() => retry.mutate()}>立即重试</Button>
: null}
- <LinkButton href={issue.href} size="small" trailingIcon={RiArrowRightLine}>去处理</LinkButton>
+ <LinkButton href={issue.href} size="small" trailingIcon={RiArrowRightLine}>{issue.link_label}</LinkButton>
</div>
}>
{retry.error ? `${moment}\n没有重试:${errorMessage(retry.error)}` : moment}
diff --git a/frontend/test/react/activity.test.tsx b/frontend/test/react/activity.test.tsx
index 2a2b6784d..0a1992a6c 100644
--- a/frontend/test/react/activity.test.tsx
+++ b/frontend/test/react/activity.test.tsx
@@ -149,27 +149,30 @@ it('首屏用 prefetch 落进缓存的那一份画出来,挂载时不再请求
});
const issue = (overrides: Partial<BackgroundIssue> = {}): BackgroundIssue => ({
- key: 'network', title: '网络不通', href: '/settings/network#peachProxy', since: null,
- noticed_at: '2026-10-22T07:00:00Z', retry: null, retry_available: false, ...overrides,
+ key: 'tunnel', title: '公网入口连接失败', href: '/settings/network#tunnel', link_label: '打开公网入口设置',
+ since: null, noticed_at: '2026-10-22T07:00:00Z', retry: null, retry_available: false, ...overrides,
});
-it('后台问题排在最前,每项只写是什么、从什么时候起和去处理的入口', async () => {
+it('后台问题排在最前,每项只写是什么、从什么时候起和写明去处的链接,能原地修的另给立即重试', async () => {
issues = [
issue(),
issue({ key: 'follow-schedule', title: '关注自动检查失败', href: '/settings/subscriptions#followScheduleSetting',
- since: '2026-10-22T06:00:00Z', retry: '/api/follow/schedule/run', retry_available: true }),
+ link_label: '打开关注调度', since: '2026-10-22T06:00:00Z', retry: '/api/follow/schedule/run', retry_available: true }),
];
const { host } = await open(payload({ running: [run()] }));
await vi.waitFor(() => { if (!host.querySelector('[role="alert"]')) throw new Error('需要处理还没画出来') });
expect(sections(host)).toEqual(['需要处理', '正在进行']);
- const [network, follow] = [...host.querySelectorAll('[role="alert"]')];
- expect(network?.textContent).toContain('网络不通');
- expect(network?.textContent).toContain('发现于');
- expect(network?.querySelector('a')?.getAttribute('href')).toBe('/settings/network#peachProxy');
- expect(buttonNamed('立即重试', network!)).toBeNull();
+ const [tunnel, follow] = [...host.querySelectorAll('[role="alert"]')];
+ expect(tunnel?.textContent).toContain('公网入口连接失败');
+ expect(tunnel?.textContent).toContain('发现于');
+ expect(tunnel?.querySelector('a')?.getAttribute('href')).toBe('/settings/network#tunnel');
+ expect(tunnel?.querySelector('a')?.textContent).toContain('打开公网入口设置');
+ expect(buttonNamed('立即重试', tunnel!)).toBeNull();
expect(follow?.textContent).toContain('自 ');
expect(follow?.textContent).toContain(' 起');
- expect(follow?.querySelector('a')?.textContent).toContain('去处理');
+ // 按钮在左、链接在右。
+ const [first, second] = [...follow!.querySelectorAll('[data-note-action] a, [data-note-action] button')];
+ expect([first?.textContent, second?.textContent]).toEqual(['立即重试', expect.stringContaining('打开关注调度')]);
await click(buttonNamed('立即重试', follow!));
await vi.waitFor(() => { if (host.querySelectorAll('[role="alert"]').length !== 1) throw new Error('重试后那一项还在') });
diff --git a/src/peach/background_issues.py b/src/peach/background_issues.py
index f5c89662a..e1da86de7 100644
--- a/src/peach/background_issues.py
+++ b/src/peach/background_issues.py
@@ -8,6 +8,9 @@
这里不再复述一遍。高频逐条的失败(站点圆标、头像、单个推送文件)不进来:它们各自有
任务记录,汇总在这里只会刷屏。
+动作按能不能原地修好分:网络、调度、amane 桥这类重跑一次就可能好的给 `retry`(界面上
+一律叫「立即重试」);要改设置、填凭据的只给链接。每项都带链接,`link_label` 写具体去处。
+
时间分两种:`since` 是服务自己记下的起点,只有两个调度有(连续失败里第一轮的开始);
其余服务不记失败时刻,`noticed_at` 是这个进程第一次读到这一项的时间,会晚于实际发生,
重启后重新计。两者不互相顶替。
@@ -32,6 +35,8 @@ class Issue:
key: str
title: str
href: str
+ #: 链接文案写具体去处(「打开推送设置」),界面直接用。
+ link_label: str
since: str | None = None
#: 能一键重试时的 POST 地址;只给自成一体、不需要表单与修订号的动作。
retry: str | None = None
@@ -53,9 +58,9 @@ def _push_discovery(state, _contract, _config) -> list[Issue]:
href = "/settings/library#pushDiscovery"
issues = []
if snapshot["queue"].get("last_error"):
- issues.append(Issue("push-discovery", "自动发现新文件入库失败", href))
+ issues.append(Issue("push-discovery", "自动发现新文件入库失败", href, "打开推送设置"))
if snapshot.get("watch_local") and not snapshot.get("local_running") and snapshot.get("local_message"):
- issues.append(Issue("push-discovery-watch", "本机文件夹监视没有运行", href))
+ issues.append(Issue("push-discovery-watch", "本机文件夹监视没有运行", href, "打开推送设置"))
return issues
@@ -71,10 +76,10 @@ def _downloads(_state, contract, _config) -> list[Issue]:
"AND coalesce(failure_detail, '') <> ''", tuple(TRACKED_STATES)).fetchone()
if not count:
return []
- return [Issue("downloads", f"{count} 个云下载任务对账暂时失败", "/tasks#cloudDownloads")]
+ return [Issue("downloads", f"{count} 个云下载任务对账暂时失败", "/tasks#cloudDownloads", "查看云下载")]
-def _scheduler(attribute: str, key: str, title: str, href: str, retry: str):
+def _scheduler(attribute: str, key: str, title: str, href: str, link_label: str, retry: str):
def provider(_state, contract, _config) -> list[Issue]:
scheduler = getattr(contract, attribute, None)
if scheduler is None:
@@ -82,7 +87,7 @@ def _scheduler(attribute: str, key: str, title: str, href: str, retry: str):
status = scheduler.status()
if not status.get("enabled") or status.get("running") or not status.get("last_error"):
return []
- return [Issue(key, title, href, since=status.get("failing_since"), retry=retry,
+ return [Issue(key, title, href, link_label, since=status.get("failing_since"), retry=retry,
retry_available=bool(status.get("available")))]
return provider
@@ -94,7 +99,7 @@ def _tunnel(state, _contract, config) -> list[Issue]:
return []
if not manager.snapshot().error:
return []
- return [Issue("tunnel", "公网入口连接失败", "/settings/network#tunnel")]
+ return [Issue("tunnel", "公网入口连接失败", "/settings/network#tunnel", "打开公网入口设置")]
def _library_sharing(_state, _contract, config) -> list[Issue]:
@@ -103,24 +108,30 @@ def _library_sharing(_state, _contract, config) -> list[Issue]:
from . import library_sharing
if library_sharing.snapshot(config)["last_attempt"].get("status") != "failed":
return []
- return [Issue("library-sharing", "馆藏分享上传失败", "/settings/maintenance#librarySharing")]
+ return [Issue("library-sharing", "馆藏分享上传失败", "/settings/maintenance#librarySharing", "打开数据上传设置")]
def _automatic_updates(state, _contract, _config) -> list[Issue]:
service = getattr(state, "automatic_updates", None)
if service is None or not service.snapshot().get("error"):
return []
- return [Issue("automatic-updates", "自动更新出错", "/settings/maintenance#automaticUpdates")]
+ return [Issue("automatic-updates", "自动更新出错", "/settings/maintenance#automaticUpdates", "打开自动更新设置")]
-def _amane_bridge(_state, contract, _config) -> list[Issue]:
+def _amane_bridge(state, contract, _config) -> list[Issue]:
tools_root = getattr(contract, "tools_root", None)
if tools_root is None:
return []
from .metadata_amane import bridge_python
if bridge_python(tools_root).is_file():
return []
- return [Issue("amane-bridge", "amane 桥未安装", "/sources#amane")]
+ # 重建是后台任务,跑着的时候再点只会撞上 409;只读端的写入闸门同样会挡。
+ job = getattr(contract, "amane_bridge_job", None)
+ building = bool(job and (job.snapshot() or {}).get("status") == "running")
+ sync = getattr(state, "sync", None)
+ writer = sync is None or not sync.read_only
+ return [Issue("amane-bridge", "amane 桥未安装", "/sources#amane", "打开 amane 设置",
+ retry="/api/scraping/amane-bridge/rebuild", retry_available=writer and not building)]
def _network(state, _contract, _config) -> list[Issue]:
@@ -128,7 +139,8 @@ def _network(state, _contract, _config) -> list[Issue]:
# 只读快照,不在这里启动探测:探测线程由页面读 `/api/network-status` 时拉起。
if monitor is None or monitor.summary().get("state") != "offline":
return []
- return [Issue("network", "网络不通", "/settings/network#peachProxy")]
+ return [Issue("network", "网络不通", "/settings/network#peachProxy", "打开 Peach 代理设置",
+ retry="/api/network-status/check", retry_available=True)]
Provider = Callable[[Any, Any, Any], Iterable[Issue]]
@@ -137,9 +149,9 @@ PROVIDERS: tuple[Provider, ...] = (
_network,
_tunnel,
_scheduler("follow_scheduler", "follow-schedule", "关注自动检查失败",
- "/settings/subscriptions#followScheduleSetting", "/api/follow/schedule/run"),
+ "/settings/subscriptions#followScheduleSetting", "打开关注调度", "/api/follow/schedule/run"),
_scheduler("feed_scheduler", "feed-schedule", "订阅源自动拉取失败",
- "/settings/subscriptions#feedScheduleSetting", "/api/feeds/schedule/run"),
+ "/settings/subscriptions#feedScheduleSetting", "打开订阅源调度", "/api/feeds/schedule/run"),
_push_discovery,
_downloads,
_automatic_updates,
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index beb2090cf..28d69dfcd 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -346,6 +346,15 @@ def network_status(request: Request, _args=Depends(require_auth)):
return monitor.summary()
[email protected]("/api/network-status/check")
+def network_status_check(request: Request, _args=Depends(require_auth)):
+ """当场再探一次外网,回探完的快照。任务中心「网络不通」那一行的「立即重试」走这里。"""
+ monitor = request.app.state.network_reachability
+ monitor.start()
+ monitor.tick()
+ return monitor.summary()
+
+
@router.post("/api/configuration/entry-links")
def save_entry_links(request: Request, body: dict = Body(...), _args=Depends(require_auth)):
local_only(request)
diff --git a/tests/test_background_issues.py b/tests/test_background_issues.py
index 94ef78944..640af3392 100644
--- a/tests/test_background_issues.py
+++ b/tests/test_background_issues.py
@@ -64,9 +64,9 @@ class BackgroundIssueTests(unittest.TestCase):
scheduler._run()
scheduler._run()
[row] = self.collect()
- self.assertEqual({key: row[key] for key in ("key", "href", "retry", "retry_available")}, {
+ self.assertEqual({key: row[key] for key in ("key", "href", "link_label", "retry", "retry_available")}, {
"key": "follow-schedule", "href": "/settings/subscriptions#followScheduleSetting",
- "retry": "/api/follow/schedule/run", "retry_available": True})
+ "link_label": "打开关注调度", "retry": "/api/follow/schedule/run", "retry_available": True})
self.assertEqual(row["since"], scheduler.status()["failing_since"])
self.assertNotIn("1 个来源检查失败", json.dumps(row, ensure_ascii=False))
@@ -78,8 +78,9 @@ class BackgroundIssueTests(unittest.TestCase):
self.state.network_reachability = SimpleNamespace(summary=lambda: {"state": "offline"})
self.state.automatic_updates = SimpleNamespace(snapshot=lambda: {"error": "下载没有启动"})
[network, updates] = self.collect()
- self.assertEqual((network["key"], network["href"], network["since"]),
- ("network", "/settings/network#peachProxy", None))
+ self.assertEqual((network["key"], network["href"], network["link_label"], network["retry"], network["since"]),
+ ("network", "/settings/network#peachProxy", "打开 Peach 代理设置",
+ "/api/network-status/check", None))
noticed = network["noticed_at"]
self.clock.now += 600
self.assertEqual([row["noticed_at"] for row in self.collect()], [noticed, noticed])
@@ -89,7 +90,8 @@ class BackgroundIssueTests(unittest.TestCase):
self.clock.now += 60
self.state.network_reachability = SimpleNamespace(summary=lambda: {"state": "offline"})
self.assertNotEqual(self.collect()[0]["noticed_at"], noticed)
- self.assertEqual(updates["retry"], None)
+ # 要改设置才修得好的只给链接,不给重试。
+ self.assertEqual((updates["retry"], updates["link_label"]), (None, "打开自动更新设置"))
def test_a_disabled_tunnel_with_a_leftover_error_is_not_a_problem(self):
self.state.tunnel = SimpleNamespace(snapshot=lambda: TunnelSnapshot(state="stopped", error="上一次没有正常收尾"))
@@ -134,10 +136,19 @@ class BackgroundIssueTests(unittest.TestCase):
self.assertEqual(keys(self.log.collect(self.state, self.contract, config)), ["library-sharing"])
self.assertEqual(self.log.collect(self.state, self.contract, config), [])
- def test_a_missing_amane_bridge_links_to_the_sources_page(self):
+ def test_a_missing_amane_bridge_can_be_rebuilt_in_place_unless_a_rebuild_is_running(self):
self.contract.tools_root = self.root / "empty-tools"
+ job = {"status": "idle"}
+ self.contract.amane_bridge_job = SimpleNamespace(snapshot=lambda: job)
[row] = self.collect()
- self.assertEqual((row["key"], row["href"]), ("amane-bridge", "/sources#amane"))
+ self.assertEqual((row["key"], row["href"], row["link_label"], row["retry"], row["retry_available"]),
+ ("amane-bridge", "/sources#amane", "打开 amane 设置",
+ "/api/scraping/amane-bridge/rebuild", True))
+ job["status"] = "running"
+ self.assertFalse(self.collect()[0]["retry_available"])
+ job["status"] = "idle"
+ self.state.sync = SimpleNamespace(read_only=True)
+ self.assertFalse(self.collect()[0]["retry_available"])
def test_one_broken_service_does_not_hide_the_others(self):
def broken():
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index 7ed01f716..2efd53742 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -393,10 +393,23 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
response = await self.client.get("/api/background-issues?t=secret")
self.assertEqual(response.status_code, 200)
[issue] = response.json()["issues"]
- self.assertEqual((issue["key"], issue["href"], issue["since"]),
- ("network", "/settings/network#peachProxy", None))
+ self.assertEqual((issue["key"], issue["href"], issue["since"], issue["retry"]),
+ ("network", "/settings/network#peachProxy", None, "/api/network-status/check"))
self.assertTrue(issue["noticed_at"])
+ async def test_network_check_probes_once_on_the_spot_and_returns_the_fresh_state(self):
+ from peach.network_reachability import NetworkReachability
+ monitor = NetworkReachability(check=lambda: True)
+ monitor.start = lambda: None
+ self.app.state.network_reachability = monitor
+ self.assertEqual(monitor.summary()["state"], "checking")
+ refused = await self.client.post("/api/network-status/check?t=secret",
+ headers={"Origin": "https://evil.example"})
+ self.assertEqual(refused.status_code, 403)
+ response = await self.client.post("/api/network-status/check?t=secret")
+ self.assertEqual(response.status_code, 200)
+ self.assertEqual(response.json()["state"], "online")
+
async def test_sources_and_public_health_read_unknown_mount_snapshot_without_io(self):
from peach.mount_reachability import MountReachability, MountRoot
monitor = MountReachability([MountRoot("local", "本地磁盘", "R:/private", self.media_root)],
diff --git a/web/dist/peach-app.js b/web/dist/peach-app.js
index 84576ea82..fea13e045 100644
--- a/web/dist/peach-app.js
+++ b/web/dist/peach-app.js
@@ -2,7 +2,7 @@
(function() {
try {
var e = typeof window < "u" ? window : typeof global < "u" ? global : typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : {}, t = new e.Error().stack;
- t && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[t] = "887b9ab3-7e7f-438e-9d30-d19bb683eace", e._sentryDebugIdIdentifier = "sentry-dbid-887b9ab3-7e7f-438e-9d30-d19bb683eace");
+ t && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[t] = "78ba88d3-4026-4c43-92f5-21c0e99edd13", e._sentryDebugIdIdentifier = "sentry-dbid-78ba88d3-4026-4c43-92f5-21c0e99edd13");
} catch {}
})();
var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, n) => {
@@ -38469,7 +38469,7 @@ function Jve({ issue: e }) {
href: e.href,
size: "small",
trailingIcon: aA,
- children: "去处理"
+ children: e.link_label
})]
}),
children: n.error ? `${r}\n没有重试:${V(n.error)}` : r
@@ -115761,4 +115761,4 @@ pxt(mxt);
//#endregion
export { $w as applyTheme, Zk as peachHistory, Jo as popCount, Vgt as showToast };
-//# debugId=887b9ab3-7e7f-438e-9d30-d19bb683eace
\ No newline at end of file
+//# debugId=78ba88d3-4026-4c43-92f5-21c0e99edd13
\ No newline at end of file