Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(channels): infinite typing indicators (#3138)

teo20b6e3af7814
diff --git a/js/app/packages/channel/Input/create-typing-tracker.ts b/js/app/packages/channel/Input/create-typing-tracker.ts
index abd1774bc5..16d6c782c2 100644
--- a/js/app/packages/channel/Input/create-typing-tracker.ts
+++ b/js/app/packages/channel/Input/create-typing-tracker.ts
@@ -1,7 +1,10 @@
import { onCleanup } from 'solid-js';
/** How long after the last keystroke before we tell the server the user stopped typing. */
-const INACTIVITY_TIMEOUT_MS = 2000;
+export const TYPING_INACTIVITY_TIMEOUT_MS = 2_000;
+
+/** How often to refresh the typing start event while the user keeps typing. */
+export const TYPING_START_REFRESH_INTERVAL_MS = 4_000;
type TypingTrackerCallbacks = {
onStartTyping: () => void;
@@ -11,13 +14,14 @@ type TypingTrackerCallbacks = {
/**
* Tracks local typing activity and fires start/stop callbacks.
*
- * - `onStartTyping` fires on the first keystroke and is not called again
- * until after the user goes idle (stop fires first).
- * - `onStopTyping` fires after `INACTIVITY_TIMEOUT_MS` of inactivity,
+ * - `onStartTyping` fires on the first keystroke and periodically while the
+ * user keeps typing so other clients can safely expire stale indicators.
+ * - `onStopTyping` fires after `TYPING_INACTIVITY_TIMEOUT_MS` of inactivity,
* or immediately when `stop()` is called (e.g. on send / close).
*/
export function createTypingTracker(callbacks: TypingTrackerCallbacks) {
let isTyping = false;
+ let lastStartTypingAt = 0;
let inactivityTimer: ReturnType<typeof setTimeout> | undefined;
function clearTimer() {
@@ -31,18 +35,26 @@ export function createTypingTracker(callbacks: TypingTrackerCallbacks) {
clearTimer();
if (isTyping) {
isTyping = false;
+ lastStartTypingAt = 0;
callbacks.onStopTyping();
}
}
function keystroke() {
+ const now = Date.now();
+
if (!isTyping) {
isTyping = true;
+ lastStartTypingAt = now;
+ callbacks.onStartTyping();
+ } else if (now - lastStartTypingAt >= TYPING_START_REFRESH_INTERVAL_MS) {
+ lastStartTypingAt = now;
callbacks.onStartTyping();
}
+
// Reset (or start) the inactivity timer on every keystroke.
clearTimer();
- inactivityTimer = setTimeout(stopTyping, INACTIVITY_TIMEOUT_MS);
+ inactivityTimer = setTimeout(stopTyping, TYPING_INACTIVITY_TIMEOUT_MS);
}
onCleanup(stopTyping);
diff --git a/js/app/packages/channel/Input/tests/create-typing-tracker.test.ts b/js/app/packages/channel/Input/tests/create-typing-tracker.test.ts
new file mode 100644
index 0000000000..9ad231362f
--- /dev/null
+++ b/js/app/packages/channel/Input/tests/create-typing-tracker.test.ts
@@ -0,0 +1,46 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ createTypingTracker,
+ TYPING_INACTIVITY_TIMEOUT_MS,
+ TYPING_START_REFRESH_INTERVAL_MS,
+} from '../create-typing-tracker';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe('createTypingTracker', () => {
+ it('refreshes start while the user keeps typing, then stops after inactivity', () => {
+ createRoot((dispose) => {
+ const onStartTyping = vi.fn();
+ const onStopTyping = vi.fn();
+ const tracker = createTypingTracker({ onStartTyping, onStopTyping });
+
+ tracker.keystroke();
+ expect(onStartTyping).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1_000);
+ tracker.keystroke();
+ vi.advanceTimersByTime(1_000);
+ tracker.keystroke();
+ vi.advanceTimersByTime(TYPING_START_REFRESH_INTERVAL_MS - 2_001);
+ tracker.keystroke();
+ expect(onStartTyping).toHaveBeenCalledTimes(1);
+
+ vi.advanceTimersByTime(1);
+ tracker.keystroke();
+ expect(onStartTyping).toHaveBeenCalledTimes(2);
+ expect(onStopTyping).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(TYPING_INACTIVITY_TIMEOUT_MS);
+ expect(onStopTyping).toHaveBeenCalledTimes(1);
+
+ dispose();
+ });
+ });
+});
diff --git a/js/app/packages/queries/channel/tests/typing.test.ts b/js/app/packages/queries/channel/tests/typing.test.ts
new file mode 100644
index 0000000000..10149b70f4
--- /dev/null
+++ b/js/app/packages/queries/channel/tests/typing.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@service-comms/client', () => ({
+ commsServiceClient: {
+ postTypingUpdate: vi.fn(),
+ },
+}));
+
+import {
+ clearTypingIndicators,
+ getTypingUsersForChannel,
+ handleCommsTyping,
+ TYPING_INDICATOR_TIMEOUT_MS,
+} from '../typing';
+
+const currentUserId = 'user-current';
+
+function typingUsers(channelId = 'channel-1') {
+ return [...getTypingUsersForChannel(channelId)];
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ clearTypingIndicators();
+});
+
+afterEach(() => {
+ clearTypingIndicators();
+ vi.useRealTimers();
+});
+
+describe('channel typing indicators', () => {
+ it('expires indicators unless refreshed by a new start event', () => {
+ handleCommsTyping(
+ { action: 'start', channel_id: 'channel-1', user_id: 'user-typing' },
+ currentUserId
+ );
+
+ expect(typingUsers()).toEqual(['user-typing']);
+
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS - 1);
+ handleCommsTyping(
+ { action: 'start', channel_id: 'channel-1', user_id: 'user-typing' },
+ currentUserId
+ );
+
+ vi.advanceTimersByTime(1);
+ expect(typingUsers()).toEqual(['user-typing']);
+
+ vi.advanceTimersByTime(TYPING_INDICATOR_TIMEOUT_MS - 2);
+ expect(typingUsers()).toEqual(['user-typing']);
+
+ vi.advanceTimersByTime(1);
+ expect(typingUsers()).toEqual([]);
+ });
+});
diff --git a/js/app/packages/queries/channel/typing.ts b/js/app/packages/queries/channel/typing.ts
index 307dde26f1..1564f1692b 100644
--- a/js/app/packages/queries/channel/typing.ts
+++ b/js/app/packages/queries/channel/typing.ts
@@ -1,8 +1,15 @@
import { commsServiceClient } from '@service-comms/client';
import { useMutation } from '@tanstack/solid-query';
import { createSignal } from 'solid-js';
-import { createMutationNonce } from '../nonce';
-import { ChannelNonceKeys } from './keys';
+
+export const TYPING_INDICATOR_TIMEOUT_MS = 8_000;
+
+type ThreadId = string | null;
+type TypingUsersByChannel = Map<string, Map<ThreadId, Set<string>>>;
+type TypingTimeoutsByChannel = Map<
+ string,
+ Map<ThreadId, Map<string, ReturnType<typeof setTimeout>>>
+>;
/**
* Websocket payload type for typing events
@@ -20,45 +27,151 @@ type CommsTypingPayload = {
*
* Uses null key for main channel, string key for threads.
*/
-const [typingUsers, setTypingUsers] = createSignal<
- Map<string, Map<string | null, Set<string>>>
->(new Map());
+const [typingUsers, setTypingUsers] = createSignal<TypingUsersByChannel>(
+ new Map()
+);
+
+const typingTimeouts: TypingTimeoutsByChannel = new Map();
+
+function withAddedTypingUser(
+ prev: TypingUsersByChannel,
+ channelId: string,
+ userId: string,
+ threadId: ThreadId
+): TypingUsersByChannel {
+ const next = new Map(prev);
+ const channelMap = new Map(prev.get(channelId));
+ const threadUsers = new Set(channelMap.get(threadId));
+
+ threadUsers.add(userId);
+ channelMap.set(threadId, threadUsers);
+ next.set(channelId, channelMap);
+
+ return next;
+}
+
+function withoutTypingUser(
+ prev: TypingUsersByChannel,
+ channelId: string,
+ userId: string,
+ threadId: ThreadId
+): TypingUsersByChannel {
+ const prevChannelMap = prev.get(channelId);
+ if (!prevChannelMap) return prev;
+
+ const prevThreadUsers = prevChannelMap.get(threadId);
+ if (!prevThreadUsers?.has(userId)) return prev;
+
+ const next = new Map(prev);
+ const channelMap = new Map(prevChannelMap);
+ const threadUsers = new Set(prevThreadUsers);
+
+ threadUsers.delete(userId);
+ if (threadUsers.size === 0) {
+ channelMap.delete(threadId);
+ } else {
+ channelMap.set(threadId, threadUsers);
+ }
+
+ if (channelMap.size === 0) {
+ next.delete(channelId);
+ } else {
+ next.set(channelId, channelMap);
+ }
+
+ return next;
+}
+
+function getOrCreate<K, V>(map: Map<K, V>, key: K, createValue: () => V): V {
+ if (map.has(key)) return map.get(key) as V;
+
+ const value = createValue();
+ map.set(key, value);
+ return value;
+}
+
+function removeTypingTimeout(
+ channelId: string,
+ userId: string,
+ threadId: ThreadId
+): void {
+ const channelTimeouts = typingTimeouts.get(channelId);
+ const threadTimeouts = channelTimeouts?.get(threadId);
+ const timeout = threadTimeouts?.get(userId);
+
+ if (timeout === undefined || !channelTimeouts || !threadTimeouts) return;
+
+ clearTimeout(timeout);
+ threadTimeouts.delete(userId);
+
+ if (threadTimeouts.size === 0) channelTimeouts.delete(threadId);
+ if (channelTimeouts.size === 0) typingTimeouts.delete(channelId);
+}
+
+function setTypingTimeout(
+ channelId: string,
+ userId: string,
+ threadId: ThreadId
+): void {
+ removeTypingTimeout(channelId, userId, threadId);
+
+ const timeout = setTimeout(() => {
+ const currentTimeout = typingTimeouts
+ .get(channelId)
+ ?.get(threadId)
+ ?.get(userId);
+ if (currentTimeout !== timeout) return;
+
+ removeTypingTimeout(channelId, userId, threadId);
+ removeTypingUser(channelId, userId, threadId);
+ }, TYPING_INDICATOR_TIMEOUT_MS);
+
+ const channelTimeouts = getOrCreate(
+ typingTimeouts,
+ channelId,
+ () => new Map<ThreadId, Map<string, ReturnType<typeof setTimeout>>>()
+ );
+ const threadTimeouts = getOrCreate(
+ channelTimeouts,
+ threadId,
+ () => new Map<string, ReturnType<typeof setTimeout>>()
+ );
+
+ threadTimeouts.set(userId, timeout);
+}
+
+export function clearTypingIndicators(): void {
+ for (const channelTimeouts of typingTimeouts.values()) {
+ for (const threadTimeouts of channelTimeouts.values()) {
+ for (const timeout of threadTimeouts.values()) {
+ clearTimeout(timeout);
+ }
+ }
+ }
+
+ typingTimeouts.clear();
+ setTypingUsers(new Map());
+}
function addTypingUser(
channelId: string,
userId: string,
- threadId: string | null = null
+ threadId: ThreadId = null
) {
- setTypingUsers((prev) => {
- const newMap = new Map(prev);
- const channelMap =
- newMap.get(channelId) ?? new Map<string | null, Set<string>>();
- const threadUsers = channelMap.get(threadId) ?? new Set<string>();
- channelMap.set(threadId, new Set([...threadUsers, userId]));
- newMap.set(channelId, channelMap);
- return newMap;
- });
+ setTypingUsers((prev) =>
+ withAddedTypingUser(prev, channelId, userId, threadId)
+ );
+ setTypingTimeout(channelId, userId, threadId);
}
function removeTypingUser(
channelId: string,
userId: string,
- threadId: string | null = null
+ threadId: ThreadId = null
) {
+ removeTypingTimeout(channelId, userId, threadId);
setTypingUsers((prev) => {
- const newMap = new Map(prev);
- const channelMap = newMap.get(channelId);
- if (!channelMap) return prev;
-
- const threadUsers = channelMap.get(threadId);
- if (!threadUsers) return prev;
-
- const newThreadUsers = new Set(
- [...threadUsers].filter((id) => id !== userId)
- );
- channelMap.set(threadId, newThreadUsers);
- newMap.set(channelId, channelMap);
- return newMap;
+ return withoutTypingUser(prev, channelId, userId, threadId);
});
}
@@ -67,7 +180,7 @@ function removeTypingUser(
*/
export function getTypingUsersForChannel(
channelId: string,
- threadId: string | null = null
+ threadId: ThreadId = null
): Set<string> {
return typingUsers().get(channelId)?.get(threadId) ?? new Set();
}
@@ -104,11 +217,6 @@ type PostTypingUpdateVars = {
threadId?: string;
};
-const typingNonce = createMutationNonce<PostTypingUpdateVars>(
- ChannelNonceKeys.TYPING,
- (v) => `${v.channelId}:${v.action}:${v.threadId ?? 'main'}`
-);
-
export function usePostTypingUpdateMutation() {
return useMutation(() => ({
gcTime: 0,
@@ -117,19 +225,8 @@ export function usePostTypingUpdateMutation() {
channel_id: vars.channelId,
action: vars.action,
thread_id: vars.threadId,
- nonce: typingNonce.use(vars),
});
},
- onMutate: (vars: PostTypingUpdateVars) => {
- typingNonce.prepare(vars);
- },
- onSettled: (
- _data: unknown,
- _error: Error | null,
- vars: PostTypingUpdateVars
- ) => {
- typingNonce.cleanup(vars);
- },
onError: (error: Error) => {
console.error('failed to post typing update', error);
},