Skip to content

fix(sessions): unread follows visible transcript rows, not run ends - #204209

Closed
obviyus wants to merge 3 commits into
mainfrom
fix/unread-from-transcript
Closed

obviyus wants to merge 3 commits into
mainfrom
fix/unread-from-transcript

Conversation

@obviyus

@obviyus obviyus commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #204164.

Problem

A session went unread with nothing new to read. Example (synthetic): a heartbeat or child-end wake runs in a chat, the model answers NO_REPLY (or HEARTBEAT_OK), and the chat shows no new row, but the sidebar lights its unread dot.

Cause: unread was stamped per run, not per content.

  • The run-end lifecycle projection set lastActivityAt = endedAt for every Control UI–visible run (controlUiVisible).
  • Agent-command post-run set lastActivityAt = now for every run without internal events (touchActivity), with a special case for subagent coordination turns (fix(sessions): exclude hidden coordination and failed children from unread #204143).
  • Auto-reply initSessionState and commitBackgroundResultToSession stamped it separately for inbound messages and background/cron results.

None of these knew whether the run added anything a person can see.

Change

One rule, applied where rows are appended: a session becomes unread (and a snooze ends) only when an appended user or assistant row is one the chat renders with something to read. The decision is projectVisibleSessionActivity (src/config/sessions/session-visible-activity.ts). It uses the Control UI's own per-message projection (projectChatDisplayMessage). Silent replies, heartbeat prompts and acknowledgements, wake inputs, display: false coordination rows, tool calls and reasoning do not count.

The rule writes the entry only when it changes something: when a visible row makes a read session unread, or ends a snooze. Appends to a chat that is already unread stay transcript-only writes, so streaming previews keep their no-rematerialize path.

It is applied by the existing append owners, in the same transaction as the append:

  • transcript turns (buildExpectedTranscriptTurnSessionPatch: chat sends, channel inbound, chat inject, background and cron results);
  • SessionManager appends outside a turn (appendTranscriptMessageSnapshotSync: embedded run replies, including openclaw agent --local);
  • the in-memory (incognito) actor's event writer.

Removed:

  • the run-end lastActivityAt stamp, and controlUiVisible on lifecycle events, which only fed it;
  • agent-command touchActivity, its coordination special case, and its snooze clearing;
  • the initSessionState and background-result lastActivityAt stamps, and lastActivityAt in the turn lifecycle patch type;
  • the lifecycle-event unread recomputation in buildGatewaySessionSnapshot.

Channel inbound messages, background/cron results and --local replies still mark unread, because each appends a visible row.

scripts/pr-lib/wrapper-components.txt gains the projection modules that the session writer now imports (the PR-wrapper import inventory test lists them).

Production line delta (excluding tests, docs and the wrapper/test inventories): +86 / −43 (net +43). The add is the one decision function and its three appliers; the per-run stamps it replaces were smaller.

What the user sees

  • A turn that ends in NO_REPLY, a quiet heartbeat, or an internal wake no longer lights the unread dot.
  • A visible reply, a channel message, or a delivered cron/background result still does.
  • A visible message in a snoozed session still wakes it; a quiet turn no longer does.

Accepted edge cases

  • lastActivityAt now marks the visible row that made the session unread. Further rows in a chat that is already unread do not move it. Row order uses lastInteractionAt/updatedAt as before. Chat prefetch keys on lastActivityAt, so it does not re-warm an already-unread chat for each later row; opening the chat still loads its history.
  • Imports, forks and other batch installs of existing history do not mark unread: they copy rows the reader already had (older than the read baseline).
  • Legacy rows without createdAt or lastReadAt were never unread and still are not; a visible row still wakes them from a snooze.

Review notes

  • Local ClawSweeper findings and why two are rejected: see the Rejected review findings: comment. Round 2 (a snoozed legacy session would not wake) is fixed.
  • CI: model-selection.configured.test.ts fails on main too (ci-triage: MAIN-ALSO). Our reds were fixed: per-append entry writes broke the streaming-preview row contract (now only unread transitions write), the wrapper import inventory, and a stale test inventory entry for the deleted snooze test.

Evidence

  • src/shared/session-unread.test.ts (rewritten) drives real SQLite appends through SessionManager and persistSessionTranscriptTurn:
    • stays read after a NO_REPLY wake turn, a quiet heartbeat, a parent's reply to a child's sessions_send (snooze kept);
    • turns unread and ends the snooze after a visible reply or a channel message; a batched turn that also writes metadata keeps it.
    • On base: the "turns unread" cases fail (appends never set activity); the "stays read" cases pass (base's bug is in the run-end stamp).
  • src/gateway/session-lifecycle-state.test.ts: a visible run's end no longer moves lastActivityAt. Red on base, green on head.
  • src/cron/isolated-agent/destination-completion.test.ts: a delivered cron result marks a read destination unread.
  • Real-Gateway Control UI E2E (throwaway, not committed; only the model provider is scripted; dist build): two chats each get an agent turn with a hidden heartbeat input while the browser shows a third chat. The first reply is NO_REPLY, the second visible.
    • Base (merge base): fails, the NO_REPLY chat shows an unread dot.
    • Head: passes on the first head and again on 854cdb3: the NO_REPLY chat stays read and the visible-reply chat shows a dot. Screenshots in the PR comment.
  • src/shared/session-unread.test.ts also covers a snoozed legacy row (no read baseline) waking on a visible reply.
  • pnpm check:changed on the first head: typecheck, lint, guards and import cycles pass. The PostgreSQL turn-count conformance lane was not run locally (no PostgreSQL); the SQLite turn-count budget is unchanged.

- One rule decides unread activity: an appended user or assistant row the chat
  renders with something to read advances lastActivityAt and ends a snooze.
- Applied by the append owners: transcript turns, SessionManager appends and
  the in-memory actor. NO_REPLY, quiet heartbeats, wakes and hidden turns no
  longer mark a session unread.
- Removed the run-end lifecycle stamp, agent-command touchActivity and its
  coordination special case, and the inbound/background-result stamps.

Co-authored-by: obviyus <[email protected]>

Fixes #204164
@clawsweeper

clawsweeper Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Control UI E2E (real Gateway, scripted provider). Sidebar after a turn with a hidden heartbeat input: "Quiet chat" got NO_REPLY, "Visible chat" got a visible reply. Base: the NO_REPLY chat shows an unread dot. Head: only the visible-reply chat does.

Base: NO_REPLY chat marked unread

Head: NO_REPLY chat stays read

Head: visible reply marks its chat unread

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: M labels Nov 23, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 23, 2026
@clawsweeper

clawsweeper Bot commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR advances unread activity and clears snooze when visible transcript messages are appended instead of when runs finish.

Example: A chat has lastActivityAt=1000 and lastReadAt=1500; a quiet wake ends at 1800 with NO_REPLY.

  • Before: Run completion advances activity to 1800 and shows an unread dot despite no visible reply.
  • After: Activity remains 1000 and the chat stays read.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful direction with convincing central browser evidence, but the append-owner cutover has concrete coverage and integration defects.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 4 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: The sidebar directs users to chats with no new visible message.
Reason: The collaborator-authored direction addresses a demonstrated attention-noise bug through existing transcript owners.

Merge readiness

⛔ Blocked before merge - 6 items remain

Keep open: this addresses a real false-unread bug, but missed failure notices, reset regressions, and broken wrapper extraction block merge.

Priority: P2
Reviewed head: 8548202808b32653b6290f910c7ead469b30bb5c

Before merge

  • Advance activity for visible failure reports before removing the fallback (P2) - When a user reads a running chat and leaves before a provider failure, recordGatewaySessionRunFailure appends a visible run-failed-before-reply custom_message through the transcript-report kernel. That path calls appendTranscriptEventInTransaction directly, bypassing all three new activity appliers, and projectVisibleSessionActivity also excludes custom roles. Removing the lifecycle stamp therefore leaves the chat read despite its new failure card. Apply the shared visibility decision at the report append owner while retaining suppression of hidden notices.
  • Preserve reset behavior when a transcript append changes activity (P2) - The new writeSessionEntry call makes an ordinary visible transcript append change the entry captured by reset preparation. applySessionResetInDatabase compares that complete snapshot, so an append accepted between preparation and commit now rejects the reset instead of parenting its boundary to the accepted message. Exact-head CI demonstrates both single and bulk reset failures in session-accessor.reset-boundary-race.test.ts. Adapt the reset owner's existing conflict handling for this new metadata mutation without weakening session identity or lifecycle checks.
  • Keep the extracted PR wrapper closed over the new runtime imports (P2) - Importing the Gateway display projection introduces session-visible-activity.ts and its transitive presentation dependencies into the trusted PR wrapper's runtime graph, but scripts/pr-lib/wrapper-components.txt does not extract them. The exact-head eager-import-closure checks fail for the missing inventory and extracted dependency resolution. Keep the shared decision within an appropriate leaf dependency boundary or update the complete wrapper inventory so the extracted wrapper can load its runtime.
  • Update consumers that still assume visible appends leave metadata untouched (P2) - The new unconditional activity projection also runs when touchSessionEntry is false, invalidating existing transcript-only fixtures. Exact-head CI fails in session-actor-memory.test.ts, session-accessor.sqlite-entry-writes.test.ts, session-row-projection.accepted-facts.test.ts, and session-row-projection.backfill.test.ts because their appends now advance entry state or observe the transcript. Update these consumers for the new contract; where a test specifically protects transcript-only invalidation or no-op writes, use a genuinely non-activity append rather than deleting its independent assertions.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Native append-kernel dependency boundary - 8e5abec: fix(sessions): isolate native workers from host session imports #182156 extracted native leaf modules to avoid unnecessary host imports; the new Gateway presentation dependency does not account for that boundary or its extracted wrapper inventory.

Findings

  • [P2] Advance activity for visible failure reports before removing the fallback — src/config/sessions/session-run-lifecycle-projection.ts:251-254
  • [P2] Preserve reset behavior when a transcript append changes activity — src/config/sessions/session-accessor.sqlite-transcript-write.kernel.ts:196-202
  • [P2] Keep the extracted PR wrapper closed over the new runtime imports — src/config/sessions/session-visible-activity.ts:3

Provenance

Tests

  • Missing end-to-end proof: Provide a latest-stable upgrade run preserving existing read, manual-unread, and snooze state, with sensitive values redacted.
Agent review details

How this fits together

Session transcript writers persist messages and session metadata; Gateway projections turn those committed facts into unread indicators and snooze state for clients.

flowchart LR
  A[Transcript append] --> B[Display visibility projection]
  B --> C[Atomic activity and snooze update]
  C --> D[Gateway session projection]
  D --> E[Client unread indicator]
  F[Run lifecycle] --> D
Loading

Technical review

Best possible solution:

Keep the shared append-time visibility rule, cover visible failure reports, preserve reset behavior, and complete the affected wrapper and consumer cutover.

Do we have a high-confidence way to reproduce the issue?

Current-main source establishes the silent-completion mismatch, and the inspected base/head browser screenshots corroborate it; no target code was executed during this review.

Is this the best way to solve the issue?

Append-time activity uses the right existing owners and removes competing stamps, but the cutover must include visible report events and consumers that depend on transcript-only writes.

Full review comments:

  • [P2] Advance activity for visible failure reports before removing the fallback — src/config/sessions/session-run-lifecycle-projection.ts:251-254
    When a user reads a running chat and leaves before a provider failure, recordGatewaySessionRunFailure appends a visible run-failed-before-reply custom_message through the transcript-report kernel. That path calls appendTranscriptEventInTransaction directly, bypassing all three new activity appliers, and projectVisibleSessionActivity also excludes custom roles. Removing the lifecycle stamp therefore leaves the chat read despite its new failure card. Apply the shared visibility decision at the report append owner while retaining suppression of hidden notices.
    Confidence: 0.99
  • [P2] Preserve reset behavior when a transcript append changes activity — src/config/sessions/session-accessor.sqlite-transcript-write.kernel.ts:196-202
    The new writeSessionEntry call makes an ordinary visible transcript append change the entry captured by reset preparation. applySessionResetInDatabase compares that complete snapshot, so an append accepted between preparation and commit now rejects the reset instead of parenting its boundary to the accepted message. Exact-head CI demonstrates both single and bulk reset failures in session-accessor.reset-boundary-race.test.ts. Adapt the reset owner's existing conflict handling for this new metadata mutation without weakening session identity or lifecycle checks.
    Confidence: 0.98
  • [P2] Keep the extracted PR wrapper closed over the new runtime imports — src/config/sessions/session-visible-activity.ts:3
    Importing the Gateway display projection introduces session-visible-activity.ts and its transitive presentation dependencies into the trusted PR wrapper's runtime graph, but scripts/pr-lib/wrapper-components.txt does not extract them. The exact-head eager-import-closure checks fail for the missing inventory and extracted dependency resolution. Keep the shared decision within an appropriate leaf dependency boundary or update the complete wrapper inventory so the extracted wrapper can load its runtime.
    Confidence: 1
  • [P2] Update consumers that still assume visible appends leave metadata untouched — src/config/sessions/session-transcript-turn-state.ts:94-104
    The new unconditional activity projection also runs when touchSessionEntry is false, invalidating existing transcript-only fixtures. Exact-head CI fails in session-actor-memory.test.ts, session-accessor.sqlite-entry-writes.test.ts, session-row-projection.accepted-facts.test.ts, and session-row-projection.backfill.test.ts because their appends now advance entry state or observe the transcript. Update these consumers for the new contract; where a test specifically protects transcript-only invalidation or no-op writes, use a genuinely non-activity append rather than deleting its independent assertions.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against a1a7893689ac.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/shared/session-unread.test.ts src/gateway/session-lifecycle-state.test.ts src/gateway/session-lifecycle-run-failure.test.ts --maxWorkers=1
  • pnpm test src/config/sessions/session-accessor.reset-boundary-race.test.ts src/config/sessions/session-actor-memory.test.ts src/config/sessions/session-accessor.sqlite-entry-writes.test.ts --maxWorkers=1
  • pnpm test src/gateway/session-row-projection.accepted-facts.test.ts src/gateway/session-row-projection.backfill.test.ts src/gateway/server-methods/sessions-read-active.test.ts --maxWorkers=1
  • pnpm test test/scripts/eager-import-closure.test.ts --maxWorkers=1
  • pnpm check:changed

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1ad9fe2 adds src/shared/session-unread.ts:11 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1ad9fe2a759d; files: src/shared/session-unread.ts)
  • Ayaan Zaidi: Raw commit 3346727 adds src/shared/session-unread.ts:15 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 334672736749; files: src/shared/session-unread.ts)
  • Vincent Koc: Raw commit 8e5abec adds src/config/sessions/session-accessor.sqlite-transcript-write.kernel.ts:41 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8e5abec30544; files: src/config/sessions/session-accessor.sqlite-transcript-write.kernel.ts)

PR surface

Source +28, Tests -53, Docs 0. Total -25 across 21 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 13 71 43 +28
Tests 7 126 179 -53
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 21 198 223 -25

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: False unread indicators and the identified regressions have a limited session-management blast radius.
  • add merge-risk: 🚨 session-state: The new activity writes omit visible failure reports and invalidate existing reset snapshots during concurrent appends.
  • add merge-risk: 🚨 automation: The new runtime dependency is absent from the extracted PR wrapper inventory, breaking its import closure.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: False unread indicators and the identified regressions have a limited session-management blast radius.
  • merge-risk: 🚨 session-state: The new activity writes omit visible failure reports and invalidate existing reset snapshots during concurrent appends.
  • merge-risk: 🚨 automation: The new runtime dependency is absent from the extracted PR wrapper inventory, breaking its import closure.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 23, 2026, 3:06 PM ET / 20:06 UTC.

…unread state

- A visible row writes the session entry only when it makes a read session
  unread or ends a snooze; appends to an already-unread chat stay
  transcript-only, keeping streaming previews off the row rematerialize path.
- Cover a real sessions_send coordination reply through the run writer's
  display projection.
- Add the projection modules to the PR wrapper import inventory.

Co-authored-by: obviyus <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 23, 2026
…ad baseline

- A visible row ends a snooze set before it, independent of the unread
  baseline, so legacy rows without createdAt/lastReadAt still wake.
- Drop the deleted snooze test from the database-worker test inventory.

Co-authored-by: obviyus <[email protected]>
@obviyus

obviyus commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator Author

Rejected review findings:

  • Round 1 (P2, session-visible-activity.ts: a parent's private reply to a child's sessions_send counted as visible): rejected. Gateway preflight sets sourceRole: "subagent" on every sessions_send input from a subagent session (src/gateway/agent-turn/agent-request-preflight.ts), and the run writer marks every row of that turn display: false (projectAgentHarnessTranscriptMessageForDisplay). The history-side resolver only serves rows written before sourceRole existed. src/shared/session-unread.test.ts drives this case through the run writer's projection.
  • Round 3 (P2, session-visible-activity.ts: keep advancing lastActivityAt for every visible row while a session is already unread): rejected; named as an accepted edge in the PR body. I tried it on this head: an entry write on every visible append broke three existing contracts (session-row-projection.backfill.test.ts streaming previews now rematerialize the row per append, session-turn-postimages.test.ts turn postimages, and session-accessor.reset-boundary-race.test.ts, where the extra entry write races the reset boundary). The cost: a session that is already unread and has old activity clocks can sort as older, or fall outside an activeMinutes window, in activity-ordered lists until it is read. Its unread dot still shows in the sidebar.

(The round 2 finding, a snoozed legacy session not waking, was fixed in 854cdb3.)

@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Status: not ready to land.

PostgreSQL conformance fails on this head because of this PR: src/gateway/server-database-engine-cron.postgres.test.ts (4 tests). Reproduced locally against PostgreSQL 16: the merge base passes, this head fails, and the head passes when the SessionManager-path entry write in appendTranscriptMessageSnapshotSync is disabled. With that write, an isolated cron run on PostgreSQL ends with isError=true after its visible prompt row marks the session unread. The read and write themselves do not throw; the extra entry write inside the transcript append appears to disturb a later fence of the same run.

Same class as the earlier reds on this branch: an entry write inside a SessionManager append breaks transcript-owned contracts (row preview rematerialization, turn postimages, reset boundary, now the PostgreSQL run).

Next step (separate design change): stop writing the entry in the SessionManager append path. Keep the content fact on the transcript side (the window's row-transcript projection already records the latest display-visible assistant row) and let the run-end writer, which already writes the entry, consume it. Turn-path stamping (buildExpectedTranscriptTurnSessionPatch) stays as is.

@obviyus

obviyus commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

Superseded by #204281: the run end reads the transcript's newest visible reply instead of writing the entry in the transcript append path, which broke the PostgreSQL cron run here.

@obviyus obviyus closed this Nov 23, 2026
obviyus added a commit that referenced this pull request Nov 24, 2026
…e reply (#204281)

Closes #204164. Replaces #204209.

## Problem

A session went unread with nothing new to read. Example (synthetic): a heartbeat or child-end wake runs in a chat, the model answers `NO_REPLY` (or `HEARTBEAT_OK`), the chat shows no new row, and the sidebar still lights its unread dot.

Cause: the run end stamped unread activity per run, not per content.
- The Gateway's run-end lifecycle projection set `lastActivityAt = endedAt` for every Control UI–visible run (`controlUiVisible`).
- Agent-command post-run set `lastActivityAt = now` for every run without internal events (`touchActivity`), with a special case for a child's `sessions_send` turns (#204143).

Neither knew whether the run added anything a person can see.

## Change

The run end now reads what the run added. Both run-end writers ask the transcript for its newest visible assistant row (`lastAssistantMessage`, the same row projection that feeds the sidebar preview) and advance `lastActivityAt` to that row's time only when it is newer. Silent replies (`NO_REPLY`), heartbeat acknowledgements and hidden coordination replies (`display: false`) are not visible rows, so a run that ends in one of them leaves unread alone.

- One read: `readVisibleSessionActivityAt` (`src/gateway/session-row-transcript-backfill.ts`), a thin wrapper over the existing bounded row-transcript read (`backfillSessionRowTranscriptFields`).
- Gateway run end: `persistPreparedGatewaySessionLifecycleEvent` passes the time into the lifecycle patch (`visibleActivityAt`); `projectSessionLifecyclePatch` applies it on terminal events.
- Agent-command run end (Gateway `agent` runs and `openclaw agent --local`): `updateSessionStoreAfterAgentRun` reads the same fact; a visible reply also ends a snooze, as before.
- Nothing is written in the transcript append path.
- Channel inbound messages and background/cron results keep their existing stamping (they add a visible row themselves).

Removed:
- the run-end `controlUiVisible` stamp and `controlUiVisible` on lifecycle events, which only fed it;
- agent-command `touchActivity`, its internal-event and coordination special cases;
- the lifecycle-event unread recomputation in `buildGatewaySessionSnapshot`;
- `session-store.snooze.test.ts`, which asserted the removed `touchActivity` parameter (snooze is covered in `session-unread.test.ts`).

Production line delta (excluding tests, docs and test inventories): **+44 / −27 (net +17)**. The read is one helper with two call sites; the per-run special cases it replaces were smaller than the read and its plumbing.

## What the user sees

- A turn that ends in `NO_REPLY`, a quiet heartbeat, an internal wake, or a parent answering its child's `sessions_send` no longer lights the unread dot.
- A visible reply, a channel message, or a delivered cron/background result still does. A visible reply still wakes a snoozed session.

## Accepted edge cases

- Incognito sessions: their transcripts stay in the Gateway process, so the run end has no stored row to read and their replies no longer mark them unread. You are usually in an incognito chat while it runs.
- A reply that is only an image (no text) has no row preview, so it does not mark the chat unread.
- CLI-backend runs (`claude-cli` and similar) persist their transcript after the agent-command run end, so `openclaw agent --local` with a CLI backend does not mark unread from that writer. I did not verify whether the Gateway lifecycle run end sees a Gateway CLI run's reply.
- A visible reply whose stored event is over 64 KiB has no row preview, so it does not mark the chat unread (the preview read is size-bounded so it can run at every run end).
- The run end adds one bounded transcript read per terminal run (the same read the sidebar row owner already does).

## Evidence

- `src/shared/session-unread.test.ts` (rewritten) appends real rows to a SQLite transcript and runs the real agent-command run end:
  - stays read and snoozed after a `NO_REPLY` wake turn, a quiet heartbeat, and a parent's reply to a child's `sessions_send` (built through the run writer's display projection). **Red on base** (base stamps every run).
  - turns unread and ends the snooze after a visible reply;
  - inbound channel message unread, internal wake read (unchanged from #204143).
- `src/gateway/session-lifecycle-state.test.ts`: a visible run that ends without a new visible reply leaves `lastActivityAt` alone. **Red on base.**
- `src/cron/isolated-agent/destination-completion.test.ts` (unchanged): a delivered cron result still stamps the destination.
- PostgreSQL conformance, full suite, locally against PostgreSQL 16 (pgvector pg16 image from CI): `server-database-engine-cron.postgres.test.ts`, which failed on #204209, passes. `client-credential-update.test.ts` and `git-backup.postgres.test.ts` fail locally the same way on the merge base (local environment, not this change).
- `pnpm check:changed`: typecheck, lint and guards pass. The dead-export scan fails on three exports this PR does not touch (also on `main`).
- Real-Gateway Control UI E2E (throwaway, not committed; only the model provider is scripted; dist build): two chats each get an `agent` turn with a hidden heartbeat input while the browser shows a third chat. The first reply is `NO_REPLY`, the second visible.
  - Base: **fails**, the `NO_REPLY` chat shows an unread dot.
  - Head: **passes**, the `NO_REPLY` chat stays read; the visible-reply chat shows a dot. Screenshots in a PR comment.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 24, 2026
…e reply (openclaw#204281)

Closes openclaw#204164. Replaces openclaw#204209.

## Problem

A session went unread with nothing new to read. Example (synthetic): a heartbeat or child-end wake runs in a chat, the model answers `NO_REPLY` (or `HEARTBEAT_OK`), the chat shows no new row, and the sidebar still lights its unread dot.

Cause: the run end stamped unread activity per run, not per content.
- The Gateway's run-end lifecycle projection set `lastActivityAt = endedAt` for every Control UI–visible run (`controlUiVisible`).
- Agent-command post-run set `lastActivityAt = now` for every run without internal events (`touchActivity`), with a special case for a child's `sessions_send` turns (openclaw#204143).

Neither knew whether the run added anything a person can see.

## Change

The run end now reads what the run added. Both run-end writers ask the transcript for its newest visible assistant row (`lastAssistantMessage`, the same row projection that feeds the sidebar preview) and advance `lastActivityAt` to that row's time only when it is newer. Silent replies (`NO_REPLY`), heartbeat acknowledgements and hidden coordination replies (`display: false`) are not visible rows, so a run that ends in one of them leaves unread alone.

- One read: `readVisibleSessionActivityAt` (`src/gateway/session-row-transcript-backfill.ts`), a thin wrapper over the existing bounded row-transcript read (`backfillSessionRowTranscriptFields`).
- Gateway run end: `persistPreparedGatewaySessionLifecycleEvent` passes the time into the lifecycle patch (`visibleActivityAt`); `projectSessionLifecyclePatch` applies it on terminal events.
- Agent-command run end (Gateway `agent` runs and `openclaw agent --local`): `updateSessionStoreAfterAgentRun` reads the same fact; a visible reply also ends a snooze, as before.
- Nothing is written in the transcript append path.
- Channel inbound messages and background/cron results keep their existing stamping (they add a visible row themselves).

Removed:
- the run-end `controlUiVisible` stamp and `controlUiVisible` on lifecycle events, which only fed it;
- agent-command `touchActivity`, its internal-event and coordination special cases;
- the lifecycle-event unread recomputation in `buildGatewaySessionSnapshot`;
- `session-store.snooze.test.ts`, which asserted the removed `touchActivity` parameter (snooze is covered in `session-unread.test.ts`).

Production line delta (excluding tests, docs and test inventories): **+44 / −27 (net +17)**. The read is one helper with two call sites; the per-run special cases it replaces were smaller than the read and its plumbing.

## What the user sees

- A turn that ends in `NO_REPLY`, a quiet heartbeat, an internal wake, or a parent answering its child's `sessions_send` no longer lights the unread dot.
- A visible reply, a channel message, or a delivered cron/background result still does. A visible reply still wakes a snoozed session.

## Accepted edge cases

- Incognito sessions: their transcripts stay in the Gateway process, so the run end has no stored row to read and their replies no longer mark them unread. You are usually in an incognito chat while it runs.
- A reply that is only an image (no text) has no row preview, so it does not mark the chat unread.
- CLI-backend runs (`claude-cli` and similar) persist their transcript after the agent-command run end, so `openclaw agent --local` with a CLI backend does not mark unread from that writer. I did not verify whether the Gateway lifecycle run end sees a Gateway CLI run's reply.
- A visible reply whose stored event is over 64 KiB has no row preview, so it does not mark the chat unread (the preview read is size-bounded so it can run at every run end).
- The run end adds one bounded transcript read per terminal run (the same read the sidebar row owner already does).

## Evidence

- `src/shared/session-unread.test.ts` (rewritten) appends real rows to a SQLite transcript and runs the real agent-command run end:
  - stays read and snoozed after a `NO_REPLY` wake turn, a quiet heartbeat, and a parent's reply to a child's `sessions_send` (built through the run writer's display projection). **Red on base** (base stamps every run).
  - turns unread and ends the snooze after a visible reply;
  - inbound channel message unread, internal wake read (unchanged from openclaw#204143).
- `src/gateway/session-lifecycle-state.test.ts`: a visible run that ends without a new visible reply leaves `lastActivityAt` alone. **Red on base.**
- `src/cron/isolated-agent/destination-completion.test.ts` (unchanged): a delivered cron result still stamps the destination.
- PostgreSQL conformance, full suite, locally against PostgreSQL 16 (pgvector pg16 image from CI): `server-database-engine-cron.postgres.test.ts`, which failed on openclaw#204209, passes. `client-credential-update.test.ts` and `git-backup.postgres.test.ts` fail locally the same way on the merge base (local environment, not this change).
- `pnpm check:changed`: typecheck, lint and guards pass. The dead-export scan fails on three exports this PR does not touch (also on `main`).
- Real-Gateway Control UI E2E (throwaway, not committed; only the model provider is scripted; dist build): two chats each get an `agent` turn with a hidden heartbeat input while the browser shows a third chat. The first reply is `NO_REPLY`, the second visible.
  - Base: **fails**, the `NO_REPLY` chat shows an unread dot.
  - Head: **passes**, the `NO_REPLY` chat stays read; the visible-reply chat shows a dot. Screenshots in a PR comment.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unread follows run visibility, not visible content (NO_REPLY and quiet wakes still mark unread)

1 participant