Skip to content

upgrade ably-chat-js#18

Merged
mattheworiordan merged 3 commits into
mainfrom
upgrade-chat-js
May 22, 2025
Merged

upgrade ably-chat-js#18
mattheworiordan merged 3 commits into
mainfrom
upgrade-chat-js

Conversation

@vladvelici

@vladvelici vladvelici commented May 19, 2025

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • Chores
    • Updated the "@ably/chat" dependency to version ^0.7.0.
  • Refactor
    • Simplified room retrieval by removing unused options for reactions and typing in relevant commands.
    • Updated typing indicator logic for more frequent and accurate updates, with improved cleanup and process termination.
    • Adjusted import statements in tests for consistency without affecting test behavior.

@coderabbitai

coderabbitai Bot commented May 19, 2025

Copy link
Copy Markdown

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update revises how room handles are retrieved from the chat client by removing explicit options for reactions and typing features across several commands. The typing heartbeat logic is updated for increased frequency and reliability. The dependency "@ably/chat" is upgraded, and a minor test import refactor is made.

Changes

Files/Paths Change Summary
package.json Upgraded "@ably/chat" dependency from "^0.5.1" to "^0.7.0".
src/commands/rooms/reactions/send.ts
src/commands/rooms/reactions/subscribe.ts
Removed explicit empty { reactions: {} } options from rooms.get() calls.
src/commands/rooms/typing/start.ts Switched typing heartbeat from start() to keystroke(), increased frequency, removed typing options, improved cleanup.
src/commands/rooms/typing/subscribe.ts Removed typing options from rooms.get(), removed explicit TypingEvent type usage.
test/unit/services/config-manager.test.ts Refactored chai import to use named and namespace imports separately.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI_Command
    participant ChatClient
    participant Room

    User->>CLI_Command: Start typing in room
    CLI_Command->>ChatClient: rooms.get(roomId)
    ChatClient->>Room: Return Room instance (no options)
    CLI_Command->>Room: typing.keystroke() (every 450ms)
    Note over CLI_Command,Room: Typing heartbeat maintained
    User->>CLI_Command: Interrupt (SIGINT)
    CLI_Command->>ChatClient: Cleanup and disconnect
Loading

Possibly related PRs

Poem

In the warren, code hops anew,
Old options gone, the chat flows through.
Typing hearts beat quick and light,
Reactions simplified, just right.
A package hops to version seven—
Testing imports, all is leaven!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/commands/rooms/typing/start.ts (1)

150-178: 🛠️ Refactor suggestion

Unhandled keystroke failures may spam the log

room.typing.keystroke() runs every interval but failures are only logged; the timer keeps firing, so persistent errors will fill logs quickly.

Consider:

  1. Backing off (exponential or fixed) after N consecutive failures.
  2. Clearing the interval on unrecoverable errors to reduce noise.
-let failureStreak = 0;
-setInterval(() => {
-  room.typing.keystroke().catch((error: Error) => {
-    failureStreak++;
-    this.logCliEvent(flags, "typing", "keystrokeError",
-      `keystroke() failed (${failureStreak}x): ${error.message}`);
-    if (failureStreak >= 3) {
-      clearInterval(this.typingIntervalId!);
-      this.typingIntervalId = null;
-    }
-  });
-}, KEYSTROKE_INTERVAL);
+let failureStreak = 0;
+this.typingIntervalId = setInterval(async () => {
+  try {
+    await room.typing.keystroke();
+    failureStreak = 0;               // reset on success
+  } catch (err) {
+    failureStreak++;
+    this.logCliEvent(
+      flags,
+      "typing",
+      "keystrokeError",
+      `keystroke() failed (${failureStreak}×): ${
+        err instanceof Error ? err.message : String(err)
+      }`,
+    );
+    if (failureStreak >= 3) {
+      clearInterval(this.typingIntervalId!);
+      this.typingIntervalId = null;
+    }
+  }
+}, KEYSTROKE_INTERVAL);
🧹 Nitpick comments (2)
src/commands/rooms/typing/start.ts (2)

8-16: Keystroke interval of 450 ms is extremely aggressive

At ~2 Hz every client will publish ~133 events/minute while typing, which may:

  • Increase mobile battery/network consumption
  • Trigger rate-limits on free accounts (20 msgs/s hard-limit)
  • Generate unnecessary load on Ably

Ably’s docs recommend ≤1 heartbeat every ~8–10 s. Consider a safer value (e.g. 2 000 ms) or make it user-configurable.

-const KEYSTROKE_INTERVAL = 450; // ms
+// Default to 2 s; override with ABLY_KEYSTROKE_MS or a --interval flag if needed
+const KEYSTROKE_INTERVAL =
+  Number(process.env.ABLY_KEYSTROKE_MS) > 0
+    ? Number(process.env.ABLY_KEYSTROKE_MS)
+    : 2_000;

227-357: process.exit() will bypass oclif’s finally() – double-check shutdown sequence

Inside the SIGINT handler you:

  1. Call resolve()
  2. Immediately call process.exit(0)

Because process.exit aborts the event-loop, the finally() of this command (and parent ChatBaseCommand) will never execute, potentially:

  • Losing final telemetry or performance traces
  • Leaking resources if future cleanup is added only in finally()

Consider removing process.exit(0) and let the promise resolve naturally, or move all mandatory cleanup to finally().

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0dd8a68 and 3cfa4b6.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • package.json (1 hunks)
  • src/commands/rooms/reactions/send.ts (1 hunks)
  • src/commands/rooms/reactions/subscribe.ts (1 hunks)
  • src/commands/rooms/typing/start.ts (7 hunks)
  • src/commands/rooms/typing/subscribe.ts (2 hunks)
  • test/unit/services/config-manager.test.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: e2e-tests
  • GitHub Check: test
  • GitHub Check: e2e-tests
  • GitHub Check: test
🔇 Additional comments (7)
package.json (1)

70-70:

Details

❓ Verification inconclusive

Verified the @ably/chat dependency upgrade

This upgrade from "^0.5.1" to "^0.7.0" aligns with the changes in room handling across the codebase, removing the need for explicit feature option objects.


🏁 Script executed:

#!/bin/bash
# Check for breaking changes or notable updates in the Ably Chat changelog between 0.5.1 and 0.7.0

# Look for the repository or changelog
curl -s https://api.github.com/repos/ably/ably-chat-js/releases | grep -E "tag_name|body" | grep -A1 "v0.[5-7]" || echo "Could not fetch releases"

# Alternative - check NPM for version information
echo -e "\nNPM version information:"
npm view @ably/chat versions --json | grep -E "0\.[5-7]\.[0-9]"

Length of output: 740


#!/bin/bash

Retrieve the repository URL for @ably/chat to locate its changelog

npm view @ably/chat repository --json


#!/bin/bash

Fetch the changelog section for v0.7.0 of ably-chat-js to verify room handling & feature options notes

curl -s https://raw.githubusercontent.com/ably/ably-chat-js/main/CHANGELOG.md
| sed -n '/## [0.7.0]/,/## [0./[!]/p'


#!/bin/bash

Fetch the official release notes for v0.7.0 of ably-chat-js to confirm room handling and feature options changes

curl -s https://api.github.com/repos/ably/ably-chat-js/releases/tags/v0.7.0 | jq -r '.body'


Verify @ably/chat v0.7.0 Room Handling Changes

I wasn’t able to locate the official changelog or release notes for v0.7.0. Please double-check Ably Chat’s CHANGELOG.md or GitHub releases to confirm:

  • v0.7.0 explicitly removes the need for feature-option objects in room handling
  • There are no additional breaking changes affecting how rooms are created or joined
test/unit/services/config-manager.test.ts (1)

11-12: Improved Chai import pattern

The refactored import improves clarity by separating the named import expect from the namespace import of Chai.

src/commands/rooms/reactions/subscribe.ts (1)

112-112:

Details

✅ Verification successful

Simplified room retrieval by removing explicit empty reactions option

The empty reactions options object is no longer needed with the updated @ably/chat library. This simplifies the API usage and makes the code more maintainable.


🏁 Script executed:

#!/bin/bash
# Check if similar changes were applied consistently across other reaction-related files

echo "Checking other reaction files for similar options removal:"
grep -r "rooms.get(.*reactions" src/commands/rooms/reactions/ || echo "No remaining rooms.get calls with reactions options found"

Length of output: 315


Simplified room retrieval: removed explicit empty reactions option

The explicit empty reactions option is no longer required with the latest @ably/chat update, making the code cleaner and more maintainable.

• Verified in src/commands/rooms/reactions/subscribe.ts (line 112)
• Confirmed no other rooms.get calls with reactions options remain in src/commands/rooms/reactions/

src/commands/rooms/typing/subscribe.ts (2)

101-101: Simplified room retrieval by removing typing configuration options

The typing timeout configuration was removed, now relying on the defaults provided by the updated library. This simplifies the API usage and aligns with the removal of explicit options in other commands.


167-167:

Details

✅ Verification successful

Removed explicit typing for event parameter

Removed the TypingEvent type annotation, now relying on TypeScript's type inference. This change works because the types are properly defined in the @ably/chat library.


🏁 Script executed:

#!/bin/bash
# Check if the TypingEvent import was also removed from the imports at the top of the file

echo "Checking if TypingEvent import was removed from the top:"
head -10 src/commands/rooms/typing/subscribe.ts | grep -o "TypingEvent" || echo "TypingEvent import was correctly removed"

echo -e "\nChecking if similar changes were applied consistently in other typing-related files:"
grep -r "rooms.get(.*typing" src/commands/rooms/typing/ || echo "No remaining rooms.get calls with typing options found"

Length of output: 647


✅ TypingEvent Annotation Removal Verified

Removed the explicit TypingEvent annotation and its import in src/commands/rooms/typing/subscribe.ts, and confirmed there are no remaining rooms.get(…typing…) calls in other typing-related files. Relying on TypeScript’s inference is safe given the types defined in @ably/chat.

src/commands/rooms/reactions/send.ts (1)

133-134:

Details

❓ Verification inconclusive

Verify reactions feature is still enabled after dropping explicit options

rooms.get(roomId) is now called without { reactions: {} }.
In @ably/chat ≥ 0.7.0 reactions are enabled by default, but if anyone is still on an earlier minor version (or forces the feature-flags off), this could silently break reactions.


🏁 Script executed:

#!/bin/bash
# Find remaining calls that still pass the old reactions option
rg --line-number --context 2 $'rooms\\.get\\([^)]*reactions' || echo "✅ no legacy calls found"

# Quickly smoke-test that sending a reaction still works (requires network):
node - <<'JS'
import { createClient } from '@ably/chat';
(async () => {
  const client = await createClient({ apiKey: process.env.ABLY_API_KEY });
  const room   = await client.rooms.get('test-room');
  await room.attach();
  await room.reactions.send({ type: '👍' });
  console.log('reaction sent');
  await client.close();
})();
JS

Length of output: 1132


Verify reactions feature remains enabled without explicit options

We’ve confirmed there are no remaining rooms.get(..., { reactions: … }) calls. To ensure reactions still work:

  • Confirm your @ably/chat dependency is pinned to version ≥0.7.0 (reactions on by default).
  • Manually smoke-test sending a reaction in an environment where @ably/chat is installed:
# Check @ably/chat version
version=$(node -p 'require("./package.json").dependencies["@ably/chat"]||require("./package.json").devDependencies["@ably/chat"]')
echo "@ably/chat@$version"

# Smoke-test reaction sending
node - <<'JS'
const { createClient } = require('@ably/chat');
(async () => {
  const client = await createClient({ apiKey: process.env.ABLY_API_KEY });
  const room   = await client.rooms.get('test-room');
  await room.attach();
  await room.reactions.send({ type: '👍' });
  console.log('✅ Reaction sent');
  await client.close();
})();
JS
src/commands/rooms/typing/start.ts (1)

341-343: Good call: unsubscribing connection listeners before closing the client

Preventing lingering event handlers avoids memory leaks when this module is embedded in longer-lived processes.

@splindsay-92 splindsay-92 self-requested a review May 22, 2025 15:26
@splindsay-92 splindsay-92 force-pushed the upgrade-chat-js branch 2 times, most recently from 1b2d02d to f4814a9 Compare May 22, 2025 16:00
- Also includes a couple of fixes to properly terminate the process.
);
this.log(
" ably rooms typing start - Start typing in a chat room",
" ably rooms typing keystroke - Start typing in a chat room",

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.

Looking at the impl of keystroke, we call it on a timer - is having the name keystroke a bit misleading, as it's not a single keystroke?

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.

What about having an additional boolean arg, autotype, to control that behaviour? I think for the CLI users are likely to want some way of maintaining the indicator, so this will give us that while making things clear. :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

start might be a better word but I like keystroke because it matches the method name.

I agree with @splindsay-92 with some flag to control whether you want it on a loop or not. I'd default it to loop as it is now.

@mattheworiordan mattheworiordan merged commit 8c59ba6 into main May 22, 2025
@mattheworiordan mattheworiordan deleted the upgrade-chat-js branch May 22, 2025 20:54
mattheworiordan added a commit that referenced this pull request May 23, 2025
Surprised this is needed given the recent PR #18
mattheworiordan added a commit that referenced this pull request May 23, 2025
Surprised this is needed given the recent PR #18
mattheworiordan added a commit that referenced this pull request May 23, 2025
Surprised this is needed given the recent PR #18
mattheworiordan added a commit that referenced this pull request May 23, 2025
Surprised this is needed given the recent PR #18
mattheworiordan added a commit that referenced this pull request Jun 12, 2025
Surprised this is needed given the recent PR #18
@coderabbitai coderabbitai Bot mentioned this pull request Jul 24, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

4 participants