Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/commands/spaces/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
formatProgress,
formatResource,
formatSuccess,
formatWarning,
} from "../../utils/output.js";

export default class SpacesCreate extends SpacesBaseCommand {
Expand Down Expand Up @@ -54,6 +55,14 @@ export default class SpacesCreate extends SpacesBaseCommand {
),
);
}

const ephemeralSpaceWarning = `Space: ${spaceName} is backed by ably channel '${spaceName}::$space' and is ephemeral — it will become active when at least one member enters. This command initializes the space without entering it. To add a member to the space, use 'ably spaces members enter ${spaceName}'`;

if (this.shouldOutputJson(flags)) {
this.logJsonStatus("warning", ephemeralSpaceWarning, flags);
} else {
this.log(formatWarning(ephemeralSpaceWarning));
}
Comment on lines +59 to +65
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Keep one-shot JSON output as a single result record.

This currently emits two JSON records (logJsonResult then logJsonStatus) for a one-shot command. Prefer a single logJsonResult payload that includes warning metadata, and reserve logJsonStatus for long-running status signals. Also use formatResource(...) for resource names in the human-readable warning branch.

Proposed adjustment
-      if (this.shouldOutputJson(flags)) {
-        this.logJsonResult({ space: { name: spaceName } }, flags);
-      } else {
+      const ephemeralSpaceWarning = `Space ${spaceName} is backed by Ably channel '${spaceName}::$space' and is ephemeral — it will become active when at least one member enters. This command initializes the space without entering it. To add a member to the space, use 'ably spaces members enter ${spaceName}'.`;
+
+      if (this.shouldOutputJson(flags)) {
+        this.logJsonResult(
+          {
+            space: { name: spaceName },
+            warning: ephemeralSpaceWarning,
+          },
+          flags,
+        );
+      } else {
         this.log(
           formatSuccess(
             `Space ${formatResource(spaceName)} initialized. Use "ably spaces members enter" to activate it.`,
           ),
         );
+        this.log(
+          formatWarning(
+            `Space ${formatResource(spaceName)} is backed by Ably channel ${formatResource(`${spaceName}::$space`)} and is ephemeral — it will become active when at least one member enters. This command initializes the space without entering it. To add a member to the space, use 'ably spaces members enter ${spaceName}'.`,
+          ),
+        );
       }
-
-      const ephemeralSpaceWarning = `Space: ${spaceName} is backed by ably channel '${spaceName}::$space' and is ephemeral — it will become active when at least one member enters. This command initializes the space without entering it. To add a member to the space, use 'ably spaces members enter ${spaceName}'`;
-
-      if (this.shouldOutputJson(flags)) {
-        this.logJsonStatus("warning", ephemeralSpaceWarning, flags);
-      } else {
-        this.log(formatWarning(ephemeralSpaceWarning));
-      }

As per coding guidelines: "Use this.logJsonResult(data, flags) for one-shot results ... this.logJsonStatus(status, message, flags) for hold/status signals in long-running commands" and "Always use formatResource(name) (cyan) for resource names instead of quoted strings."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/spaces/create.ts` around lines 59 - 65, The JSON branch
currently emits a separate status record via logJsonStatus; instead, include the
warning on the one-shot result by calling this.logJsonResult(...) with the
result payload plus a warning field (use ephemeralSpaceWarning content) when
shouldOutputJson(flags) is true and remove the logJsonStatus call; in the
human-readable branch replace the quoted spaceName in ephemeralSpaceWarning with
formatResource(spaceName) and keep using formatWarning(...) when logging; locate
symbols ephemeralSpaceWarning, shouldOutputJson(flags), logJsonStatus,
logJsonResult, formatWarning, formatResource, spaceName and flags to make these
changes.

} catch (error) {
this.fail(error, flags, "spaceCreate");
}
Expand Down
29 changes: 26 additions & 3 deletions src/commands/spaces/cursors/set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -237,10 +237,33 @@ export default class SpacesCursorsSet extends SpacesBaseCommand {
{ position: { x: simulatedX, y: simulatedY } },
);

if (!this.shouldOutputJson(flags)) {
this.log(
`${formatLabel("Simulated")} cursor at (${simulatedX}, ${simulatedY})`,
if (this.shouldOutputJson(flags)) {
this.logJsonEvent(
{
cursor: {
clientId: this.realtimeClient!.auth.clientId,
connectionId: this.realtimeClient!.connection.id,
position: { x: simulatedX, y: simulatedY },
data: (cursorData.data as CursorData) ?? null,
},
},
flags,
);
this.logJsonStatus(
"holding",
"Holding cursor. Press Ctrl+C to exit.",
flags,
);
} else {
const simLines = [
`${formatLabel("Simulated")} cursor at (${simulatedX}, ${simulatedY})`,
];
if (cursorData.data) {
simLines.push(
` ${formatLabel("Data")} ${JSON.stringify(cursorData.data)}`,
);
}
this.log(simLines.join("\n"));
}
} catch (error) {
this.logCliEvent(
Expand Down
2 changes: 1 addition & 1 deletion src/commands/spaces/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ export default class SpacesGet extends SpacesBaseCommand {

if (items.length === 0) {
this.fail(
`Space ${spaceName} doesn't have any members currently present. Spaces only exist while members are present. Please enter at least one member using "ably spaces members enter".`,
`Space ${spaceName} doesn't have any members currently present. Spaces only exist while members are present. Please enter at least one member using 'ably spaces members enter ${spaceName}'.`,
flags,
"spaceGet",
{ spaceName },
Expand Down
94 changes: 44 additions & 50 deletions src/commands/spaces/locations/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,62 +56,56 @@ export default class SpacesLocationsSubscribe extends SpacesBaseCommand {
"Subscribing to location updates",
);

try {
const locationHandler = (update: LocationsEvents.UpdateEvent) => {
try {
const timestamp = new Date().toISOString();
this.logCliEvent(
flags,
"location",
"updateReceived",
"Location update received",
{
clientId: update.member.clientId,
connectionId: update.member.connectionId,
timestamp,
},
);
const locationHandler = (update: LocationsEvents.UpdateEvent) => {
try {
const timestamp = new Date().toISOString();
this.logCliEvent(
flags,
"location",
"updateReceived",
"Location update received",
{
clientId: update.member.clientId,
connectionId: update.member.connectionId,
timestamp,
},
);

if (this.shouldOutputJson(flags)) {
this.logJsonEvent(
{
location: {
member: {
clientId: update.member.clientId,
connectionId: update.member.connectionId,
},
currentLocation: update.currentLocation,
previousLocation: update.previousLocation,
timestamp,
if (this.shouldOutputJson(flags)) {
this.logJsonEvent(
{
location: {
member: {
clientId: update.member.clientId,
connectionId: update.member.connectionId,
},
currentLocation: update.currentLocation,
previousLocation: update.previousLocation,
timestamp,
},
flags,
);
} else {
this.log(formatTimestamp(timestamp));
this.log(formatLocationUpdateBlock(update));
this.log("");
}
} catch (error) {
this.fail(error, flags, "locationSubscribe", {
spaceName,
});
},
flags,
);
} else {
this.log(formatTimestamp(timestamp));
this.log(formatLocationUpdateBlock(update));
this.log("");
}
};
} catch (error) {
this.fail(error, flags, "locationSubscribe", {
spaceName,
});
}
};

this.space!.locations.subscribe("update", locationHandler);
this.space!.locations.subscribe("update", locationHandler);

this.logCliEvent(
flags,
"location",
"subscribed",
"Successfully subscribed to location updates",
);
} catch (error) {
this.fail(error, flags, "locationSubscribe", {
spaceName,
});
}
this.logCliEvent(
flags,
"location",
"subscribed",
"Successfully subscribed to location updates",
);

await this.waitAndTrackCleanup(flags, "location", flags.duration);
} catch (error) {
Expand Down
115 changes: 53 additions & 62 deletions src/commands/spaces/members/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ export default class SpacesMembersSubscribe extends SpacesBaseCommand {
...durationFlag,
};

private listener: ((member: SpaceMember) => void) | null = null;

async run(): Promise<void> {
const { args, flags } = await this.parse(SpacesMembersSubscribe);
const { space_name: spaceName } = args;
Expand Down Expand Up @@ -69,69 +67,69 @@ export default class SpacesMembersSubscribe extends SpacesBaseCommand {
"subscribing",
"Subscribing to member updates",
);
// Define the listener function
this.listener = (member: SpaceMember) => {
const now = Date.now();

// Determine the action from the member's lastEvent
const action = member.lastEvent?.name || "unknown";
const clientId = member.clientId || "Unknown";
const connectionId = member.connectionId || "Unknown";

// Skip self events - check connection ID
const selfConnectionId = this.realtimeClient!.connection.id;
if (member.connectionId === selfConnectionId) {
return;
}

// Create a unique key for this client+connection combination
const clientKey = `${clientId}:${connectionId}`;

// Check if we've seen this exact event recently (within 500ms)
const lastEvent = lastSeenEvents.get(clientKey);
const memberListener = (member: SpaceMember) => {
try {
const now = Date.now();

// Determine the action from the member's lastEvent
const action = member.lastEvent?.name || "unknown";
const clientId = member.clientId || "Unknown";
const connectionId = member.connectionId || "Unknown";

// Create a unique key for this client+connection combination
const clientKey = `${clientId}:${connectionId}`;

// Check if we've seen this exact event recently (within 500ms)
const lastEvent = lastSeenEvents.get(clientKey);

if (
lastEvent &&
lastEvent.action === action &&
now - lastEvent.timestamp < 500
) {
this.logCliEvent(
flags,
"member",
"duplicateEventSkipped",
`Skipping duplicate event '${action}' for ${clientId}`,
{ action, clientId },
);
return; // Skip duplicate events within 500ms window
}

// Update the last seen event for this client+connection
lastSeenEvents.set(clientKey, {
action,
timestamp: now,
});

if (
lastEvent &&
lastEvent.action === action &&
now - lastEvent.timestamp < 500
) {
this.logCliEvent(
flags,
"member",
"duplicateEventSkipped",
`Skipping duplicate event '${action}' for ${clientId}`,
{ action, clientId },
`update-${action}`,
`Member event '${action}' received`,
{ action, clientId, connectionId },
);
return; // Skip duplicate events within 500ms window
}

// Update the last seen event for this client+connection
lastSeenEvents.set(clientKey, {
action,
timestamp: now,
});

this.logCliEvent(
flags,
"member",
`update-${action}`,
`Member event '${action}' received`,
{ action, clientId, connectionId },
);

if (this.shouldOutputJson(flags)) {
this.logJsonEvent({ member: formatMemberOutput(member) }, flags);
} else {
this.log(
formatTimestamp(formatMessageTimestamp(member.lastEvent.timestamp)),
);
this.log(formatMemberEventBlock(member, action));
this.log("");
if (this.shouldOutputJson(flags)) {
this.logJsonEvent({ member: formatMemberOutput(member) }, flags);
} else {
this.log(
formatTimestamp(
formatMessageTimestamp(member.lastEvent.timestamp),
),
);
Comment on lines +118 to +122
Copy link

Copilot AI Mar 25, 2026

Choose a reason for hiding this comment

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

Same as spaces:subscribe: the listener treats member.lastEvent?.name as optional but later reads member.lastEvent.timestamp without guarding. Either treat lastEvent as required consistently (no optional chaining/defaults) or guard both name and timestamp via a single local lastEvent variable to avoid potential runtime errors if the SDK ever emits a member without lastEvent.

Copilot uses AI. Check for mistakes.
this.log(formatMemberEventBlock(member, action));
this.log("");
}
} catch (error) {
this.fail(error, flags, "memberSubscribe", { spaceName });
Comment on lines +119 to +127
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In the @ably/spacesTypeScript SDK, what is the declared type ofSpaceMember.lastEvent, and can it be undefined on members.subscribe("update", ...) callbacks?

💡 Result:

In the @ably/spaces TypeScript SDK, SpaceMember.lastEvent is declared as an object with properties { name: string; timestamp: number }, based on consistent examples across official documentation and SDK README. It is always present and populated in member objects received in members.subscribe("update", ...) callbacks, as shown in all payload examples for enter, leave, update events (e.g., {"name": "enter", "timestamp": 1677595689759}). No examples show it as undefined or absent, indicating it cannot be undefined in these callbacks.

Citations:


🏁 Script executed:

cat -n src/commands/spaces/members/subscribe.ts | head -150

Repository: ably/ably-cli

Length of output: 5568


🏁 Script executed:

find node_modules/@ably/spaces -name "*.d.ts" -o -name "*.ts" | head -20

Repository: ably/ably-cli

Length of output: 117


🏁 Script executed:

cat package.json | grep -A 5 "@ably/spaces"

Repository: ably/ably-cli

Length of output: 288


Move error handling from callback to outer catch block and use consistent optional chaining.

According to @ably/spaces SDK documentation, SpaceMember.lastEvent is always present in members.subscribe callbacks with { name: string; timestamp: number }, so the direct access on line 120 is safe. However, line 76 treats it as optional with ?.name, creating inconsistency.

More importantly, calling this.fail() inside the memberListener callback (lines 126-127) violates the coding guidelines. Per the guidelines: "In Promise callbacks (e.g., connection event handlers), use reject(new Error(...)) for errors, which propagates to await where the catch block calls this.fail()". Replace the try-catch with reject(new Error(...)) and let the outer catch block handle the error consistently.

If keeping the try-catch for defensive programming, either make both accesses use optional chaining (member.lastEvent?.timestamp) or remove the optional chaining on line 76 to reflect that the property is always defined.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/commands/spaces/members/subscribe.ts` around lines 119 - 127, The member
subscribe callback (memberListener) currently calls this.fail(...) inside the
callback and inconsistently accesses member.lastEvent (both direct and with
optional chaining); change the callback to propagate errors via reject(new
Error(...)) instead of calling this.fail directly so the outer await/catch can
call this.fail, and make the lastEvent access consistent across the handler
(either use member.lastEvent?.name and member.lastEvent?.timestamp everywhere
for defensive coding or remove the optional chaining so both places assume
lastEvent is present); update the code around
formatMessageTimestamp/formatTimestamp/formatMemberEventBlock usage and replace
the inner catch's this.fail call with reject(...) so errors bubble to the outer
catch.

}
};

// Subscribe using the stored listener
await this.space!.members.subscribe("update", this.listener);
// Subscribe using the listener
await this.space!.members.subscribe("update", memberListener);

this.logCliEvent(
flags,
Expand All @@ -140,13 +138,6 @@ export default class SpacesMembersSubscribe extends SpacesBaseCommand {
"Subscribed to member updates",
);

this.logCliEvent(
flags,
"member",
"listening",
"Listening for member updates...",
);

// Wait until the user interrupts or the optional duration elapses
await this.waitAndTrackCleanup(flags, "member", flags.duration);
} catch (error) {
Expand Down
Loading
Loading