[PR #4715] [MERGED] fix(autonomous): poll lightweight candidate ids instead of the full chat list every 30s #6474

Closed
opened 2026-10-23 04:10:46 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/4715
Author: @kolacheee
Created: 8/7/2026
Status: ✅ Merged
Merged: 8/7/2026
Merged by: @kolacheee

Base: staging ← Head: fix/4704-autonomous-candidates-poll


📝 Commits (1)

  • 661b61d fix(autonomous): poll lightweight candidate ids instead of the full chat list

📊 Changes

5 files changed (+169 additions, -19 deletions)

View changed files

📝 packages/client/src/hooks/use-autonomous-messaging.ts (+9 -3)
📝 packages/client/src/hooks/use-background-autonomous.ts (+53 -16)
📝 packages/server/src/routes/chats.routes.ts (+26 -0)
➕ packages/server/src/services/conversation/autonomous-candidates.ts (+35 -0)
📝 scripts/regressions/open-issues.regression.ts (+46 -0)

📄 Description

Linked issue

Closes #4704 (from the Termux battery follow-up audit; related: #4629/#4643 fixed the extension-poll half, #4705 covers the server-side scheduler sweep)

Why this change

The background-autonomous poller fetched the full /chats list every 30 seconds on every open client, even with zero autonomous chats — and each of those GETs also ran the empty-DM-cleanup pass (an O(total-messages) countMessages scan per DM thread on the file-native store). On a Termux self-host the phone pays both the radio and the server CPU for that, forever. It was the heaviest remaining idle network cost after #4643.

What changed

  • New GET /chats/autonomous-candidates — returns only [{ id }] for conversation chats with autonomous messaging enabled (excluding the Professor Mari home assistant), via a pure predicate (services/conversation/autonomous-candidates.ts) shared with the regression suite. No full-list serialization, no cleanup scans. Static path, so Fastify prefers it over GET /:id.
  • Empty-DM-thread guard — the legacy poll's GET /chats ran cleanupEmptyRoleplayDmChats as a side effect; without it, an emptied DM thread with stale in-memory activity state could receive an autonomous message and permanently exempt itself from cleanup. The route excludes zero-message chats carrying the DM markers (countMessages runs only for DM-marker candidates, so the scan cost the endpoint exists to avoid stays avoided). Marker expression mirrors the cleanup's, with a sync-note comment on both sides.
  • Poller swap (use-background-autonomous.ts) — same 30s cadence (cross-device discovery unchanged at ≤1 tick), same client-side exclusions (active chat, in-flight generations). Against pre-#4704 servers it falls back to the legacy full-list fetch with identical local filtering; a definitive 404 latches the fallback for the session (transient errors keep retrying; reload after a server upgrade resets it), with a one-time console.debug note.
  • Removed the mis-wired per-tick invalidation (use-autonomous-messaging.ts) — it refetched the full character list every 30s during open autonomous conversations, but its stated purpose (sidebar status dots) reads ["characters","summaries"], which the invalidated key never matched. Dot freshness actually comes from chat-metadata status snapshots plus the summaries query's staleTime/focus refetches.

Review provenance: the fix design was red-teamed before implementation (including an explicit trace proving message-edit persistence is fully independent of this poll — the concern is answered in #4704), and the implementation then went through a second adversarial review that found 3 issues, all fixed here: the empty-DM cleanup dependency (the old poll was accidentally load-bearing), the fallback lacking a 404 latch, and a wrong comment. Zero findings refuted.

Known pre-existing (not fixed here): ConversationPresenceCard's signature invalidation targets the same mismatched characterKeys.list() key — flagged during review; happy to file/fix separately.

Validation

  • pnpm check passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed CONTRIBUTING.md

Manual verification notes

Automated/scripted checks already performed (green):

  • pnpm check (lint + production build) — run twice (post-implementation, post-review-fixes)
  • regression:issues open-issues lane — passes with new cases for the candidate predicate (mode/metadata/Mari/unparseable) and the DM-marker helper
  • Live on the built app: the poller's first tick hits GET /api/chats/autonomous-candidates (zero legacy /chats calls observed); direct probe returns 200 with the [{id}] shape (empty array on a no-autonomous install, which the shape check accepts without falling back); hidden-tab gating still skips ticks

Still to verify manually (please tick above once done):

  1. A chat with autonomous messages enabled still receives background messages (≤30s discovery), with notification/badge/toast behavior unchanged.
  2. DND: presence still propagates to candidate chats while suppressed.
  3. Against an older server build (or by renaming the route): background autonomous still works via the fallback, and the console shows the one-time legacy-fallback debug line.
  4. Roleplay DM flow: emptied DM threads still get cleaned up on normal navigation, and no autonomous message ever lands in an emptied thread.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

No user-facing docs cover the polling internals; no version bump.

Summary by CodeRabbit

  • New Features

    • Improved background autonomous messaging to identify eligible conversations more efficiently.
    • Added filtering to exclude inactive, empty, malformed, or unsupported conversations.
    • Added fallback behavior when the optimized candidate lookup is unavailable.
  • Bug Fixes

    • Prevented unnecessary character-list refreshes during autonomous messaging checks.
  • Tests

    • Added coverage for candidate eligibility and Roleplay conversation detection.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/4715 **Author:** [@kolacheee](https://github.com/kolacheee) **Created:** 8/7/2026 **Status:** ✅ Merged **Merged:** 8/7/2026 **Merged by:** [@kolacheee](https://github.com/kolacheee) **Base:** `staging` ← **Head:** `fix/4704-autonomous-candidates-poll` --- ### 📝 Commits (1) - [`661b61d`](https://github.com/Pasta-Devs/Marinara-Engine/commit/661b61dd9a31db608b8dba41ba81a70b3341d078) fix(autonomous): poll lightweight candidate ids instead of the full chat list ### 📊 Changes **5 files changed** (+169 additions, -19 deletions) <details> <summary>View changed files</summary> 📝 `packages/client/src/hooks/use-autonomous-messaging.ts` (+9 -3) 📝 `packages/client/src/hooks/use-background-autonomous.ts` (+53 -16) 📝 `packages/server/src/routes/chats.routes.ts` (+26 -0) ➕ `packages/server/src/services/conversation/autonomous-candidates.ts` (+35 -0) 📝 `scripts/regressions/open-issues.regression.ts` (+46 -0) </details> ### 📄 Description <!-- Target branch: `staging`. --> ## Linked issue Closes #4704 (from the Termux battery follow-up audit; related: #4629/#4643 fixed the extension-poll half, #4705 covers the server-side scheduler sweep) ## Why this change The background-autonomous poller fetched the **full `/chats` list every 30 seconds on every open client**, even with zero autonomous chats — and each of those GETs also ran the empty-DM-cleanup pass (an O(total-messages) `countMessages` scan per DM thread on the file-native store). On a Termux self-host the phone pays both the radio and the server CPU for that, forever. It was the heaviest remaining idle network cost after #4643. ## What changed - **New `GET /chats/autonomous-candidates`** — returns only `[{ id }]` for conversation chats with autonomous messaging enabled (excluding the Professor Mari home assistant), via a pure predicate (`services/conversation/autonomous-candidates.ts`) shared with the regression suite. No full-list serialization, no cleanup scans. Static path, so Fastify prefers it over `GET /:id`. - **Empty-DM-thread guard** — the legacy poll's `GET /chats` ran `cleanupEmptyRoleplayDmChats` as a side effect; without it, an emptied DM thread with stale in-memory activity state could receive an autonomous message and permanently exempt itself from cleanup. The route excludes zero-message chats carrying the DM markers (`countMessages` runs only for DM-marker candidates, so the scan cost the endpoint exists to avoid stays avoided). Marker expression mirrors the cleanup's, with a sync-note comment on both sides. - **Poller swap** (`use-background-autonomous.ts`) — same 30s cadence (cross-device discovery unchanged at ≤1 tick), same client-side exclusions (active chat, in-flight generations). Against pre-#4704 servers it **falls back to the legacy full-list fetch** with identical local filtering; a definitive 404 latches the fallback for the session (transient errors keep retrying; reload after a server upgrade resets it), with a one-time `console.debug` note. - **Removed the mis-wired per-tick invalidation** (`use-autonomous-messaging.ts`) — it refetched the full character list every 30s during open autonomous conversations, but its stated purpose (sidebar status dots) reads `["characters","summaries"]`, which the invalidated key never matched. Dot freshness actually comes from chat-metadata status snapshots plus the summaries query's staleTime/focus refetches. **Review provenance:** the fix design was red-teamed before implementation (including an explicit trace proving message-edit persistence is fully independent of this poll — the concern is answered in #4704), and the implementation then went through a second adversarial review that found 3 issues, all fixed here: the empty-DM cleanup dependency (the old poll was accidentally load-bearing), the fallback lacking a 404 latch, and a wrong comment. Zero findings refuted. **Known pre-existing (not fixed here):** `ConversationPresenceCard`'s signature invalidation targets the same mismatched `characterKeys.list()` key — flagged during review; happy to file/fix separately. ## Validation <!-- Required: include commands run and/or manual checks performed --> - [x] `pnpm check` passes locally - [x] Container (Docker / Podman) built and ran without issue - [x] Ran the app, clicked through the changes manually - [x] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [x] Above manual verification completed (describe below) - [x] Read and followed `CONTRIBUTING.md` ### Manual verification notes Automated/scripted checks already performed (green): - `pnpm check` (lint + production build) — run twice (post-implementation, post-review-fixes) - `regression:issues` open-issues lane — passes with new cases for the candidate predicate (mode/metadata/Mari/unparseable) and the DM-marker helper - **Live on the built app**: the poller's first tick hits `GET /api/chats/autonomous-candidates` (zero legacy `/chats` calls observed); direct probe returns `200` with the `[{id}]` shape (empty array on a no-autonomous install, which the shape check accepts without falling back); hidden-tab gating still skips ticks Still to verify manually (please tick above once done): 1. A chat with autonomous messages enabled still receives background messages (≤30s discovery), with notification/badge/toast behavior unchanged. 2. DND: presence still propagates to candidate chats while suppressed. 3. Against an older server build (or by renaming the route): background autonomous still works via the fallback, and the console shows the one-time legacy-fallback debug line. 4. Roleplay DM flow: emptied DM threads still get cleaned up on normal navigation, and no autonomous message ever lands in an emptied thread. ## Docs and release impact - [x] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) No user-facing docs cover the polling internals; no version bump. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved background autonomous messaging to identify eligible conversations more efficiently. * Added filtering to exclude inactive, empty, malformed, or unsupported conversations. * Added fallback behavior when the optimized candidate lookup is unavailable. * **Bug Fixes** * Prevented unnecessary character-list refreshes during autonomous messaging checks. * **Tests** * Added coverage for candidate eligibility and Roleplay conversation detection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-23 04:10:46 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#6474
No description provided.