Skip to content

Commit 763a5ee

Browse files
Pleiades1726apet
andauthored
fix(cron): say who owns a task instead of returning an empty list (#10104)
* fix(cron): say *who* owns a task instead of returning an empty list future_task only ever reported tasks owned by the calling sender, so a job that fired in a group chat was invisible to the agent woken by it: the woken event's sender is the group id while the job records the member id, and both edit/delete and list silently dropped it. Agents then concluded the task had disappeared, told users it was stopped, and kept being woken by it. This keeps the ownership rule (only the creator may edit/delete) but makes the result self-describing: * edit/delete of somebody else's task now says the task exists and belongs to another member of this group chat (or to another user when the session is not the same), and points the user at the creator; * list keeps filtering, and appends a note with the number of same-session tasks created by other members that were filtered out. No behaviour change for owned tasks; jobs from other sessions are still neither listed nor counted. * fix(cron): only count real member-owned tasks as hidden Follow-up to the review on the listing note. A same-session job was counted as "created by another member" even when it had no recorded creator, which is the same kind of wrong statement the previous commit set out to remove: CronService.create_job writes origin="api" with a session but no sender_id, and older rows may miss it too. * count only same-session active-agent jobs that recorded a sender id and are not owned by the caller, comparing ownership directly instead of diffing job ids; * edit/delete now answer "has no chat member as its creator (created outside this chat, e.g. from the dashboard)" for such rows instead of blaming another member; * cover basic jobs, creator-less rows and the creator-less delete message. * refactor(cron): inline the ownership replies per AGENTS.md AGENTS.md's "No Unnecessary Helpers" section is inline-first: a helper is only justified at 3+ identical call sites, or when inlining would blow up the enclosing function. The two previous commits added four module-level helpers, three of which had one or two call sites, so fold them back into the edit/delete/list branches. The diff now only changes the answers, not the structure of the calling code. Behaviour is unchanged and the same 22 tests cover it. * refactor(cron): drop the hidden-task count from the list note The count was the only part of the note that could state something false: it needed a predicate that excludes basic jobs and dashboard rows without a sender id, which is what review flagged. A static hint that the list only contains tasks created by the caller is true in every case, needs no counting, and no longer depends on the chat type. --------- Co-authored-by: apet <[email protected]>
1 parent 553096b commit 763a5ee

2 files changed

Lines changed: 238 additions & 7 deletions

File tree

‎astrbot/core/tools/cron_tools.py‎

Lines changed: 66 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from astrbot.core.agent.tool import FunctionTool, ToolExecResult
1212
from astrbot.core.astr_agent_context import AstrAgentContext
1313
from astrbot.core.cron.manager import CronJobSchedulingError
14+
from astrbot.core.platform.message_type import MessageType
1415
from astrbot.core.tools.registry import builtin_tool
1516

1617
_CRON_TOOL_CONFIG = {
@@ -206,7 +207,29 @@ async def call(
206207
if not job:
207208
return f"error: cron job {job_id} not found."
208209
if not _job_belongs_to_current_sender(job, current_umo, current_sender_id):
209-
return "error: you can only edit your own future tasks."
210+
same_session = _extract_job_session(job) == current_umo
211+
if same_session and not _extract_job_sender(job):
212+
# Dashboard / legacy rows have a session but no member as
213+
# their creator, so blaming another member would be wrong.
214+
return (
215+
f"error: cron job {job_id} has no chat member as its creator "
216+
"(it was created outside this chat, e.g. from the dashboard), "
217+
"so you cannot edit it here."
218+
)
219+
if (
220+
same_session
221+
and context.context.event.get_message_type()
222+
== MessageType.GROUP_MESSAGE
223+
):
224+
return (
225+
f"error: cron job {job_id} was created by another member of "
226+
"this group chat, so you cannot edit it. Only the member who "
227+
"created it can edit it; tell the user to ask that member."
228+
)
229+
return (
230+
f"error: cron job {job_id} was not created by you, so you cannot "
231+
"edit it. Only whoever created it can edit it."
232+
)
210233

211234
payload = dict(job.payload) if isinstance(job.payload, dict) else {}
212235

@@ -274,18 +297,56 @@ async def call(
274297
if not job:
275298
return f"error: cron job {job_id} not found."
276299
if not _job_belongs_to_current_sender(job, current_umo, current_sender_id):
277-
return "error: you can only delete your own future tasks."
300+
same_session = _extract_job_session(job) == current_umo
301+
if same_session and not _extract_job_sender(job):
302+
# Dashboard / legacy rows have a session but no member as
303+
# their creator, so blaming another member would be wrong.
304+
return (
305+
f"error: cron job {job_id} has no chat member as its creator "
306+
"(it was created outside this chat, e.g. from the dashboard), "
307+
"so you cannot delete it here."
308+
)
309+
if (
310+
same_session
311+
and context.context.event.get_message_type()
312+
== MessageType.GROUP_MESSAGE
313+
):
314+
return (
315+
f"error: cron job {job_id} was created by another member of "
316+
"this group chat, so you cannot delete it. Only the member who "
317+
"created it can delete it; tell the user to ask that member."
318+
)
319+
return (
320+
f"error: cron job {job_id} was not created by you, so you cannot "
321+
"delete it. Only whoever created it can delete it."
322+
)
278323
await cron_mgr.delete_job(str(job_id))
279324
return f"Deleted cron job {job_id}."
280325

281326
if action == "list":
327+
all_jobs = await cron_mgr.list_jobs()
282328
jobs = [
283329
job
284-
for job in await cron_mgr.list_jobs()
330+
for job in all_jobs
285331
if _job_belongs_to_current_sender(job, current_umo, current_sender_id)
286332
]
333+
# Tasks in this session that were created by somebody else stay
334+
# out of the result. Saying so stops an agent from reading "No cron
335+
# jobs found." as "the task no longer exists".
336+
hidden_note = ""
337+
for job in all_jobs:
338+
if _extract_job_session(job) != current_umo:
339+
continue
340+
if _job_belongs_to_current_sender(job, current_umo, current_sender_id):
341+
continue
342+
hidden_note = (
343+
"\n\nNote: tasks in this chat that were not created by you "
344+
"are not listed here, and can only be edited or deleted by "
345+
"whoever created them."
346+
)
347+
break
287348
if not jobs:
288-
return "No cron jobs found."
349+
return "No cron jobs found." + hidden_note
289350
tz_name = str(
290351
context.context.context.get_config(
291352
umo=context.context.event.unified_msg_origin
@@ -316,7 +377,7 @@ async def call(
316377
lines.append(
317378
f"{j.job_id} | {j.name} | {j.job_type} | run_once={getattr(j, 'run_once', False)} | enabled={j.enabled} | next={next_run}"
318379
)
319-
return "\n".join(lines)
380+
return "\n".join(lines) + hidden_note
320381

321382
return "error: action must be one of create, edit, delete, or list."
322383

‎tests/unit/test_cron_tools.py‎

Lines changed: 172 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import pytest
88

9+
from astrbot.core.platform.message_type import MessageType
910
from astrbot.core.tools.cron_tools import FutureTaskTool
1011

1112

@@ -15,6 +16,7 @@ def _context(
1516
umo: str = "test:group:shared",
1617
sender_id: str = "user-1",
1718
tz_name: str | None = "Asia/Shanghai",
19+
message_type: MessageType = MessageType.GROUP_MESSAGE,
1820
):
1921
return SimpleNamespace(
2022
context=SimpleNamespace(
@@ -25,6 +27,7 @@ def _context(
2527
event=SimpleNamespace(
2628
unified_msg_origin=umo,
2729
get_sender_id=lambda: sender_id,
30+
get_message_type=lambda: message_type,
2831
),
2932
)
3033
)
@@ -183,7 +186,11 @@ async def test_future_task_edit_rejects_same_umo_different_sender():
183186
note="attacker note",
184187
)
185188

186-
assert result == "error: you can only edit your own future tasks."
189+
assert result == (
190+
"error: cron job job-1 was created by another member of this group chat, "
191+
"so you cannot edit it. Only the member who created it can edit it; tell "
192+
"the user to ask that member."
193+
)
187194
cron_mgr.update_job.assert_not_awaited()
188195

189196

@@ -203,7 +210,11 @@ async def test_future_task_delete_rejects_same_umo_different_sender():
203210
job_id="job-1",
204211
)
205212

206-
assert result == "error: you can only delete your own future tasks."
213+
assert result == (
214+
"error: cron job job-1 was created by another member of this group chat, "
215+
"so you cannot delete it. Only the member who created it can delete it; "
216+
"tell the user to ask that member."
217+
)
207218
cron_mgr.delete_job.assert_not_awaited()
208219

209220

@@ -367,3 +378,162 @@ async def test_future_task_create_falls_back_to_run_at_when_scheduler_has_no_tim
367378
)
368379

369380
assert "2026-02-02 08:00:00+08:00" in result
381+
382+
383+
def _raw_job(
384+
job_id: str,
385+
*,
386+
payload: dict | None = None,
387+
job_type: str = "active_agent",
388+
):
389+
"""A job row without the convenience defaults of ``_job``."""
390+
return SimpleNamespace(
391+
job_id=job_id,
392+
name=f"name-{job_id}",
393+
job_type=job_type,
394+
run_once=False,
395+
cron_expression="0 8 * * *",
396+
enabled=True,
397+
next_run_time=None,
398+
payload=payload or {},
399+
)
400+
401+
402+
@pytest.mark.asyncio
403+
async def test_future_task_edit_reports_foreign_job_from_another_session():
404+
"""A job from another session is still "not yours", without group wording."""
405+
tool = FutureTaskTool()
406+
existing_job = _job("job-1", umo="test:group:other", sender_id="user-1")
407+
cron_mgr = SimpleNamespace(
408+
db=SimpleNamespace(get_cron_job=AsyncMock(return_value=existing_job)),
409+
update_job=AsyncMock(),
410+
)
411+
412+
result = await tool.call(
413+
_context(cron_mgr, sender_id="user-1"),
414+
action="edit",
415+
job_id="job-1",
416+
note="nope",
417+
)
418+
419+
assert result == (
420+
"error: cron job job-1 was not created by you, so you cannot edit it. "
421+
"Only whoever created it can edit it."
422+
)
423+
cron_mgr.update_job.assert_not_awaited()
424+
425+
426+
@pytest.mark.asyncio
427+
async def test_future_task_list_notes_hidden_same_session_group_tasks():
428+
"""List mode must say that other members' tasks exist but are filtered out."""
429+
tool = FutureTaskTool()
430+
own_job = _job("own-job", sender_id="user-1")
431+
other_member_job = _job("other-member-job", sender_id="user-2")
432+
cron_mgr = SimpleNamespace(
433+
list_jobs=AsyncMock(return_value=[own_job, other_member_job])
434+
)
435+
436+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
437+
438+
assert "own-job" in result
439+
assert "other-member-job" not in result
440+
assert (
441+
"Note: tasks in this chat that were not created by you are not listed here, "
442+
"and can only be edited or deleted by whoever created them."
443+
) in result
444+
445+
446+
@pytest.mark.asyncio
447+
async def test_future_task_list_explains_hidden_tasks_when_none_are_owned():
448+
"""The "no jobs" answer must not read as "your task disappeared"."""
449+
tool = FutureTaskTool()
450+
other_member_job = _job("other-member-job", sender_id="user-2")
451+
cron_mgr = SimpleNamespace(list_jobs=AsyncMock(return_value=[other_member_job]))
452+
453+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
454+
455+
assert result.startswith("No cron jobs found.")
456+
assert "Note: tasks in this chat that were not created by you" in result
457+
458+
459+
@pytest.mark.asyncio
460+
async def test_future_task_list_has_no_note_when_nothing_is_hidden():
461+
"""No hidden tasks -> no note, the plain answer is enough."""
462+
tool = FutureTaskTool()
463+
cron_mgr = SimpleNamespace(list_jobs=AsyncMock(return_value=[_job("own-job")]))
464+
465+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
466+
467+
assert "Note:" not in result
468+
469+
470+
@pytest.mark.asyncio
471+
async def test_future_task_list_ignores_other_sessions_for_the_hidden_note():
472+
"""Jobs from other sessions must not leak into the count."""
473+
tool = FutureTaskTool()
474+
other_session_job = _job("other-session-job", umo="test:group:other")
475+
cron_mgr = SimpleNamespace(list_jobs=AsyncMock(return_value=[other_session_job]))
476+
477+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
478+
479+
assert result == "No cron jobs found."
480+
481+
482+
@pytest.mark.asyncio
483+
async def test_future_task_list_notes_hidden_basic_job_in_the_session():
484+
"""A basic job in this session is still not a task of the caller."""
485+
tool = FutureTaskTool()
486+
basic_job = _raw_job(
487+
"basic-job",
488+
job_type="basic",
489+
payload={"session": "test:group:shared", "handler_arg": "x"},
490+
)
491+
cron_mgr = SimpleNamespace(list_jobs=AsyncMock(return_value=[basic_job]))
492+
493+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
494+
495+
assert result.startswith("No cron jobs found.")
496+
assert "not created by you are not listed here" in result
497+
498+
499+
@pytest.mark.asyncio
500+
async def test_future_task_list_notes_hidden_jobs_without_a_creator():
501+
"""Dashboard/legacy rows have a session but no member as their creator."""
502+
tool = FutureTaskTool()
503+
orphan_job = _raw_job(
504+
"orphan-job",
505+
payload={"session": "test:group:shared", "origin": "api"},
506+
)
507+
cron_mgr = SimpleNamespace(list_jobs=AsyncMock(return_value=[orphan_job]))
508+
509+
result = await tool.call(_context(cron_mgr, sender_id="user-1"), action="list")
510+
511+
assert result.startswith("No cron jobs found.")
512+
assert "not created by you are not listed here" in result
513+
514+
515+
@pytest.mark.asyncio
516+
async def test_future_task_delete_explains_jobs_without_a_creator():
517+
"""A job with no recorded creator must not be blamed on another member."""
518+
tool = FutureTaskTool()
519+
orphan_job = _raw_job(
520+
"orphan-job",
521+
payload={"session": "test:group:shared", "origin": "api"},
522+
)
523+
cron_mgr = SimpleNamespace(
524+
db=SimpleNamespace(get_cron_job=AsyncMock(return_value=orphan_job)),
525+
delete_job=AsyncMock(),
526+
)
527+
528+
result = await tool.call(
529+
_context(cron_mgr, sender_id="user-1"),
530+
action="delete",
531+
job_id="orphan-job",
532+
)
533+
534+
assert result == (
535+
"error: cron job orphan-job has no chat member as its creator (it was "
536+
"created outside this chat, e.g. from the dashboard), so you cannot "
537+
"delete it here."
538+
)
539+
cron_mgr.delete_job.assert_not_awaited()

0 commit comments

Comments
 (0)