@micha.bigler/ui-core-micha 2.18.0 → 2.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/WORK_ORDERS.md CHANGED
@@ -28,7 +28,9 @@ prefixed ID; never reuse a bare flat number across workstreams.
28
28
  | NOTIF-6 | NotificationsProvider + bell on canonical dcm feed/* API | Single-WS-owner `NotificationsProvider`/`useNotifications` (initial REST seed via `feedApi.js` + one `/ws/notifications/` socket, reconnect w/ backoff) + generic MUI `NotificationBell`; additive exports only | 2026-07-27 | done | 6c63fb9 | Codex-built direct (no nesting), independent `reviewer`: single-WS-owner invariant traced clean (no way to break it — `authenticated`/`replaceNotifications`/`refresh` all referentially stable across unrelated re-renders, re-render test is genuine not a no-op). R1 (P2, real bug): the `notification.status` WS handler patched item flags but never adjusted `unreadCount`, so the badge went stale after a cross-tab/cross-device mark — the test had locked in the stale count as expected behavior. Fixed: delta computed from before/after unread state on the WS patch path, mirroring `mark()`'s own logic; test corrected + a new cross-tab regression test added. 57 passing, build clean. No new npm dependency. Full history + backend contract: dcm's `WORK_ORDERS.md`/`docs/design/notifications-platform.md`. Publishes ucm 2.11.0 |
29
29
  | NOTIF-13 | Layer-1 transport extraction (pluggable realtime) | Extract the socket out of `NotificationsProvider` into a generic **subscribe-by-envelope** realtime primitive (shipped API: `useRealtime() -> subscribe(envelope, handler)`; the WO said "by message-type", but routing is on the `envelope` discriminator, deliberately NOT on the overloaded `type` field — that overload was the bug) so a second domain (messaging) can ride the same socket; the catch-all that turns every non-`notification.status` message into a feed entry is replaced by explicit dispatch with unknown types ignored. Additive: `NotificationsProvider` stays the sole mount point, its context value unchanged. Full spec: [work-orders/NOTIF-13.md](work-orders/NOTIF-13.md). | 2026-07-29 | done | ucm: 7a83ee9; dcm: de77335 | Tier 2 (cockpit consumes `NotificationsProvider` at 2.12.0 in prod). Phase A, the hinge: unblocks NOTIF-15 (jg bell adoption) and is the substrate for Phase B messaging. Canonical register row: django-core-micha `WORK_ORDERS.md`. Operator decision 2026-07-29: additive only, NO standalone `RealtimeProvider` apps must mount. Scope E (envelope contract + helper + doc) also touches dcm; note that the roadmap wording "dcm multi-stream consumer" overstates it — `push_to_users`/`NotificationConsumer` are already stream-agnostic. Codex failed twice on this WO with a genuine CLI/model-version error (`gpt-5.6-terra requires a newer version of Codex`), not a transient issue — orchestrator fell back to direct Claude implementation per the Codex→Claude fallback rule. Independent `reviewer` (sec_reviewer not required per WO): found R1 (P2, real bug — decoupling the REST seed from the socket connect opened a race where a live push arriving before the initial feed loaded would be silently discarded by `refresh()`'s unconditional `replaceNotifications()`; fixed via a `seeded` state gate restoring the exact original seed-then-connect ordering, re-verified 70/70 green), R2 (P3 — the WO's "must be called out in the CHANGELOG" has no home since ucm has no CHANGELOG.md convention at all; operator decision: document via commit message + this register entry only, no new file), R3 (register housekeeping, closed by this update). ucm full suite 70/70 + `pnpm build` clean; dcm notifications suite 92/92, full dcm suite 392/392. Published: ucm 2.13.0 (npm), dcm 2.33.0 (PyPI, verified live before this record) — no app pin bumps in this WO per spec. |
30
30
  | NOTIF-12 | Popup channel via the wizard renderer | Make `popup` a real delivery channel: extract the presentational dialog shell out of `OnboardingWizard`, render popup-eligible notifications through it, and record seen/dismissed on `NotificationRecipient` (design D-F7: renderer reuse only, NOT the onboarding progress store); dcm `PopupDispatcher` stops being a logging stub. Full spec: [work-orders/NOTIF-12.md](work-orders/NOTIF-12.md). | 2026-07-29 | done | ucm: c8e222f, d7bdcbe; dcm: django-core-micha 1612429, 82fd89f | Tier 2 (extracts a renderer cockpit+jg run in production; the roadmap label "uncritical" is about urgency, not blast radius). **HARD GATE: starts only after NOTIF-13 landed + published** — consumes its envelope contract and `subscribe()`, and edits the same ucm files (AGENTS.md overlap rule). **SHIPS WITH ZERO PRODUCERS, deliberately** (operator decision 2026-07-29, made with the evidence): no notification type declares `popup` in `eligible_channels` anywhere in dcm/jg/cockpit/hram/spesix/survey_app, so the channel is wired but inactive until an app opts a type in. WO therefore requires (a) CHANGELOG wording that does not overclaim (NOTIF-4 R1 precedent) and (b) a test-local producer type proving the path end-to-end, so it is not untested dead code. Was NOTIF-11 (renumbered 2026-07-29 for the jg cutover/drop split). **Gate satisfied 2026-07-30** (ucm 2.13.0 / dcm 2.33.0); WO re-verified against the landed NOTIF-13 code and corrected in `345631d`: NOTIF-13 shipped the envelope as a **domain**-level discriminator, so a popup payload built the same way as a chip payload would be indistinguishable from it - the WO now mandates a `channel` field inside the envelope (never a second envelope value) plus feed de-duplication by `notification_id`, without which chip+popup double-counts the unread badge. **Codex failed twice with the same genuine CLI/model-version error as NOTIF-13** (`gpt-5.6-terra requires a newer version of Codex`) — orchestrator implemented directly in Claude per the Codex→Claude fallback rule, both scopes. Independent `reviewer` (background agent, `fork_context=false`, full diff of both repos): found R1 (P1, real bug — the WS payload only carried `notification_id`, but `feed/mark/` resolves ids against `NotificationRecipient.pk`; every `markSeen`/`markDismissed` from a session-live-only popup would either no-op or corrupt an unrelated recipient row once a producer opts in — fixed by adding `recipient_id` to both `ChipDispatcher` and `PopupDispatcher` payloads, dcm-side, with regression tests), R2 (P2 — the reused dialog shell always showed the onboarding "Setup"/step-counter header even for a popup, a real mislabeling once any producer exists — fixed via an optional `title` override on `WizardDialogShell`, defaulting to the prior exact text so `OnboardingWizard` stays bit-for-bit unchanged; popup now shows its own notification title), R3 (P2 — coexistence only gated on a *blocking* onboarding step, so a non-blocking step (e.g. `browser_push`) and a popup could stack two simultaneous MUI dialogs — fixed by broadening the gate to any active onboarding step, with a new regression test). All three fixed and re-verified: ucm 88/88 vitest + `pnpm`/tsc build clean, dcm 95/95 pytest (notifications package). Published (once pushed): ucm 2.14.0 (npm, CI-gated on push to `main`), dcm 2.34.0 (PyPI, same). No app pin bumps in this WO per spec. Own orchestrator security/exposure pass in parallel with the reviewer: no findings (content rendering follows the existing `NotificationBell` i18n-interpolation pattern, no new WS consumer, `prefs.py`/`router.py`/`resolve_channels` untouched). |
31
- | DX-1 | Minimal Vite dev harness for ucm components | Give ucm a way to **render** its components during development: a `dev` script starting a Vite dev page that mounts surfaces with the repo's MUI theme, i18n and router context, driven by fixtures through an injectable mock API/realtime adapter, with light/dark and viewport switching. Harness code stays out of the published package (not exported, excluded from the build, zero runtime deps). | 2026-07-31 | done | 7ea7b26 | New `DX-*` prefix (ucm-local). Envelope: [work-orders/DX-1.md](work-orders/DX-1.md). Tier 1, but **adds devDependencies → approval-gated**; operator approval granted 2026-07-31 as part of the MSG-3 scoping decision. Gap found while scoping MSG-3: `package.json` had only `build` (tsc) and `test` (vitest) — no Storybook, no demo, no dev page, so every ucm surface ever shipped (auth, onboarding, notifications, charts) was verified only in jsdom or after a consuming app pinned it. Storybook deliberately not chosen (config surface vs. a repo with no story-writing habit). **Runs before MSG-3**, which is ~3700 LOC of UI with no consumer until MSG-5 and an operator-granted redesign licence that is only iterable if the result can be looked at. No version bump, no publish (dev-only). **Implemented (Codex, one pass):** `pnpm dev` (`vite`) boots a harness (`dev/main.jsx`) with MUI theme/i18n/router, light/dark + mobile/tablet/desktop switching, entries for a notifications surface (`NotificationBell`) and a standalone chart (`BarChart`, proving single-component mounting), plus a dedicated realtime-adapter demo entry. Mock transport (`dev/mockTransport.jsx`) overrides `apiClient`'s axios adapter for REST and provides a `RealtimeContext.Provider` for context-consuming components. Independent `reviewer`: one P2 — `NotificationsProvider` opens its own WebSocket internally rather than reading one from context, so the notifications entry opened a real, always-failing socket; fixed by the orchestrator with a `MockWebSocket` class registered as `window.WebSocket` while the harness is mounted, covering both consumption paths. Verified in the browser (both entries, dispatch button, no console errors/WS connection attempts). Build clean, `dist/` unaffected, `dependencies`/`peerDependencies` untouched (only `devDependencies` + `scripts.dev`), 104/104 tests green. |
31
+ | DX-1 | Minimal Vite dev harness for ucm components | Give ucm a way to **render** its components during development: a `dev` script starting a Vite dev page that mounts surfaces with the repo's MUI theme, i18n and router context, driven by fixtures through an injectable mock API/realtime adapter, with light/dark and viewport switching. Harness code stays out of the published package (not exported, excluded from the build, zero runtime deps). | 2026-07-31 | done | 7ea7b26 | New `DX-*` prefix (ucm-local). Envelope: [work-orders/DX-1.md](work-orders/DX-1.md). **Tier 2** (reclassified 2026-08-01 — it adds dependencies in a shared-core repo, two binding Tier-2 surfaces per AGENTS.md Tiering; a named independent `reviewer` did run, so only the label was wrong). **Adds devDependencies → approval-gated**; operator approval granted 2026-07-31 as part of the MSG-3 scoping decision. Gap found while scoping MSG-3: `package.json` had only `build` (tsc) and `test` (vitest) — no Storybook, no demo, no dev page, so every ucm surface ever shipped (auth, onboarding, notifications, charts) was verified only in jsdom or after a consuming app pinned it. Storybook deliberately not chosen (config surface vs. a repo with no story-writing habit). **Runs before MSG-3**, which is ~3700 LOC of UI with no consumer until MSG-5 and an operator-granted redesign licence that is only iterable if the result can be looked at. No version bump, no publish (dev-only). **Implemented (Codex, one pass):** `pnpm dev` (`vite`) boots a harness (`dev/main.jsx`) with MUI theme/i18n/router, light/dark + mobile/tablet/desktop switching, entries for a notifications surface (`NotificationBell`) and a standalone chart (`BarChart`, proving single-component mounting), plus a dedicated realtime-adapter demo entry. Mock transport (`dev/mockTransport.jsx`) overrides `apiClient`'s axios adapter for REST and provides a `RealtimeContext.Provider` for context-consuming components. Independent `reviewer`: one P2 — `NotificationsProvider` opens its own WebSocket internally rather than reading one from context, so the notifications entry opened a real, always-failing socket; fixed by the orchestrator with a `MockWebSocket` class registered as `window.WebSocket` while the harness is mounted, covering both consumption paths. Verified in the browser (both entries, dispatch button, no console errors/WS connection attempts). Build clean, `dist/` unaffected, `dependencies`/`peerDependencies` untouched (only `devDependencies` + `scripts.dev`), 104/104 tests green. |
32
32
  | MSG-3 | ucm messaging surfaces (full parity) | `MessagingProvider` + API adapter + normalized cache, `ConversationList`/`Thread`/`Composer`/`ReadTicks`/`ReactionBar`/`PollCard`/`AttachmentList` + config/preferences and launchers, on the Layer-1 transport (`subscribe('messaging', …)`, `event_id` dedup, reconnect refetch); opaque-cursor pagination with reverse infinite scroll and optimistic send from day one; de/en/fr. Host apps supply routing/display/scope pickers, not a forked state machine. | 2026-07-31 | done | affa5ac, 5e87315, a12c9c6, c7100b1, 95b69d4, 974e24c, 4369400 | ucm-side mirror of the canonical dcm `MSG-3` row. Envelope: [work-orders/MSG-3.md](work-orders/MSG-3.md). Tier 2, 5 proposed chunks (register's "3-5" treated as a floor — jg's parity target is ~3700 LOC excluding tests, `Thread.jsx` alone 2470). Two operator decisions 2026-07-31: (1) **redesign permitted** for layout/composition/interaction, but the design's "No jg feature is lost" stays binding and the WO must ship a written **deviation list** — consequence: MSG-5 becomes a visible change for jg users and needs its own UX review; (2) validation runs through the **DX-1** harness, which is therefore a precondition. Carries `ui_reviewer` at WO end in addition to the per-chunk independent `reviewer`. **Decomposition is a binding requirement, not a preference:** jg's UI is one 2470-LOC component with a 2173-LOC test file, and reproducing that shape is a scope violation even with every feature present — each named component is separately exported, independently mountable and independently testable, state lives in the provider rather than being prop-drilled through `Thread`, every component gets its own DX-1 harness entry (the forcing function — a monolith cannot be mounted piecewise), and any component file above ~400 LOC must be justified in that chunk's review. Depends on dcm 2.36.1 (MSG-2 + MSG-2b). **All 5 chunks implemented, independently reviewed and committed** (chunk 1: additive Layer-1 `onReconnect` extension per operator decision, provider/cache/transport; chunk 2: conversation list + launchers, R1 menu-anchor fix, R2 per-kind icon, R3 broadcast-launcher visibility; chunk 3: Thread/MessageBubble/ReadTicks, R1 N+1 ReadTicks gating fix; chunk 4: Composer/attachments, R1 `extractApiErrorMessage` for dcm's `{files:[...]}` shape, R2 optimistic sender, R3 own-message pending-ReadTicks fix, R4 i18n diacritics; chunk 5: reactions/polls/scope-config/announcements, R1-R4 + a follow-up verification pass V1-V3 including building jg's previously-missing `AnnouncementDialog` parity per explicit operator decision). **WO-end `ui_reviewer`** (independent, full assembled feature not one chunk's diff): found U1-U5, all P2/P3, none blocking — raw-`<button>` reply action instead of MUI `Button` (U1), PollCard packed into the same wrapping flex row as reaction chips instead of its own full-width row (U2), MessagingScopeConfig's text-only loading state instead of the package's `CircularProgress` convention (U3), a raw inline-style attachment thumbnail instead of theme spacing (U4), and `MessageBubble`/`ConversationLaunchers` missing their required DX-1 harness entries (U5). All five fixed by the orchestrator (`974e24c`), re-verified 139/139 tests + clean build. Translation coverage, dark-mode tokens, deviation-doc accuracy and primitive reuse checked clean, no findings. Published: **ucm 2.16.0** (npm, CI-gated on push to `main`, `4369400`). No CHANGELOG.md in this repo (same as noted in NOTIF-13/NOTIF-12) — documented via commit messages + this register entry only. No app pin bumps in this WO. |
33
33
  | MSG-3b | Close the MSG-3 parity and contract gaps | Capability-checklist WO closing what MSG-3 missed: the entire unread lifecycle (mark-read never called — badges once raised never clear), message edit/delete + action menu, the DM launcher (`createDirectConversation` had no caller — the case MSG-2b unblocked in the backend), broken reply grouping (`serialize_message` emits `reply_to_id`, `Thread.jsx:40,62` reads `reply_to`, so every server-loaded reply renders as a root), quoted reply previews + jump-to-original, copy, client-side image compression, staged-image previews, upload progress, composer emoji insertion, relative timestamps, active-row highlight, announcement deep-link rendering. Plus a contract-conformance test and a corrected deviation list. | 2026-07-31 | done | c164db3, db8cd92, 61ed3b8, 7253172, fadb60a, 646fd01, 9748aca | Extends the landed MSG-3 (2.16.0), convention as MSG-2b/NOTIF-8b. Envelope: [work-orders/MSG-3b.md](work-orders/MSG-3b.md). Tier 2. **Origin: a three-way audit** (jg capability baseline / ucm wired-vs-adapter-only inventory / dcm contract-coverage sweep) run after MSG-3 was marked done. MSG-3 had 139/139 green, five per-chunk reviews and a clean `ui_reviewer`, and still missed all of it — **because both sides were tested against themselves**: dcm against its services, ucm against a mock whose surface mirrors the provider rather than the contract, so an endpoint with no caller is structurally invisible. Second cause: "no jg feature is lost" was made binding without anyone writing the feature list first, and the deviation list meant to prove parity was authored by the party doing the work; its "Final parity confirmation" section claims completeness and is demonstrably false. This WO's checklist IS the spec (59 rows, each OK/DEV/MISSING/BROKEN/PARTIAL/BLOCKED; the review corrected one false OK — row 5, unread never live-updates at all); the contract-conformance test is the systemic fix. **Rows 38, 51-53, 56-58 are BLOCKED on dcm** (`MSG-2c`, not yet cut): no `serialize_poll` exists at all so `PollCard` reads fields no endpoint returns — and the design specifies no poll read path either, so `messaging-platform.md` must be amended first; `services.py` has 3 `_publish` call sites for 12 designed frames, so reaction/poll live sync cannot work; `serialize_conversation` omits `last_message`, so the list preview is permanently empty. Carries `ui_reviewer` at WO end, which must check the corrected deviation list against the checklist row by row. **All 6 chunks implemented, independently reviewed and committed** (chunk 1: unread lifecycle end-to-end + contract-conformance test, own-fix for a markThreadRead failure silently blocking thread-open; chunk 2: `reply_to`/`reply_to_id` fix + quoting/jump-to-original, row 27 found and recorded BLOCKED (no dcm thread-receipt read path) after an independent-review P1 caught it being silently dropped first time; chunk 3: message action menu/edit/delete/copy with a host-supplied moderator capability prop (dcm exposes no server-side capability field), fixed an undefined-vs-undefined author-match bug; chunk 4: `DirectMessageLauncher` wiring `createDirectConversation`, fixed jest-dom-matcher and MUI-dialog-transition-timing test issues after Codex's own verification pass died without a `RESULT:` line; chunk 5: composer shortcuts/previews/compression/emoji, fixed Codex settling for indeterminate-only upload progress by threading real `onUploadProgress` through the adapter as the WO asked, fixed missing diacritics in new translations (same bug class caught once before in MSG-3), corrected an unverified poll/attachment-mutual-exclusivity claim before it could land in the deviation doc; chunk 6: list/timeline polish (relative timestamps, auto-scroll, announcement links, DM sender-suppression, read-receipt popover) plus the full deviation-doc rewrite against all 59 checklist rows — fixed a repeat of an already-once-fixed raw-interactive-element pattern, corrected an overclaiming doc line, fixed a stale-ref edge case in auto-scroll). Row 42 (managed all-vs-team) also verified genuinely BLOCKED — dcm has `external_key` but never serializes it. **WO-end `ui_reviewer`** (independent, row-by-row cross-check of `docs/messaging-deviations.md` against landed code for all 59 checklist rows, per the WO's binding "the review that signed off the false completeness claim is the one this WO exists to correct" instruction): no findings — every OK/DEV/BLOCKED row verified against actual code, not against the doc's own claims; translation coverage, DX-1 harness coverage, design-system/dark-mode/reuse all checked clean. Published: **ucm 2.17.0** (npm, CI-gated on push to `main`, `9748aca`). No CHANGELOG.md in this repo (same as NOTIF-12/NOTIF-13/MSG-3) — documented via commit messages + this register entry only. No app pin bumps in this WO. |
34
- | MSG-3c | Deliver the rows MSG-3b left blocked against a stale dcm version | Seven checklist rows (38, 51-53, 56-58) that MSG-3b correctly refused to fake against dcm 2.36.1, and which dcm 2.37.0 made buildable **while MSG-3b was still running**: real last-message preview + list reorder/preview refresh, full `PollCard` rendering (question / options / `vote_count` / `voters` / closed state), and the `reaction` / `poll_updated` frame handlers that stop being dead code. Plus the deviation-doc correction and a conformance-test extension requiring every BLOCKED entry to carry a dependency version pin. | 2026-07-31 | in-review | 84cc3c2, 5dd4d3a, 733588a | Envelope: [work-orders/MSG-3c.md](work-orders/MSG-3c.md); canonical row in dcm's register. Extends the landed MSG-3b (2.17.0). **Root cause — third occurrence of one pattern in this workstream:** the WO-end `ui_reviewer` cross-checked all 59 rows against *ucm's* landed code and took the dependency's state from the WO text instead of reading dcm, so seven rows closed as "blocked on a future dcm work order" that had already shipped. New rule this WO adds: a BLOCKED row is re-verified against the live dependency **at WO close, not at WO start**, and every BLOCKED entry names the version it was blocked at. MSG-3b already did the version-pinning unprompted — that pin is the only reason the staleness was a two-minute check rather than surfacing at MSG-5. Rows 27 and 42 stay correctly BLOCKED, on dcm `MSG-2d`. Highest latent risk: rows 56/57 are handler paths that have **never** run against a real frame, so treat them as new code under test rather than as working code being unblocked; and poll tests must use server-shaped payloads (`serialize_poll` output), since client-shaped fixtures are what let the `reply_to_id` bug survive MSG-3. **Codex was out of credits for this entire WO** (verified: every invocation returned only a workspace-credits error, no work done) — all three chunks implemented directly by the orchestrator per the Codex→Claude fallback rule, with mandatory independent review on every chunk (author ≠ reviewer). **Chunk 1** (rows 38/58): fixed a real bug found while scoping — `ConversationList` read `last_message.body`, but dcm's `serialize_last_message` only ever returns `.excerpt` — plus a defensive fix to `applyFrame`'s `message_edited` keying (reviewer found my initial bug analysis incomplete: dcm always attaches a full `frame.message`, so the fix is a no-op against the real wire contract but kept as genuine defensive robustness; the regression test was rewritten to use the real enriched frame shape instead of a fabricated minimal one). **Chunk 2** (rows 51-53): fixed `PollCard` reading non-existent `created_by`/`selected`/`voted` fields (real fields: `created_by_id`, `voted_option_ids` — the latter present only on the vote/create/close REST responses, never in `serialize_poll` or the `poll_updated` frame); found and fixed the same "frame wholesale-replaces viewer-specific state" defect class in `poll_updated`'s own handler ahead of chunk 3's explicit scope. **Chunk 3** (rows 56/57 + WO deliverables): found and fixed the identical defect in the `reaction` frame handler and `toggleReaction`'s REST-confirm path (dcm's `serialize_reactions` never returns a per-viewer `reacted` flag; both call sites were wholesale-replacing and silently wiping known reacted state); extended the contract-conformance test with the WO's new BLOCKED-version-pin rule plus a required negative-case test; rewrote `docs/messaging-deviations.md` (rows 38/51/53/56-58 → OK, row 52 → DEV, rows 27/42 stay BLOCKED with the new version pin, substance untouched). Status `in-review`, not yet `done`: WO-end `ui_reviewer` pass (per the WO's changed instruction — cross-check BLOCKED rows against dcm's *current* version) and the version-bump/publish step are still outstanding. |
34
+ | MSG-3c | Deliver the rows MSG-3b left blocked against a stale dcm version | Seven checklist rows (38, 51-53, 56-58) that MSG-3b correctly refused to fake against dcm 2.36.1, and which dcm 2.37.0 made buildable **while MSG-3b was still running**: real last-message preview + list reorder/preview refresh, full `PollCard` rendering (question / options / `vote_count` / `voters` / closed state), and the `reaction` / `poll_updated` frame handlers that stop being dead code. Plus the deviation-doc correction and a conformance-test extension requiring every BLOCKED entry to carry a dependency version pin. | 2026-07-31 | done | 84cc3c2, 5dd4d3a, 733588a, 170ce1e | Envelope: [work-orders/MSG-3c.md](work-orders/MSG-3c.md); canonical row in dcm's register. Extends the landed MSG-3b (2.17.0). **Root cause — third occurrence of one pattern in this workstream:** the WO-end `ui_reviewer` cross-checked all 59 rows against *ucm's* landed code and took the dependency's state from the WO text instead of reading dcm, so seven rows closed as "blocked on a future dcm work order" that had already shipped. New rule this WO adds: a BLOCKED row is re-verified against the live dependency **at WO close, not at WO start**, and every BLOCKED entry names the version it was blocked at. MSG-3b already did the version-pinning unprompted — that pin is the only reason the staleness was a two-minute check rather than surfacing at MSG-5. Rows 27 and 42 stay correctly BLOCKED, on dcm `MSG-2d`. Highest latent risk: rows 56/57 are handler paths that have **never** run against a real frame, so treat them as new code under test rather than as working code being unblocked; and poll tests must use server-shaped payloads (`serialize_poll` output), since client-shaped fixtures are what let the `reply_to_id` bug survive MSG-3. **Codex was out of credits for this entire WO** (verified: every invocation returned only a workspace-credits error, no work done) — all three chunks implemented directly by the orchestrator per the Codex→Claude fallback rule, with mandatory independent review on every chunk (author ≠ reviewer). **Chunk 1** (rows 38/58): fixed a real bug found while scoping — `ConversationList` read `last_message.body`, but dcm's `serialize_last_message` only ever returns `.excerpt` — plus a defensive fix to `applyFrame`'s `message_edited` keying (reviewer found my initial bug analysis incomplete: dcm always attaches a full `frame.message`, so the fix is a no-op against the real wire contract but kept as genuine defensive robustness; the regression test was rewritten to use the real enriched frame shape instead of a fabricated minimal one). **Chunk 2** (rows 51-53): fixed `PollCard` reading non-existent `created_by`/`selected`/`voted` fields (real fields: `created_by_id`, `voted_option_ids` — the latter present only on the vote/create/close REST responses, never in `serialize_poll` or the `poll_updated` frame); found and fixed the same "frame wholesale-replaces viewer-specific state" defect class in `poll_updated`'s own handler ahead of chunk 3's explicit scope. **Chunk 3** (rows 56/57 + WO deliverables): found and fixed the identical defect in the `reaction` frame handler and `toggleReaction`'s REST-confirm path (dcm's `serialize_reactions` never returns a per-viewer `reacted` flag; both call sites were wholesale-replacing and silently wiping known reacted state); extended the contract-conformance test with the WO's new BLOCKED-version-pin rule plus a required negative-case test; rewrote `docs/messaging-deviations.md` (rows 38/51/53/56-58 → OK, row 52 → DEV, rows 27/42 stay BLOCKED with the new version pin, substance untouched). **WO-end `ui_reviewer`** (independent, re-derived rows 27/42 against dcm's actual committed `HEAD`, not the WO text or the doc's own claims, per this WO's own corrective rule): no findings — dcm's committed state is still 2.37.0 (a naive check of dcm's working tree showed 2.38.0, but that's uncommitted `MSG-2d` WIP from a concurrent session, not the published state); rows 27/42 confirmed genuinely still BLOCKED at the real committed version; all seven newly-delivered rows spot-checked against dcm's committed serializers/services directly, all match. Flagged for awareness, not actionable now: dcm's uncommitted `MSG-2d` WIP (external_key, thread-receipt read path) will very likely unblock rows 27/42 once committed and published — a future `MSG-3d` candidate. Published: **ucm 2.18.0** (npm, CI-gated on push to `main`, `170ce1e`). No CHANGELOG.md in this repo (same as MSG-3/MSG-3b/NOTIF-12/NOTIF-13) — documented via commit messages + this register entry only. No app pin bumps in this WO. |
35
+ | MSG-3d | The last two blocked rows: unread-reply marker and managed-conversation identity | Deliver checklist rows **27** (unread-reply marker on the thread toggle, from `reply_count`/`last_reply_at` plus the REST-only `thread_last_read_at`) and **42** (surface `external_key` so a host can distinguish managed conversations — ucm must NOT know that `event_all`/`event_team` mean anything, that is jg vocabulary). Deviation doc reaches **zero** BLOCKED entries. | 2026-08-01 | done | 6708ec8, 0701489, f614277 | Envelope: [work-orders/MSG-3d.md](work-orders/MSG-3d.md); canonical row in dcm's register. Extends MSG-3c (2.18.0). Unblocked by dcm 2.38.0 (MSG-2d), verified in `serializers.py` before authoring rather than assumed. **Carries a named trap:** `thread_last_read_at` is viewer-specific and REST-only while `reply_count`/`last_reply_at` ride `serialize_message` and therefore the `message`/`message_edited` frames — so every such frame carries the projection *without* the receipt. That is the **fourth** field of the exact shape whose merge behaviour caused three live bugs in MSG-3c; the field-wise-merge obligation is now in design §Realtime and has a mandatory test here. Second named risk: jg vocabulary leaking into a consumer-agnostic package via row 42, with its own assertion. **Tier 2** (raised from Tier 1 on review — the change lands in the frame-merge code where MSG-3c found three shipped bugs; size does not lower review sensitivity), independent `reviewer` + `ui_reviewer` at WO end. Review also surfaced a plan gap now closed in the envelope: a new reply arrives as its own `message` frame and does NOT update the root's counters, so the root must be incremented client-side or the marker only appears after a refetch (jg does this live). **Closes the post-audit remediation** — after this every MSG-3b checklist row is implemented or a recorded deliberate deviation, and MSG-5 is unblocked. **Codex out of credits again** (fourth consecutive WO in this workstream) — implemented directly, independent review mandatory and run. Fixed a real bug while implementing: `markReplyThreadRead` fired the REST read call and discarded the response entirely, so the receipt was never actually cached client-side before this WO. Own review caught a TDZ crash (a `useCallback` dependency array referencing `patchMessage` before its declaration — dependency arrays evaluate eagerly, unlike the deferred callback body) before the independent reviewer ever saw it. Independent `reviewer`: R1 (P2) — the live-root-update test only proved the marker's visibility, which can't distinguish "still read" from "receipt silently wiped"; added a dedicated assertion on the receipt's own value across the bump, the WO's named highest-risk path. R2 (P2) — the marker's `aria-label` sat on MUI's `Badge` wrapper, which spreads unrecognized props onto a non-interactive `span` a screen reader wouldn't focus; moved onto the inner `Button`. R3 (P3) — a dead client-shaped `reply_to` fallback had crept into the new root-bump code despite the WO's explicit warning against it; removed. R4 (P3) — documented in code that the deliberate absence of self-send-marker suppression relies on dcm excluding the sender from live WS fan-out, an unstated cross-repo invariant. **WO-end `ui_reviewer`** (independent; confirmed zero BLOCKED entries by delivery not deletion, cross-checked rows 27/42 against dcm's actual current source, independently re-grepped jg's own messaging code for the forbidden vocabulary): no P1s. Two P2 harness gaps — `messagingHarnessApi` in `dev/entries.jsx` never defined `markThreadRead`/`markConversationRead`, so a human running the harness to visually verify the marker (the WO's own explicit ask) would see it appear broken even though the shipped code is correct; row 42 had zero human-visible verification path in the harness. Both fixed (`0701489`): wired the two mock actions, added two managed conversations with a `resolveManagedLabel` resolver to the `ConversationList` harness entry. CI's publish run hit the pre-existing `NotificationsProvider.test.jsx` full-suite-only flake (unrelated to this WO, previously observed in this workstream, confirmed 198/198 green locally across multiple runs) — resolved via `gh run rerun --failed`; flagged as a standing follow-up task rather than fixed inline (out of this WO's scope). Published: **ucm 2.19.0** (npm, CI-gated on push to `main`, `f614277`). No CHANGELOG.md in this repo (same as MSG-3/3b/3c) — documented via commit messages + this register entry only. No app pin bumps in this WO. **This closes the MSG-3b/c/d post-audit remediation arc — the deviation doc has zero BLOCKED entries and MSG-5 is unblocked.** |
36
+ | MSG-3e | Per-candidate scope in `DirectMessageLauncher` | Optional `candidates[n].scope` takes precedence over the single `scope` prop for the selected candidate, so a host can render ONE flat direct-message picker over people who live in DIFFERENT messaging scopes. Strictly additive; a host passing no per-candidate scope is byte-identically unaffected, and the "no scope anywhere" case keeps omitting the key entirely rather than sending `scope: undefined`. | 2026-08-02 | planned | | Envelope + map: [work-orders/MSG-3e.md](work-orders/MSG-3e.md). Driver is jg-ferien MSG-6 (global inbox across all of a user's events; a jg DM is event-scoped, so a flat "everyone I may DM" list carries a different scope per person). Alternative was a ~90-line jg-local copy of the component — rejected under AGENTS.md reuse-before-reimplement; the need is generic to any multi-scope host. **Tier 2** because shared-core is excluded from the Tier-1 fast path regardless of diff size, not because the change is large. Named trap: a naive `scope: candidate.scope ?? scope` inside the object literal would start sending `scope: undefined` and break an existing contract. Release 2.20.0 at WO end is the precondition for jg MSG-6's pin bump. |
package/dev/entries.jsx CHANGED
@@ -61,15 +61,29 @@ function RealtimeAdapterEntry() {
61
61
  const messagingHarnessApi = {
62
62
  listConversations: async ({ cursor } = {}) => cursor
63
63
  ? ({ results: [{ id: 13, title: 'Archived planning', last_message_at: '2026-07-30T09:00:00Z' }], next_cursor: null })
64
- : ({ results: [{ id: 12, title: 'Support group', unread_count: 1, last_message_at: '2026-07-31T09:00:00Z', last_message: { excerpt: 'Can someone help?' } }], next_cursor: 'signed-next-page' }),
64
+ : ({ results: [
65
+ { id: 12, title: 'Support group', unread_count: 1, last_message_at: '2026-07-31T09:00:00Z', last_message: { excerpt: 'Can someone help?' } },
66
+ // Row 42 (MSG-3d): two managed conversations, distinguishable only via
67
+ // external_key — ucm renders whatever ConversationListEntry's
68
+ // resolveManagedLabel resolver below returns, never the raw value.
69
+ { id: 30, kind: 'managed', external_key: 'all', last_message_at: '2026-07-29T09:00:00Z' },
70
+ { id: 31, kind: 'managed', external_key: 'team', last_message_at: '2026-07-28T09:00:00Z' },
71
+ ], next_cursor: 'signed-next-page' }),
65
72
  // GET conversations/{id}/messages/ returns roots only (design §REST); replies
66
73
  // come from GET messages/{root_id}/thread/ (listThread below), never mixed in here.
74
+ // reply_count with no thread_last_read_at (MSG-3d row 27): the unread-reply
75
+ // marker on the thread toggle should render visibly by default here.
67
76
  listMessages: async (conversationId, { cursor } = {}) => cursor
68
77
  ? ({ results: [{ id: 42, conversation_id: conversationId, body: 'An older message', created_at: '2026-07-30T09:00:00Z' }], next_cursor: null })
69
- : ({ results: [{ id: 44, conversation_id: conversationId, body: 'Initial message', created_at: '2026-07-31T09:00:00Z', sender: { display_name: 'Alex' }, reply_count: 1 }], next_cursor: 'signed-older-page' }),
78
+ : ({ results: [{ id: 44, conversation_id: conversationId, body: 'Initial message', created_at: '2026-07-31T09:00:00Z', sender: { display_name: 'Alex' }, reply_count: 1, last_reply_at: '2026-07-31T09:05:00Z', thread_last_read_at: null }], next_cursor: 'signed-older-page' }),
70
79
  listThread: async (rootId) => ({ results: [{ id: 45, reply_to: rootId, body: 'A reply', created_at: '2026-07-31T09:05:00Z', sender: { display_name: 'Sam' } }], next_cursor: null }),
71
80
  getReadStatus: async () => ({ all_read: false, delivered_count: 2 }),
72
81
  getUnreadCount: async () => ({ unread_count: 1, by_conversation: { 12: 1 } }),
82
+ markConversationRead: async () => ({}),
83
+ // The response's last_read_at (MSG-3d) maps onto the root's own
84
+ // thread_last_read_at cache field — clicking "Show replies" in this harness
85
+ // should make the unread-reply marker disappear.
86
+ markThreadRead: async () => ({ last_read_at: new Date().toISOString() }),
73
87
  archiveConversation: async (id, archived) => ({ id, archived }),
74
88
  patchConversationPreferences: async (id, patch) => ({ id, ...patch }),
75
89
  createGroupConversation: async (payload) => ({ id: 20, title: payload.title || 'Opened group', kind: 'group' }),
@@ -115,6 +129,7 @@ function ConversationListEntry() {
115
129
  groupLaunchers={[{ id: 'volunteers', label: 'Open volunteers group', payload: { title: 'Volunteers', participant_ids: [1, 2] } }]}
116
130
  broadcastLauncher={{ label: 'Open announcements', payload: { scope: { kind: 'global' } } }}
117
131
  onOpen={(conversation) => setOpened(conversation)}
132
+ resolveManagedLabel={(conversation) => (conversation.external_key === 'all' ? 'Everyone' : conversation.external_key === 'team' ? 'My team' : null)}
118
133
  />
119
134
  {opened && <Typography sx={{ mt: 2 }}>Opened: {opened.title}</Typography>}
120
135
  </MessagingProvider>
@@ -31,6 +31,7 @@ export const messagingTranslations = {
31
31
  'MessagingThread.REPLYING_TO': { de: 'Antwort an {{sender}}', en: 'Replying to {{sender}}', fr: 'Réponse à {{sender}}' },
32
32
  'MessagingThread.SHOW_REPLIES': { de: '{{count}} Antworten anzeigen', en: 'Show {{count}} replies', fr: 'Afficher {{count}} réponses' },
33
33
  'MessagingThread.HIDE_REPLIES': { de: 'Antworten ausblenden', en: 'Hide replies', fr: 'Masquer les réponses' },
34
+ 'MessagingThread.UNREAD_REPLIES': { de: 'Ungelesene Antworten', en: 'Unread replies', fr: 'Réponses non lues' },
34
35
  'MessagingThread.UNKNOWN_SENDER': { de: 'Unbekannte Person', en: 'Unknown person', fr: 'Personne inconnue' },
35
36
  'MessagingThread.QUOTE_ATTACHMENT': { de: 'Anhang', en: 'Attachment', fr: 'Pièce jointe' },
36
37
  'MessagingActions.MENU': { de: 'Nachrichtenaktionen', en: 'Message actions', fr: 'Actions du message' },
@@ -5,7 +5,19 @@ import { Badge, Box, Button, CircularProgress, IconButton, List, ListItemButton,
5
5
  import { useTranslation } from 'react-i18next';
6
6
  import { useMessaging } from './MessagingProvider';
7
7
  import { ConversationLaunchers } from './ConversationLaunchers';
8
- function titleOf(conversation, t) { var _a, _b; return conversation.title || ((_a = conversation.other_user) === null || _a === void 0 ? void 0 : _a.display_name) || ((_b = conversation.other_user) === null || _b === void 0 ? void 0 : _b.username) || t('MessagingList.UNTITLED'); }
8
+ // external_key (dcm 2.38.0+) is the consuming app's own identity for a
9
+ // managed conversation — ucm must not know what any particular app's values
10
+ // mean, so a label for it is host-supplied only; resolveManagedLabel receives
11
+ // the raw conversation (including external_key) and owns all interpretation.
12
+ function titleOf(conversation, t, resolveManagedLabel) {
13
+ var _a, _b;
14
+ if (conversation.kind === 'managed' && resolveManagedLabel) {
15
+ const label = resolveManagedLabel(conversation);
16
+ if (label)
17
+ return label;
18
+ }
19
+ return conversation.title || ((_a = conversation.other_user) === null || _a === void 0 ? void 0 : _a.display_name) || ((_b = conversation.other_user) === null || _b === void 0 ? void 0 : _b.username) || t('MessagingList.UNTITLED');
20
+ }
9
21
  function ordered(conversations) {
10
22
  return [...conversations].sort((left, right) => new Date(right.last_message_at || 0) - new Date(left.last_message_at || 0));
11
23
  }
@@ -28,7 +40,7 @@ function KindIcon({ conversation }) {
28
40
  return _jsx(Person, { fontSize: "small" });
29
41
  }
30
42
  /** A standalone, provider-backed list; scope picker metadata is supplied as launcher props. */
31
- export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, autoOpenBroadcast = false, includeArchived = false }) {
43
+ export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, autoOpenBroadcast = false, includeArchived = false, resolveManagedLabel }) {
32
44
  const { t, i18n } = useTranslation();
33
45
  const { cache, activeConversationId, loadMoreConversations, setConversationArchived, setConversationPreferences, markConversationRead } = useMessaging();
34
46
  const [menuConversation, setMenuConversation] = useState(null);
@@ -77,6 +89,6 @@ export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, au
77
89
  var _a;
78
90
  const unread = unreadFor(conversation);
79
91
  const archived = Boolean(conversation.archived || conversation.archived_at);
80
- return _jsxs(ListItemButton, { selected: conversation.id === activeConversationId, onClick: () => { markConversationRead(conversation.id).catch(() => { }); onOpen === null || onOpen === void 0 ? void 0 : onOpen(conversation); }, sx: { minHeight: 64, opacity: archived ? 0.6 : 1 }, children: [_jsx(Badge, { color: "error", badgeContent: unread || null, max: 99, sx: { mr: 2 }, children: archived ? _jsx(Archive, { fontSize: "small", color: "disabled" }) : _jsx(KindIcon, { conversation: conversation }) }), _jsx(ListItemText, { primary: _jsxs(Stack, { direction: "row", spacing: 1, justifyContent: "space-between", children: [_jsx(Typography, { component: "span", fontWeight: unread ? 700 : 400, noWrap: true, children: titleOf(conversation, t) }), relativeTime(conversation.last_message_at, i18n === null || i18n === void 0 ? void 0 : i18n.language) && _jsx(Typography, { component: "span", variant: "caption", color: "text.secondary", noWrap: true, children: relativeTime(conversation.last_message_at, i18n === null || i18n === void 0 ? void 0 : i18n.language) })] }), secondary: ((_a = conversation.last_message) === null || _a === void 0 ? void 0 : _a.excerpt) || t('MessagingList.NO_MESSAGES'), secondaryTypographyProps: { noWrap: true } }), _jsx(IconButton, { "aria-label": t('MessagingList.ACTIONS'), onClick: (event) => { event.stopPropagation(); setMenuAnchor(event.currentTarget); setMenuConversation(conversation); }, children: _jsx(MoreVert, {}) })] }, conversation.id);
92
+ return _jsxs(ListItemButton, { selected: conversation.id === activeConversationId, onClick: () => { markConversationRead(conversation.id).catch(() => { }); onOpen === null || onOpen === void 0 ? void 0 : onOpen(conversation); }, sx: { minHeight: 64, opacity: archived ? 0.6 : 1 }, children: [_jsx(Badge, { color: "error", badgeContent: unread || null, max: 99, sx: { mr: 2 }, children: archived ? _jsx(Archive, { fontSize: "small", color: "disabled" }) : _jsx(KindIcon, { conversation: conversation }) }), _jsx(ListItemText, { primary: _jsxs(Stack, { direction: "row", spacing: 1, justifyContent: "space-between", children: [_jsx(Typography, { component: "span", fontWeight: unread ? 700 : 400, noWrap: true, children: titleOf(conversation, t, resolveManagedLabel) }), relativeTime(conversation.last_message_at, i18n === null || i18n === void 0 ? void 0 : i18n.language) && _jsx(Typography, { component: "span", variant: "caption", color: "text.secondary", noWrap: true, children: relativeTime(conversation.last_message_at, i18n === null || i18n === void 0 ? void 0 : i18n.language) })] }), secondary: ((_a = conversation.last_message) === null || _a === void 0 ? void 0 : _a.excerpt) || t('MessagingList.NO_MESSAGES'), secondaryTypographyProps: { noWrap: true } }), _jsx(IconButton, { "aria-label": t('MessagingList.ACTIONS'), onClick: (event) => { event.stopPropagation(); setMenuAnchor(event.currentTarget); setMenuConversation(conversation); }, children: _jsx(MoreVert, {}) })] }, conversation.id);
81
93
  }) })), cache.cursors.conversations && _jsx(Button, { onClick: loadMore, disabled: loadingMore, children: loadingMore ? _jsx(CircularProgress, { size: 18 }) : t('MessagingList.LOAD_MORE') }), _jsxs(Menu, { anchorEl: menuAnchor, open: Boolean(menuConversation), onClose: closeMenu, children: [_jsxs(MenuItem, { onClick: toggleMute, children: [_jsx(NotificationsOff, { fontSize: "small", sx: { mr: 1 } }), (menuConversation === null || menuConversation === void 0 ? void 0 : menuConversation.muted) ? t('MessagingList.UNMUTE') : t('MessagingList.MUTE')] }), _jsxs(MenuItem, { onClick: archive, children: [_jsx(Archive, { fontSize: "small", sx: { mr: 1 } }), t('MessagingList.ARCHIVE')] })] })] }));
82
94
  }
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useId, useState } from 'react';
2
+ import { useId, useMemo, useState } from 'react';
3
3
  import { Alert, Button, CircularProgress, Dialog, DialogActions, DialogContent, DialogTitle, List, ListItemButton, ListItemText, Typography, useMediaQuery, } from '@mui/material';
4
4
  import { useTheme } from '@mui/material/styles';
5
5
  import { useTranslation } from 'react-i18next';
@@ -18,6 +18,7 @@ export function DirectMessageLauncher({ candidates = [], scope, onOpen }) {
18
18
  const [starting, setStarting] = useState(false);
19
19
  const [error, setError] = useState(null);
20
20
  const titleId = useId();
21
+ const selectedCandidate = useMemo(() => candidates.find((candidate) => candidate.id === selectedId) || null, [candidates, selectedId]);
21
22
  const showPicker = () => {
22
23
  setSelectedId(null);
23
24
  setError(null);
@@ -28,12 +29,14 @@ export function DirectMessageLauncher({ candidates = [], scope, onOpen }) {
28
29
  setOpen(false);
29
30
  };
30
31
  const start = async () => {
32
+ var _a;
31
33
  if (selectedId == null || starting)
32
34
  return;
33
35
  setStarting(true);
34
36
  setError(null);
35
37
  try {
36
- const conversation = await openDirectConversation(Object.assign({ target_user_id: selectedId }, (scope == null ? {} : { scope })));
38
+ const effectiveScope = (_a = selectedCandidate === null || selectedCandidate === void 0 ? void 0 : selectedCandidate.scope) !== null && _a !== void 0 ? _a : scope;
39
+ const conversation = await openDirectConversation(Object.assign({ target_user_id: selectedId }, (effectiveScope == null ? {} : { scope: effectiveScope })));
37
40
  setOpen(false);
38
41
  onOpen === null || onOpen === void 0 ? void 0 : onOpen(conversation);
39
42
  }
@@ -99,7 +99,32 @@ export function applyFrame(state, frame, activeConversationId = null) {
99
99
  const message = Object.assign(Object.assign({}, payload), { conversation_id: conversationId });
100
100
  const requestId = clientRequestIdOf(message);
101
101
  const reconcilesOptimisticMessage = Boolean(requestId && Object.values(state.messages).some((item) => clientRequestIdOf(item) === requestId));
102
- const messages = reconcileMessage(state.messages, message);
102
+ let messages = reconcileMessage(state.messages, message);
103
+ // reply_count/last_reply_at are viewer-independent facts (serialize_message
104
+ // always includes them, live-recomputed when not annotated) — bump the
105
+ // cached root unconditionally, regardless of who sent the reply. Spread
106
+ // the existing root first and only override these two fields, never
107
+ // rebuild the object from frame data, so thread_last_read_at (REST-only,
108
+ // never present on this frame) is never wiped — the merge-trap discipline
109
+ // MSG-3c's fixes established for exactly this failure shape.
110
+ //
111
+ // No self-send suppression here: a viewer never receives a "message"
112
+ // frame for their own reply in the first place — dcm's
113
+ // resolve_live_recipients(sender=actor) excludes the sender from the
114
+ // live WS fan-out (django_core_micha/messaging/services.py), so this
115
+ // branch structurally cannot fire for the viewer's own send. That is a
116
+ // dcm-side guarantee this code relies on, not something ucm re-derives —
117
+ // if dcm's recipient exclusion ever changes, this would need revisiting.
118
+ //
119
+ // reply_to_id only, never a client-shaped reply_to fallback — a live
120
+ // "message" frame is always server-shaped (serialize_message), so a
121
+ // reply_to fallback here would be dead-code-guessing at a payload shape
122
+ // no server ever sends, exactly the kind of unverified compatibility
123
+ // guess this workstream has twice shipped as a real bug.
124
+ const rootId = message.reply_to_id;
125
+ const root = rootId != null ? messages[rootId] : null;
126
+ if (root)
127
+ messages = Object.assign(Object.assign({}, messages), { [rootId]: Object.assign(Object.assign({}, root), { reply_count: (root.reply_count || 0) + 1, last_reply_at: message.created_at || root.last_reply_at }) });
103
128
  if (conversationId == null || String(conversationId) === String(activeConversationId) || reconcilesOptimisticMessage)
104
129
  return Object.assign(Object.assign({}, state), { messages });
105
130
  const unread = state.unread || EMPTY_CACHE.unread;
@@ -228,7 +253,6 @@ export function MessagingProvider({ children, filters = {}, activeConversationId
228
253
  dispatch({ type: 'conversationRead', conversationId });
229
254
  return result;
230
255
  }, [api]);
231
- const markReplyThreadRead = useCallback((rootId, readAt) => api.markThreadRead(rootId, readAt), [api]);
232
256
  const openGroupConversation = useCallback(async (payload) => {
233
257
  const conversation = await api.createGroupConversation(payload);
234
258
  return updateConversation(conversation);
@@ -282,6 +306,17 @@ export function MessagingProvider({ children, filters = {}, activeConversationId
282
306
  }
283
307
  }, [api, user]);
284
308
  const patchMessage = useCallback((message) => dispatch({ type: 'messagePatched', message }), []);
309
+ const markReplyThreadRead = useCallback(async (rootId, readAt) => {
310
+ const result = await api.markThreadRead(rootId, readAt);
311
+ // The mark-read response's `last_read_at` maps onto the cached root
312
+ // message's `thread_last_read_at` field — different key names, same
313
+ // value; this is the only place the client ever learns this viewer's own
314
+ // thread receipt, since it's REST-only and never rides a realtime frame.
315
+ const previous = cache.messages[rootId];
316
+ if (previous && (result === null || result === void 0 ? void 0 : result.last_read_at) !== undefined)
317
+ patchMessage(Object.assign(Object.assign({}, previous), { thread_last_read_at: result.last_read_at }));
318
+ return result;
319
+ }, [api, cache.messages, patchMessage]);
285
320
  // Keep this API-backed action deliberately distinct from the cache-merge
286
321
  // helper above. The server remains the authority for author/moderator rights.
287
322
  const editMessage = useCallback(async (messageId, patch) => {
@@ -1,5 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Alert, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
2
+ import { Alert, Badge, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
3
3
  import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
4
4
  import { useTranslation } from 'react-i18next';
5
5
  import { AuthContext } from '../auth/AuthContext';
@@ -8,6 +8,17 @@ import { useMessaging } from './MessagingProvider';
8
8
  import { ReadTicks } from './ReadTicks';
9
9
  function chronological(messages) { return [...messages].sort((left, right) => new Date(left.created_at || 0) - new Date(right.created_at || 0)); }
10
10
  function replyToId(message) { var _a; return (_a = message.reply_to_id) !== null && _a !== void 0 ? _a : message.reply_to; }
11
+ // last_reply_at/reply_count are viewer-independent (always on serialize_message);
12
+ // thread_last_read_at is viewer-specific and REST-only (never on a frame — see
13
+ // MessagingProvider.jsx's applyFrame merge-trap handling). A null receipt with
14
+ // at least one reply counts as unread; no replies means no marker at all.
15
+ function hasUnreadReplies(message) {
16
+ if (!message.reply_count)
17
+ return false;
18
+ if (message.thread_last_read_at == null)
19
+ return true;
20
+ return Boolean(message.last_reply_at) && new Date(message.last_reply_at) > new Date(message.thread_last_read_at);
21
+ }
11
22
  // A still-pending optimistic row (chunk 4) has a fake `local-<requestId>` id
12
23
  // and no durable server row yet — mounting ReadTicks against it would fire a
13
24
  // getMessageReadStatus REST call for an id the server has never heard of.
@@ -105,6 +116,14 @@ export function Thread({ conversationId, onReplyTargetChange, canModerateMessage
105
116
  };
106
117
  return (_jsxs(Stack, { spacing: 1, sx: { minWidth: 0 }, children: [error && _jsx(Alert, { severity: "error", role: "alert", children: error }), replyingTo && _jsx(Alert, { severity: "info", onClose: () => { setReplyingTo(null); onReplyTargetChange === null || onReplyTargetChange === void 0 ? void 0 : onReplyTargetChange(null); }, children: t('MessagingThread.REPLYING_TO', { sender: ((_a = replyingTo.sender) === null || _a === void 0 ? void 0 : _a.display_name) || t('MessagingThread.UNKNOWN_SENDER') }) }), _jsxs(Box, { ref: scrollRef, onScroll: onScroll, sx: { maxHeight: 560, overflowY: 'auto', px: 0.5 }, "aria-label": t('MessagingThread.TIMELINE'), children: [cache.cursors.messages[conversationId] && _jsx(Box, { textAlign: "center", py: 1, children: _jsx(Button, { onClick: loadOlder, disabled: loadingOlder, children: loadingOlder ? _jsx(CircularProgress, { size: 18 }) : t('MessagingThread.LOAD_OLDER') }) }), !roots.length && _jsx(Typography, { color: "text.secondary", textAlign: "center", py: 4, children: t('MessagingThread.EMPTY') }), _jsx(Stack, { spacing: 1, children: roots.map((message) => {
107
118
  const replies = chronological(Object.values(cache.messages).filter((item) => String(replyToId(item)) === String(message.id)));
108
- return _jsxs(Stack, { spacing: 0.75, children: [_jsx(MessageBubble, { message: message, conversation: conversation, onReply: reply, onJumpToMessage: jumpToMessage, onAnnouncementLink: onAnnouncementLink, canModerateMessages: canModerateMessages, children: canShowReadTicks(message, user) && _jsx(ReadTicks, { messageId: message.id, conversation: conversation }) }), (message.reply_count || replies.length) > 0 && _jsx(Button, { size: "small", onClick: () => toggleReplies(message), children: openThreads[message.id] ? t('MessagingThread.HIDE_REPLIES') : t('MessagingThread.SHOW_REPLIES', { count: message.reply_count || replies.length }) }), openThreads[message.id] && _jsx(Stack, { spacing: 0.75, sx: { pl: 3, borderLeft: 2, borderColor: 'divider' }, children: replies.map((item) => _jsx(MessageBubble, { message: item, replyTo: message, conversation: conversation, onReply: reply, onJumpToMessage: jumpToMessage, onAnnouncementLink: onAnnouncementLink, canModerateMessages: canModerateMessages, children: canShowReadTicks(item, user) && _jsx(ReadTicks, { messageId: item.id, conversation: conversation }) }, item.id)) }), _jsx(Divider, {})] }, message.id);
119
+ return _jsxs(Stack, { spacing: 0.75, children: [_jsx(MessageBubble, { message: message, conversation: conversation, onReply: reply, onJumpToMessage: jumpToMessage, onAnnouncementLink: onAnnouncementLink, canModerateMessages: canModerateMessages, children: canShowReadTicks(message, user) && _jsx(ReadTicks, { messageId: message.id, conversation: conversation }) }), (message.reply_count || replies.length) > 0 && (() => {
120
+ const unread = hasUnreadReplies(message);
121
+ const label = openThreads[message.id] ? t('MessagingThread.HIDE_REPLIES') : t('MessagingThread.SHOW_REPLIES', { count: message.reply_count || replies.length });
122
+ // MUI's Badge spreads unrecognized props (incl. aria-label) onto
123
+ // its own non-interactive wrapping span, not the inner control —
124
+ // a screen reader focuses the Button, so the accessible name
125
+ // must live there, not on the purely-visual dot.
126
+ return _jsx(Badge, { color: "error", variant: "dot", invisible: !unread, children: _jsx(Button, { size: "small", "aria-label": unread ? `${label} — ${t('MessagingThread.UNREAD_REPLIES')}` : undefined, onClick: () => toggleReplies(message), children: label }) });
127
+ })(), openThreads[message.id] && _jsx(Stack, { spacing: 0.75, sx: { pl: 3, borderLeft: 2, borderColor: 'divider' }, children: replies.map((item) => _jsx(MessageBubble, { message: item, replyTo: message, conversation: conversation, onReply: reply, onJumpToMessage: jumpToMessage, onAnnouncementLink: onAnnouncementLink, canModerateMessages: canModerateMessages, children: canShowReadTicks(item, user) && _jsx(ReadTicks, { messageId: item.id, conversation: conversation }) }, item.id)) }), _jsx(Divider, {})] }, message.id);
109
128
  }) })] })] }));
110
129
  }
@@ -1,4 +1,4 @@
1
- # Messaging parity outcomes (MSG-3b, extended by MSG-3c)
1
+ # Messaging parity outcomes (MSG-3b, extended by MSG-3c and MSG-3d)
2
2
 
3
3
  This is the authoritative parity record for the ucm messaging surfaces. It
4
4
  replaces the former file-level “final parity confirmation,” which was not
@@ -55,7 +55,7 @@ now fails the build if a `BLOCKED` line omits one.
55
55
  24. **OK** — Replies show a sender and short quoted snippet.
56
56
  25. **OK** — Clicking a quote scrolls its source message into view.
57
57
  26. **OK** — Quotes of deleted messages render the deleted placeholder rather than stale content.
58
- 27. **BLOCKED** (blocked as of dcm 2.37.0) — dcm writes a thread receipt but exposes no prior thread receipt state, unread flag, or unread count to read. A truthful cross-device unread-reply dot cannot be rendered without a dcm contract addition. Re-verified against 2.37.0 (MSG-3c): still absent. Waits on dcm `MSG-2d`.
58
+ 27. **OK** (delivered in MSG-3d, was BLOCKED as of dcm 2.37.0) — dcm 2.38.0's `serialize_message` gains viewer-independent `reply_count`/`last_reply_at`, and `thread_last_read_at` is attached REST-only from `MessageThreadReceipt`. `Thread` shows an unread-reply marker on the thread toggle when `last_reply_at > thread_last_read_at`, treats a `null` receipt with replies as unread, and shows no marker (and no toggle) when there are no replies. Opening a thread updates the receipt from the REST response, not a frame (the field is never present on one, by design). An incoming reply's `message` frame also live-advances the cached root's `reply_count`/`last_reply_at`, merged field-wise so a previously-fetched `thread_last_read_at` is never wiped — the same merge-trap discipline MSG-3c's three fixes established, now with its own mandatory regression test.
59
59
  28. **OK** — Reply threads load lazily on expand and collapse locally.
60
60
  29. **DEV** — Reply composition is supplied through the independently mountable `Composer` target prop rather than jg’s per-thread embedded composer.
61
61
 
@@ -76,7 +76,7 @@ now fails the build if a `BLOCKED` line omits one.
76
76
  39. **OK** — `last_message_at` renders through browser-native, locale-aware `Intl.RelativeTimeFormat` labels.
77
77
  40. **OK** — The existing MUI `selected={conversation.id === activeConversationId}` wiring produces the `Mui-selected` active-row highlight; it was verified and needs no redundant styling.
78
78
  41. **OK** — Unread badges and bold unread titles are present.
79
- 42. **BLOCKED** (blocked as of dcm 2.37.0) — dcm stores the managed all/team distinction in `external_key`, but `serialize_conversation_core` still omits it from every conversation payload. The UI must not guess from titles or other unrelated fields. Re-verified against 2.37.0 (MSG-3c): still absent. Waits on dcm `MSG-2d`.
79
+ 42. **OK** (delivered in MSG-3d, was BLOCKED as of dcm 2.37.0) — dcm 2.38.0's `serialize_conversation_core` includes `external_key`. ucm does not interpret it — jg's `event_all`/`event_team` vocabulary (or any other app's) stays entirely host-side. `ConversationList` accepts an optional `resolveManagedLabel(conversation)` host resolver, called only for `kind: 'managed'` conversations, falling back to the existing title behavior when unset; no app-specific string appears anywhere in `src/` (asserted directly by test).
80
80
  43. **DEV** — Generic MUI kind icons replace jg’s richer per-kind/person avatar treatment while retaining type identification.
81
81
  44. **OK** — Mute and archive actions are present.
82
82
 
@@ -109,10 +109,10 @@ now fails the build if a `BLOCKED` line omits one.
109
109
 
110
110
  ## Required backend follow-up
111
111
 
112
- Rows 27 and 42 require a future dcm work order (`MSG-2d`): expose readable thread receipt state, and
113
- serialize `external_key` where managed all/team labeling is required. Until then, these are explicit
114
- BLOCKED outcomes, each pinned to the dcm version they were verified blocked against, rather than
115
- simulated client behavior. MSG-2c (dcm 2.37.0) already delivered what MSG-3b's own audit had recorded
116
- as blocking rows 38, 51–53 and 56–58 — MSG-3c re-verified each against the live dependency and
117
- delivered them; see those rows above for what was actually built (in three cases, fixing a real
118
- client-side bug found only once real server data was checked against, not just unblocked).
112
+ None outstanding. This checklist has **zero `BLOCKED` entries** as of MSG-3d. MSG-2c (dcm 2.37.0)
113
+ delivered what MSG-3b's own audit had recorded as blocking rows 38, 51–53 and 56–58 — MSG-3c
114
+ re-verified each against the live dependency and delivered them. MSG-2d (dcm 2.38.0) delivered what
115
+ remained blocking rows 27 and 42 — MSG-3d re-verified and delivered them the same way. Every row of
116
+ the original MSG-3b checklist is now either implemented or a recorded deliberate deviation; see the
117
+ rows above for what was actually built, including the client-side bugs found and fixed only once real
118
+ server data was checked against, not assumed from the WO text or the doc's own prior claims.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@micha.bigler/ui-core-micha",
3
- "version": "2.18.0",
3
+ "version": "2.20.0",
4
4
  "main": "dist/index.js",
5
5
  "module": "dist/index.js",
6
6
  "repository": {
@@ -31,6 +31,7 @@ export const messagingTranslations = {
31
31
  'MessagingThread.REPLYING_TO': { de: 'Antwort an {{sender}}', en: 'Replying to {{sender}}', fr: 'Réponse à {{sender}}' },
32
32
  'MessagingThread.SHOW_REPLIES': { de: '{{count}} Antworten anzeigen', en: 'Show {{count}} replies', fr: 'Afficher {{count}} réponses' },
33
33
  'MessagingThread.HIDE_REPLIES': { de: 'Antworten ausblenden', en: 'Hide replies', fr: 'Masquer les réponses' },
34
+ 'MessagingThread.UNREAD_REPLIES': { de: 'Ungelesene Antworten', en: 'Unread replies', fr: 'Réponses non lues' },
34
35
  'MessagingThread.UNKNOWN_SENDER': { de: 'Unbekannte Person', en: 'Unknown person', fr: 'Personne inconnue' },
35
36
  'MessagingThread.QUOTE_ATTACHMENT': { de: 'Anhang', en: 'Attachment', fr: 'Pièce jointe' },
36
37
  'MessagingActions.MENU': { de: 'Nachrichtenaktionen', en: 'Message actions', fr: 'Actions du message' },
@@ -6,7 +6,17 @@ import { useTranslation } from 'react-i18next';
6
6
  import { useMessaging } from './MessagingProvider';
7
7
  import { ConversationLaunchers } from './ConversationLaunchers';
8
8
 
9
- function titleOf(conversation, t) { return conversation.title || conversation.other_user?.display_name || conversation.other_user?.username || t('MessagingList.UNTITLED'); }
9
+ // external_key (dcm 2.38.0+) is the consuming app's own identity for a
10
+ // managed conversation — ucm must not know what any particular app's values
11
+ // mean, so a label for it is host-supplied only; resolveManagedLabel receives
12
+ // the raw conversation (including external_key) and owns all interpretation.
13
+ function titleOf(conversation, t, resolveManagedLabel) {
14
+ if (conversation.kind === 'managed' && resolveManagedLabel) {
15
+ const label = resolveManagedLabel(conversation);
16
+ if (label) return label;
17
+ }
18
+ return conversation.title || conversation.other_user?.display_name || conversation.other_user?.username || t('MessagingList.UNTITLED');
19
+ }
10
20
  function ordered(conversations) {
11
21
  return [...conversations].sort((left, right) => new Date(right.last_message_at || 0) - new Date(left.last_message_at || 0));
12
22
  }
@@ -27,7 +37,7 @@ function KindIcon({ conversation }) {
27
37
  }
28
38
 
29
39
  /** A standalone, provider-backed list; scope picker metadata is supplied as launcher props. */
30
- export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, autoOpenBroadcast = false, includeArchived = false }) {
40
+ export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, autoOpenBroadcast = false, includeArchived = false, resolveManagedLabel }) {
31
41
  const { t, i18n } = useTranslation();
32
42
  const { cache, activeConversationId, loadMoreConversations, setConversationArchived, setConversationPreferences, markConversationRead } = useMessaging();
33
43
  const [menuConversation, setMenuConversation] = useState(null);
@@ -68,7 +78,7 @@ export function ConversationList({ onOpen, groupLaunchers, broadcastLauncher, au
68
78
  <Badge color="error" badgeContent={unread || null} max={99} sx={{ mr: 2 }}>
69
79
  {archived ? <Archive fontSize="small" color="disabled" /> : <KindIcon conversation={conversation} />}
70
80
  </Badge>
71
- <ListItemText primary={<Stack direction="row" spacing={1} justifyContent="space-between"><Typography component="span" fontWeight={unread ? 700 : 400} noWrap>{titleOf(conversation, t)}</Typography>{relativeTime(conversation.last_message_at, i18n?.language) && <Typography component="span" variant="caption" color="text.secondary" noWrap>{relativeTime(conversation.last_message_at, i18n?.language)}</Typography>}</Stack>} secondary={conversation.last_message?.excerpt || t('MessagingList.NO_MESSAGES')} secondaryTypographyProps={{ noWrap: true }} />
81
+ <ListItemText primary={<Stack direction="row" spacing={1} justifyContent="space-between"><Typography component="span" fontWeight={unread ? 700 : 400} noWrap>{titleOf(conversation, t, resolveManagedLabel)}</Typography>{relativeTime(conversation.last_message_at, i18n?.language) && <Typography component="span" variant="caption" color="text.secondary" noWrap>{relativeTime(conversation.last_message_at, i18n?.language)}</Typography>}</Stack>} secondary={conversation.last_message?.excerpt || t('MessagingList.NO_MESSAGES')} secondaryTypographyProps={{ noWrap: true }} />
72
82
  <IconButton aria-label={t('MessagingList.ACTIONS')} onClick={(event) => { event.stopPropagation(); setMenuAnchor(event.currentTarget); setMenuConversation(conversation); }}><MoreVert /></IconButton>
73
83
  </ListItemButton>;
74
84
  })}
@@ -1,4 +1,4 @@
1
- import { useId, useState } from 'react';
1
+ import { useId, useMemo, useState } from 'react';
2
2
  import {
3
3
  Alert,
4
4
  Button,
@@ -32,6 +32,10 @@ export function DirectMessageLauncher({ candidates = [], scope, onOpen }) {
32
32
  const [starting, setStarting] = useState(false);
33
33
  const [error, setError] = useState(null);
34
34
  const titleId = useId();
35
+ const selectedCandidate = useMemo(
36
+ () => candidates.find((candidate) => candidate.id === selectedId) || null,
37
+ [candidates, selectedId],
38
+ );
35
39
 
36
40
  const showPicker = () => {
37
41
  setSelectedId(null);
@@ -46,9 +50,10 @@ export function DirectMessageLauncher({ candidates = [], scope, onOpen }) {
46
50
  setStarting(true);
47
51
  setError(null);
48
52
  try {
53
+ const effectiveScope = selectedCandidate?.scope ?? scope;
49
54
  const conversation = await openDirectConversation({
50
55
  target_user_id: selectedId,
51
- ...(scope == null ? {} : { scope }),
56
+ ...(effectiveScope == null ? {} : { scope: effectiveScope }),
52
57
  });
53
58
  setOpen(false);
54
59
  onOpen?.(conversation);
@@ -127,7 +127,31 @@ export function applyFrame(state, frame, activeConversationId = null) {
127
127
  const message = { ...payload, conversation_id: conversationId };
128
128
  const requestId = clientRequestIdOf(message);
129
129
  const reconcilesOptimisticMessage = Boolean(requestId && Object.values(state.messages).some((item) => clientRequestIdOf(item) === requestId));
130
- const messages = reconcileMessage(state.messages, message);
130
+ let messages = reconcileMessage(state.messages, message);
131
+ // reply_count/last_reply_at are viewer-independent facts (serialize_message
132
+ // always includes them, live-recomputed when not annotated) — bump the
133
+ // cached root unconditionally, regardless of who sent the reply. Spread
134
+ // the existing root first and only override these two fields, never
135
+ // rebuild the object from frame data, so thread_last_read_at (REST-only,
136
+ // never present on this frame) is never wiped — the merge-trap discipline
137
+ // MSG-3c's fixes established for exactly this failure shape.
138
+ //
139
+ // No self-send suppression here: a viewer never receives a "message"
140
+ // frame for their own reply in the first place — dcm's
141
+ // resolve_live_recipients(sender=actor) excludes the sender from the
142
+ // live WS fan-out (django_core_micha/messaging/services.py), so this
143
+ // branch structurally cannot fire for the viewer's own send. That is a
144
+ // dcm-side guarantee this code relies on, not something ucm re-derives —
145
+ // if dcm's recipient exclusion ever changes, this would need revisiting.
146
+ //
147
+ // reply_to_id only, never a client-shaped reply_to fallback — a live
148
+ // "message" frame is always server-shaped (serialize_message), so a
149
+ // reply_to fallback here would be dead-code-guessing at a payload shape
150
+ // no server ever sends, exactly the kind of unverified compatibility
151
+ // guess this workstream has twice shipped as a real bug.
152
+ const rootId = message.reply_to_id;
153
+ const root = rootId != null ? messages[rootId] : null;
154
+ if (root) messages = { ...messages, [rootId]: { ...root, reply_count: (root.reply_count || 0) + 1, last_reply_at: message.created_at || root.last_reply_at } };
131
155
  if (conversationId == null || String(conversationId) === String(activeConversationId) || reconcilesOptimisticMessage) return { ...state, messages };
132
156
  const unread = state.unread || EMPTY_CACHE.unread;
133
157
  const previousCount = unread.by_conversation?.[conversationId] || 0;
@@ -259,7 +283,6 @@ export function MessagingProvider({ children, filters = {}, activeConversationId
259
283
  dispatch({ type: 'conversationRead', conversationId });
260
284
  return result;
261
285
  }, [api]);
262
- const markReplyThreadRead = useCallback((rootId, readAt) => api.markThreadRead(rootId, readAt), [api]);
263
286
  const openGroupConversation = useCallback(async (payload) => {
264
287
  const conversation = await api.createGroupConversation(payload);
265
288
  return updateConversation(conversation);
@@ -318,6 +341,16 @@ export function MessagingProvider({ children, filters = {}, activeConversationId
318
341
  }
319
342
  }, [api, user]);
320
343
  const patchMessage = useCallback((message) => dispatch({ type: 'messagePatched', message }), []);
344
+ const markReplyThreadRead = useCallback(async (rootId, readAt) => {
345
+ const result = await api.markThreadRead(rootId, readAt);
346
+ // The mark-read response's `last_read_at` maps onto the cached root
347
+ // message's `thread_last_read_at` field — different key names, same
348
+ // value; this is the only place the client ever learns this viewer's own
349
+ // thread receipt, since it's REST-only and never rides a realtime frame.
350
+ const previous = cache.messages[rootId];
351
+ if (previous && result?.last_read_at !== undefined) patchMessage({ ...previous, thread_last_read_at: result.last_read_at });
352
+ return result;
353
+ }, [api, cache.messages, patchMessage]);
321
354
  // Keep this API-backed action deliberately distinct from the cache-merge
322
355
  // helper above. The server remains the authority for author/moderator rights.
323
356
  const editMessage = useCallback(async (messageId, patch) => {
@@ -1,4 +1,4 @@
1
- import { Alert, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
1
+ import { Alert, Badge, Box, Button, CircularProgress, Divider, Stack, Typography } from '@mui/material';
2
2
  import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
3
3
  import { useTranslation } from 'react-i18next';
4
4
 
@@ -9,6 +9,15 @@ import { ReadTicks } from './ReadTicks';
9
9
 
10
10
  function chronological(messages) { return [...messages].sort((left, right) => new Date(left.created_at || 0) - new Date(right.created_at || 0)); }
11
11
  function replyToId(message) { return message.reply_to_id ?? message.reply_to; }
12
+ // last_reply_at/reply_count are viewer-independent (always on serialize_message);
13
+ // thread_last_read_at is viewer-specific and REST-only (never on a frame — see
14
+ // MessagingProvider.jsx's applyFrame merge-trap handling). A null receipt with
15
+ // at least one reply counts as unread; no replies means no marker at all.
16
+ function hasUnreadReplies(message) {
17
+ if (!message.reply_count) return false;
18
+ if (message.thread_last_read_at == null) return true;
19
+ return Boolean(message.last_reply_at) && new Date(message.last_reply_at) > new Date(message.thread_last_read_at);
20
+ }
12
21
  // A still-pending optimistic row (chunk 4) has a fake `local-<requestId>` id
13
22
  // and no durable server row yet — mounting ReadTicks against it would fire a
14
23
  // getMessageReadStatus REST call for an id the server has never heard of.
@@ -92,7 +101,15 @@ export function Thread({ conversationId, onReplyTargetChange, canModerateMessage
92
101
  <Stack spacing={1}>{roots.map((message) => {
93
102
  const replies = chronological(Object.values(cache.messages).filter((item) => String(replyToId(item)) === String(message.id)));
94
103
  return <Stack key={message.id} spacing={0.75}><MessageBubble message={message} conversation={conversation} onReply={reply} onJumpToMessage={jumpToMessage} onAnnouncementLink={onAnnouncementLink} canModerateMessages={canModerateMessages}>{canShowReadTicks(message, user) && <ReadTicks messageId={message.id} conversation={conversation} />}</MessageBubble>
95
- {(message.reply_count || replies.length) > 0 && <Button size="small" onClick={() => toggleReplies(message)}>{openThreads[message.id] ? t('MessagingThread.HIDE_REPLIES') : t('MessagingThread.SHOW_REPLIES', { count: message.reply_count || replies.length })}</Button>}
104
+ {(message.reply_count || replies.length) > 0 && (() => {
105
+ const unread = hasUnreadReplies(message);
106
+ const label = openThreads[message.id] ? t('MessagingThread.HIDE_REPLIES') : t('MessagingThread.SHOW_REPLIES', { count: message.reply_count || replies.length });
107
+ // MUI's Badge spreads unrecognized props (incl. aria-label) onto
108
+ // its own non-interactive wrapping span, not the inner control —
109
+ // a screen reader focuses the Button, so the accessible name
110
+ // must live there, not on the purely-visual dot.
111
+ return <Badge color="error" variant="dot" invisible={!unread}><Button size="small" aria-label={unread ? `${label} — ${t('MessagingThread.UNREAD_REPLIES')}` : undefined} onClick={() => toggleReplies(message)}>{label}</Button></Badge>;
112
+ })()}
96
113
  {openThreads[message.id] && <Stack spacing={0.75} sx={{ pl: 3, borderLeft: 2, borderColor: 'divider' }}>{replies.map((item) => <MessageBubble key={item.id} message={item} replyTo={message} conversation={conversation} onReply={reply} onJumpToMessage={jumpToMessage} onAnnouncementLink={onAnnouncementLink} canModerateMessages={canModerateMessages}>{canShowReadTicks(item, user) && <ReadTicks messageId={item.id} conversation={conversation} />}</MessageBubble>)}</Stack>}
97
114
  <Divider /></Stack>;
98
115
  })}</Stack>