Skip to content

feat(subscriptions): mark a single thread as read via REST tmid#40957

Open
ggazzo wants to merge 2 commits into
developfrom
chore/rest-subscriptions-read-tmid
Open

feat(subscriptions): mark a single thread as read via REST tmid#40957
ggazzo wants to merge 2 commits into
developfrom
chore/rest-subscriptions-read-tmid

Conversation

@ggazzo

@ggazzo ggazzo commented Jun 15, 2026

Copy link
Copy Markdown
Member

Summary

Extends POST /v1/subscriptions.read with an optional tmid field so the client can mark a single thread as read over REST instead of via the readThreads DDP method.

When tmid is supplied the server resolves the owning message, validates it belongs to the target room, and marks just that thread as read via readThreadMethod. Without tmid the endpoint behaves exactly as before (marks the whole room).

Changes

Area Change
POST /v1/subscriptions.read Optional tmid. Validates the thread belongs to the room (error-invalid-thread otherwise) and marks the thread read.
threads/server/functions.ts New readThreadMethod centralizing the legacy readThreads behavior (threads-enabled check, room/access validation, beforeReadMessages callback, readThread).
readThreads DDP method Refactored to delegate to readThreadMethod and log a deprecation pointing at /v1/subscriptions.read (kept for external SDK/mobile until 9.0.0).
Client callers ThreadChat.tsx and useThreadMessagesQuery.ts migrated from readThreads DDP to the REST endpoint.

Test plan

  • Open a thread → unread counter clears.
  • POST /v1/subscriptions.read with { rid, tmid } marks only that thread read.
  • POST /v1/subscriptions.read with a tmid that does not belong to rid → 400 error-invalid-thread.
  • readThreads DDP still works (logs deprecation).

Review in cubic

Summary by CodeRabbit

  • New Features

    • Thread read status can now be updated for a specific thread in the app and via the API.
    • The read-status request now accepts an optional thread ID field for more precise behavior.
  • Bug Fixes

    • Thread read updates now validate that the selected thread belongs to the current room.
    • Thread message loading now keeps read state in sync without blocking message retrieval.
  • Chores

    • Added notes for the API and migration changes.
    • Updated end-to-end coverage for thread read scenarios.

@dionisio-bot

dionisio-bot Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@coderabbitai

coderabbitai Bot commented Jun 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Adds optional tmid field to POST /v1/subscriptions.read for thread-level read marking. Extracts shared readThreadMethod from the readThreads DDP handler, which is now deprecated with a logger pointing to the REST route until 9.0.0. Client callers in ThreadChat and useThreadMessagesQuery migrate from useMethod to useEndpoint.

Changes

Thread Read: DDP → REST Migration with tmid Support

Layer / File(s) Summary
REST type contract
packages/rest-typings/src/v1/subscriptionsEndpoints.ts
SubscriptionsRead type and SubscriptionsReadSchema extended with optional nullable tmid in both rid/roomId union branches.
Shared readThreadMethod and subscriptions.read handler
apps/meteor/app/threads/server/functions.ts, apps/meteor/app/api/server/v1/subscriptions.ts
readThreadMethod exported from functions.ts encapsulating threads-enabled check, room access, beforeReadMessages callback, and readThread call. subscriptions.read endpoint branches on tmid, validates thread belongs to room, and delegates to readThreadMethod.
DDP method deprecation
apps/meteor/server/methods/readThreads.ts
readThreads method body replaced with a methodDeprecationLogger call and delegation to readThreadMethod; all inline logic removed.
Client callers migrated
apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx, apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
Both files replace useMethod/readThreads with useEndpoint calling POST /v1/subscriptions.read with {rid, tmid}. useThreadMessagesQuery also adds mapMessageFromApi mapping step.
E2E tests and changesets
apps/meteor/tests/end-to-end/api/subscriptions.ts, .changeset/*.md
Tests added for tmid success (verifies thread removed from tunread) and mismatched tmid 400 error. Two changesets document the REST extension and client migration.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • RocketChat/Rocket.Chat#40659: Modifies the same useThreadMessagesQuery.ts hook for DDP→REST thread read marking, directly preceding this PR's changes.
  • RocketChat/Rocket.Chat#40711: Modifies the same subscriptions.ts endpoint and readThreadsreadThreadMethod refactor path.

Suggested labels

type: feature

Suggested reviewers

  • tassoevan
  • sampaiodiego
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding REST support to mark a single thread as read using tmid.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@changeset-bot

changeset-bot Bot commented Jun 15, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 46f9940

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@rocket.chat/meteor Minor
@rocket.chat/rest-typings Minor
@rocket.chat/core-typings Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

ggazzo added a commit that referenced this pull request Jun 15, 2026
The thread read-marker migration (subscriptions.read tmid endpoint +
ThreadChat/useThreadMessagesQuery callers) moves to its own PR #40957.
Extend POST /v1/subscriptions.read with an optional tmid field that marks
a specific thread as read (validating it belongs to the room) instead of
the whole room. Add readThreadMethod to centralize the legacy readThreads
behavior and migrate the thread read-marker client callers (ThreadChat,
useThreadMessagesQuery) off the readThreads DDP method.
@ggazzo ggazzo force-pushed the chore/rest-subscriptions-read-tmid branch from d1cad08 to 391cf16 Compare June 15, 2026 20:38
@codecov

codecov Bot commented Jun 15, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 84.61538% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.15%. Comparing base (275a6ed) to head (46f9940).

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #40957      +/-   ##
===========================================
+ Coverage    70.13%   70.15%   +0.01%     
===========================================
  Files         3368     3365       -3     
  Lines       130022   129894     -128     
  Branches     22582    22568      -14     
===========================================
- Hits         91191    91121      -70     
+ Misses       35519    35475      -44     
+ Partials      3312     3298      -14     
Flag Coverage Δ
unit 70.13% <ø> (+0.02%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@ggazzo ggazzo added this to the 8.7.0 milestone Jun 29, 2026
@ggazzo ggazzo marked this pull request as ready for review June 29, 2026 13:06
@ggazzo ggazzo requested review from a team as code owners June 29, 2026 13:06
@coderabbitai coderabbitai Bot added the type: feature Pull requests that introduces new feature label Jun 29, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/meteor/app/threads/server/functions.ts (1)

105-110: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the implementation comment.

The function name and body already document this flow, and the repo guidance asks to avoid implementation comments.

Proposed cleanup
-/**
- * Marks a thread as read for a user, replicating the full behavior of the
- * legacy `readThreads` DDP method: it validates that threads are enabled, that
- * the thread and its room exist, that the user can access the room, and runs
- * the `beforeReadMessages` callback before clearing the thread unread state.
- */
 export const readThreadMethod = async ({ user, tmid }: { user: IUser; tmid: IMessage['_id'] }) => {

As per coding guidelines, **/*.{ts,tsx,js}: “Avoid code comments in the implementation”.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/app/threads/server/functions.ts` around lines 105 - 110, Remove
the implementation comment above the thread read logic in the functions.ts
module; the behavior is already clear from the surrounding function and code.
Delete the descriptive block comment associated with the thread-marking flow so
the implementation stays comment-free, and keep the logic in the relevant thread
read function(s) unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/meteor/app/api/server/v1/subscriptions.ts`:
- Around line 151-158: The thread-read branch in `subscriptions.ts` is using a
truthiness check on `tmid`, which lets an empty string bypass validation and
fall through to the room-wide read path. Update the `if (tmid)` logic to branch
on presence instead of truthiness so any provided `tmid` value is treated as a
thread-read attempt. Keep the existing `Messages.findOneById(tmid)` and
`readThreadMethod({ user: this.user, tmid })` flow, and ensure invalid or empty
IDs still reach the `error-invalid-thread` case.

In
`@apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx`:
- Line 74: The fire-and-forget call to markThreadRead in ThreadChat can reject
and currently has no rejection handling, which may cause an unhandled promise
rejection on transient REST failures. Update the call site in the ThreadChat
component to handle the returned promise explicitly by attaching a catch path or
equivalent error suppression/logging so the rejection is safely consumed while
keeping the non-blocking behavior.

In `@apps/meteor/tests/end-to-end/api/subscriptions.ts`:
- Around line 429-432: The subscription test is asserting an implementation
artifact in `removeUnreadThreadByRoomIdAndUserId` by expecting `tunread` to
remain as an empty array after the last thread is cleared. Update the
expectation in the `subscriptions.ts` end-to-end test to match the API contract
instead, using the `subscription` response shape to assert that the
unread-thread state no longer contains `threadId` and allowing `tunread` to be
absent when it is fully removed.

---

Nitpick comments:
In `@apps/meteor/app/threads/server/functions.ts`:
- Around line 105-110: Remove the implementation comment above the thread read
logic in the functions.ts module; the behavior is already clear from the
surrounding function and code. Delete the descriptive block comment associated
with the thread-marking flow so the implementation stays comment-free, and keep
the logic in the relevant thread read function(s) unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: da8edaa7-b713-4fd5-b44f-8555e886d685

📥 Commits

Reviewing files that changed from the base of the PR and between 275a6ed and 46f9940.

📒 Files selected for processing (9)
  • .changeset/migrate-thread-read-callers.md
  • .changeset/rest-subscriptions-read-tmid.md
  • apps/meteor/app/api/server/v1/subscriptions.ts
  • apps/meteor/app/threads/server/functions.ts
  • apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/server/methods/readThreads.ts
  • apps/meteor/tests/end-to-end/api/subscriptions.ts
  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/server/methods/readThreads.ts
  • apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/api/server/v1/subscriptions.ts
  • apps/meteor/tests/end-to-end/api/subscriptions.ts
  • apps/meteor/app/threads/server/functions.ts
  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
🧠 Learnings (11)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/rest-subscriptions-read-tmid.md
  • .changeset/migrate-thread-read-callers.md
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/server/methods/readThreads.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/api/server/v1/subscriptions.ts
  • apps/meteor/tests/end-to-end/api/subscriptions.ts
  • apps/meteor/app/threads/server/functions.ts
  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/server/methods/readThreads.ts
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/api/server/v1/subscriptions.ts
  • apps/meteor/tests/end-to-end/api/subscriptions.ts
  • apps/meteor/app/threads/server/functions.ts
  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
📚 Learning: 2026-03-09T18:39:14.020Z
Learnt from: Harxhit
Repo: RocketChat/Rocket.Chat PR: 39476
File: apps/meteor/server/methods/addAllUserToRoom.ts:0-0
Timestamp: 2026-03-09T18:39:14.020Z
Learning: When implementing batch processing in server methods, favor a single data pass to collect both the items and any derived fields needed for validation. Use the same dataset for both validation and processing to avoid races between validation and execution, and document the approach in code comments. Apply this pattern to similar Meteor Rocket.Chat server methods under apps/meteor/server/methods to prevent race conditions and ensure consistent batch behavior.

Applied to files:

  • apps/meteor/server/methods/readThreads.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • apps/meteor/server/methods/readThreads.ts
  • apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx
  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
  • apps/meteor/app/api/server/v1/subscriptions.ts
  • apps/meteor/tests/end-to-end/api/subscriptions.ts
  • apps/meteor/app/threads/server/functions.ts
  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.

Applied to files:

  • apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.

Applied to files:

  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.

Applied to files:

  • apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: During PR reviews that touch endpoint files under apps/meteor/app/api/server/v1, enforce strict scope: if a PR targets a specific endpoint (e.g., rooms.favorite), do not propose changes to unrelated endpoints (e.g., rooms.invite) unless maintainers explicitly request them. Focus feedback on the touched endpoint's behavior, API surface, and related tests; avoid broad cross-endpoint changes in the same PR unless requested.

Applied to files:

  • apps/meteor/app/api/server/v1/subscriptions.ts
📚 Learning: 2026-02-24T19:09:01.522Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:01.522Z
Learning: In Rocket.Chat OpenAPI migration PRs for endpoints under apps/meteor/app/api/server/v1, avoid introducing logic changes. Only perform scope-tight changes that preserve behavior; style-only cleanups (e.g., removing inline comments) may be deferred to follow-ups to keep the migration PR focused.

Applied to files:

  • apps/meteor/app/api/server/v1/subscriptions.ts
📚 Learning: 2026-05-11T23:14:59.316Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40469
File: packages/rest-typings/src/v1/users.ts:337-337
Timestamp: 2026-05-11T23:14:59.316Z
Learning: In Rocket.Chat REST endpoint typings (e.g., packages/rest-typings/src/v1/users.ts and other rest-typings files), keep the established convention of deriving field types from the domain model (e.g., use IUser indexed access like IUser['statusExpiresAt']) rather than swapping individual fields to serialized primitives (like string) in an ad-hoc way. If a truly different “serialized” representation is needed, perform the refactor consistently across the codebase (not just a single endpoint/field) and ensure all related REST typings stay aligned with the shared serialization types.

Applied to files:

  • packages/rest-typings/src/v1/subscriptionsEndpoints.ts
🔇 Additional comments (9)
packages/rest-typings/src/v1/subscriptionsEndpoints.ts (1)

9-11: LGTM!

Also applies to: 54-57, 72-75

apps/meteor/app/threads/server/functions.ts (1)

3-13: LGTM!

Also applies to: 111-132

apps/meteor/app/api/server/v1/subscriptions.ts (1)

2-17: LGTM!

apps/meteor/server/methods/readThreads.ts (1)

6-7: LGTM!

Also applies to: 18-26

apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx (1)

5-5: LGTM!

Also applies to: 65-65, 83-83

apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)

2-8: LGTM!

Also applies to: 28-29, 110-114

apps/meteor/tests/end-to-end/api/subscriptions.ts (1)

436-450: LGTM!

.changeset/migrate-thread-read-callers.md (1)

1-8: LGTM!

.changeset/rest-subscriptions-read-tmid.md (1)

1-6: LGTM!

Comment on lines +151 to +158
if (tmid) {
const thread = await Messages.findOneById(tmid);
if (thread?.rid !== room._id) {
throw new Error('error-invalid-thread');
}
await readThreadMethod({ user: this.user, tmid });
return API.v1.success();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Branch on presence, not truthiness, for tmid.

With if (tmid), a request body containing tmid: '' skips thread validation and falls through to the room-wide read path. Treat non-null provided values as thread-read attempts so invalid IDs fail as error-invalid-thread.

Proposed fix
-		if (tmid) {
+		if (tmid !== undefined && tmid !== null) {
 			const thread = await Messages.findOneById(tmid);
 			if (thread?.rid !== room._id) {
 				throw new Error('error-invalid-thread');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (tmid) {
const thread = await Messages.findOneById(tmid);
if (thread?.rid !== room._id) {
throw new Error('error-invalid-thread');
}
await readThreadMethod({ user: this.user, tmid });
return API.v1.success();
}
if (tmid !== undefined && tmid !== null) {
const thread = await Messages.findOneById(tmid);
if (thread?.rid !== room._id) {
throw new Error('error-invalid-thread');
}
await readThreadMethod({ user: this.user, tmid });
return API.v1.success();
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/app/api/server/v1/subscriptions.ts` around lines 151 - 158, The
thread-read branch in `subscriptions.ts` is using a truthiness check on `tmid`,
which lets an empty string bypass validation and fall through to the room-wide
read path. Update the `if (tmid)` logic to branch on presence instead of
truthiness so any provided `tmid` value is treated as a thread-read attempt.
Keep the existing `Messages.findOneById(tmid)` and `readThreadMethod({ user:
this.user, tmid })` flow, and ensure invalid or empty IDs still reach the
`error-invalid-thread` case.

}

readThreads(mainMessage._id);
void markThreadRead({ rid: room._id, tmid: mainMessage._id });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Handle the dropped endpoint rejection.

This fire-and-forget call can reject, and without a .catch it will surface as an unhandled promise rejection on transient REST failures.

Suggested change
-				void markThreadRead({ rid: room._id, tmid: mainMessage._id });
+				void markThreadRead({ rid: room._id, tmid: mainMessage._id }).catch(() => undefined);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
void markThreadRead({ rid: room._id, tmid: mainMessage._id });
void markThreadRead({ rid: room._id, tmid: mainMessage._id }).catch(() => undefined);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx`
at line 74, The fire-and-forget call to markThreadRead in ThreadChat can reject
and currently has no rejection handling, which may cause an unhandled promise
rejection on transient REST failures. Update the call site in the ThreadChat
component to handle the returned promise explicitly by attaching a catch path or
equivalent error suppression/logging so the rejection is safely consumed while
keeping the non-blocking behavior.

Comment on lines +429 to +432
.expect((res) => {
expect(res.body).to.have.property('success', true);
// removeUnreadThreadByRoomIdAndUserId only $pulls the tmid, leaving an empty array
expect(res.body.subscription).to.have.property('tunread').that.is.an('array').and.does.not.include(threadId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Assert the API contract, not the empty-array artifact.

This test will fail on a valid implementation that removes tunread entirely once the last unread thread is cleared.

Suggested change
-						// removeUnreadThreadByRoomIdAndUserId only $pulls the tmid, leaving an empty array
-						expect(res.body.subscription).to.have.property('tunread').that.is.an('array').and.does.not.include(threadId);
+						const tunread = res.body.subscription.tunread ?? [];
+						expect(tunread).to.be.an('array');
+						expect(tunread).to.not.include(threadId);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
.expect((res) => {
expect(res.body).to.have.property('success', true);
// removeUnreadThreadByRoomIdAndUserId only $pulls the tmid, leaving an empty array
expect(res.body.subscription).to.have.property('tunread').that.is.an('array').and.does.not.include(threadId);
.expect((res) => {
expect(res.body).to.have.property('success', true);
const tunread = res.body.subscription.tunread ?? [];
expect(tunread).to.be.an('array');
expect(tunread).to.not.include(threadId);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/meteor/tests/end-to-end/api/subscriptions.ts` around lines 429 - 432,
The subscription test is asserting an implementation artifact in
`removeUnreadThreadByRoomIdAndUserId` by expecting `tunread` to remain as an
empty array after the last thread is cleared. Update the expectation in the
`subscriptions.ts` end-to-end test to match the API contract instead, using the
`subscription` response shape to assert that the unread-thread state no longer
contains `threadId` and allowing `tunread` to be absent when it is fully
removed.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 issues found across 9 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/meteor/app/api/server/v1/subscriptions.ts">

<violation number="1" location="apps/meteor/app/api/server/v1/subscriptions.ts:151">
P2: Use a presence/type check for `tmid` instead of truthiness. An empty string `tmid` is currently treated as omitted, so a malformed thread-read request can mark the entire room read.</violation>
</file>

<file name="apps/meteor/tests/end-to-end/api/subscriptions.ts">

<violation number="1" location="apps/meteor/tests/end-to-end/api/subscriptions.ts:418">
P2: Error-assertion test only checks `error` property presence but does not validate the specific error type. PR description states the endpoint returns `error-invalid-thread` for mismatched tmid/rid. Without verifying the errorType, the test cannot distinguish the expected error from an unrelated 400.</violation>
</file>

<file name="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts">

<violation number="1" location="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts:111">
P2: Mutation side-effect inside queryFn: `markThreadRead` POST runs on every refetch, not only on mount. This violates TanStack Query's separation of concerns and causes unnecessary API calls on window refocus, stale cache re-fetch, etc.</violation>
</file>

<file name="apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx">

<violation number="1" location="apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx:74">
P2: This fire-and-forget call lacks a `.catch()` handler. On transient REST failures the rejected promise will surface as an unhandled promise rejection, which in strict environments can crash the process or produce noisy console errors.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

throw new Error('error-invalid-subscription');
}

if (tmid) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Use a presence/type check for tmid instead of truthiness. An empty string tmid is currently treated as omitted, so a malformed thread-read request can mark the entire room read.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/app/api/server/v1/subscriptions.ts, line 151:

<comment>Use a presence/type check for `tmid` instead of truthiness. An empty string `tmid` is currently treated as omitted, so a malformed thread-read request can mark the entire room read.</comment>

<file context>
@@ -139,14 +140,23 @@ API.v1.post(
 			throw new Error('error-invalid-subscription');
 		}
 
+		if (tmid) {
+			const thread = await Messages.findOneById(tmid);
+			if (thread?.rid !== room._id) {
</file context>
Suggested change
if (tmid) {
if (typeof tmid === 'string') {

tmid: threadId,
})
.expect(200)
.expect((res) => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Error-assertion test only checks error property presence but does not validate the specific error type. PR description states the endpoint returns error-invalid-thread for mismatched tmid/rid. Without verifying the errorType, the test cannot distinguish the expected error from an unrelated 400.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/tests/end-to-end/api/subscriptions.ts, line 418:

<comment>Error-assertion test only checks `error` property presence but does not validate the specific error type. PR description states the endpoint returns `error-invalid-thread` for mismatched tmid/rid. Without verifying the errorType, the test cannot distinguish the expected error from an unrelated 400.</comment>

<file context>
@@ -394,6 +394,60 @@ describe('[Subscriptions]', () => {
+						tmid: threadId,
+					})
+					.expect(200)
+					.expect((res) => {
+						expect(res.body).to.have.property('success', true);
+					});
</file context>

(msg): msg is IThreadMessage => isThreadMessage(msg) && msg.tmid === tmid && msg._id !== tmid && msg._hidden !== true,
);
const { messages } = await getThreadMessages({ tmid });
void markThreadRead({ rid: roomId, tmid }).catch(() => undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Mutation side-effect inside queryFn: markThreadRead POST runs on every refetch, not only on mount. This violates TanStack Query's separation of concerns and causes unnecessary API calls on window refocus, stale cache re-fetch, etc.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts, line 111:

<comment>Mutation side-effect inside queryFn: `markThreadRead` POST runs on every refetch, not only on mount. This violates TanStack Query's separation of concerns and causes unnecessary API calls on window refocus, stale cache re-fetch, etc.</comment>

<file context>
@@ -105,10 +107,11 @@ export const useThreadMessagesQuery = (tmid: IThreadMainMessage['_id'], rid?: IR
-				(msg): msg is IThreadMessage => isThreadMessage(msg) && msg.tmid === tmid && msg._id !== tmid && msg._hidden !== true,
-			);
+			const { messages } = await getThreadMessages({ tmid });
+			void markThreadRead({ rid: roomId, tmid }).catch(() => undefined);
+			const filtered = messages
+				.map((m) => mapMessageFromApi(m))
</file context>

}

readThreads(mainMessage._id);
void markThreadRead({ rid: room._id, tmid: mainMessage._id });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This fire-and-forget call lacks a .catch() handler. On transient REST failures the rejected promise will surface as an unhandled promise rejection, which in strict environments can crash the process or produce noisy console errors.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/components/ThreadChat.tsx, line 74:

<comment>This fire-and-forget call lacks a `.catch()` handler. On transient REST failures the rejected promise will surface as an unhandled promise rejection, which in strict environments can crash the process or produce noisy console errors.</comment>

<file context>
@@ -71,7 +71,7 @@ const ThreadChat = ({ mainMessage }: ThreadChatProps) => {
 				}
 
-				readThreads(mainMessage._id);
+				void markThreadRead({ rid: room._id, tmid: mainMessage._id });
 			},
 			clientCallbacks.priority.MEDIUM,
</file context>
Suggested change
void markThreadRead({ rid: room._id, tmid: mainMessage._id });
void markThreadRead({ rid: room._id, tmid: mainMessage._id }).catch(() => undefined);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feature Pull requests that introduces new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant