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(comments): catch up on comments missed while the tab was in the background (#7007)

gbirman4ae6bd1da19d
diff --git a/apps/web/src/lib/queries/messages/tests/subscription.test.ts b/apps/web/src/lib/queries/messages/tests/subscription.test.ts
index 4d8e0dec08..8318add5c0 100644
--- a/apps/web/src/lib/queries/messages/tests/subscription.test.ts
+++ b/apps/web/src/lib/queries/messages/tests/subscription.test.ts
@@ -1,5 +1,6 @@
import {
useEntitySubscription,
+ useRefreshTrackedEntitiesOnFocus,
useReopenTrackedEntitiesOnReconnect,
} from '@service-connection/client';
import type { MessageParent } from '@service-storage/messages';
@@ -7,14 +8,19 @@ import { createRoot, createSignal } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { useMessageThreadQuery } from '../thread-replies';
-const mocks = vi.hoisted(() => ({
- send: vi.fn(),
- clearStream: vi.fn(),
- focused: vi.fn(() => true),
- invalidate: vi.fn().mockResolvedValue(undefined),
- updates: new Set<(event: unknown) => void>(),
- reconnects: new Set<() => void>(),
-}));
+const mocks = await vi.hoisted(async () => {
+ const { createSignal } = await import('solid-js');
+ const [focused, setFocused] = createSignal(true);
+ return {
+ send: vi.fn(),
+ clearStream: vi.fn(),
+ focused,
+ setFocused,
+ invalidate: vi.fn().mockResolvedValue(undefined),
+ updates: new Set<(event: unknown) => void>(),
+ reconnects: new Set<() => void>(),
+ };
+});
vi.mock('@core/signal/tabFocus', () => ({ isTabFocused: mocks.focused }));
vi.mock('@service-connection/stream', () => ({
clearStream: mocks.clearStream,
@@ -75,7 +81,7 @@ function sent(action: string, id = parent.id) {
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
- mocks.focused.mockReturnValue(true);
+ mocks.setFocused(true);
});
afterEach(() => {
for (const dispose of disposers.splice(0)) dispose();
@@ -179,14 +185,45 @@ it('refreshes cached messages after all views close and the parent reopens', ()
it('suspends the shared heartbeat in a background tab', () => {
mountBlock();
- mocks.focused.mockReturnValue(false);
+ mocks.setFocused(false);
vi.advanceTimersByTime(40_000);
expect(sent('ping')).toHaveLength(0);
- mocks.focused.mockReturnValue(true);
+ mocks.setFocused(true);
vi.advanceTimersByTime(20_000);
expect(sent('ping')).toHaveLength(1);
});
+it('pings on refocus and refreshes only views left unseen past the gateway window', () => {
+ mount(useRefreshTrackedEntitiesOnFocus);
+ mount(() =>
+ useMessageThreadQuery(
+ () => parent,
+ () => 'root'
+ )
+ );
+ mocks.invalidate.mockClear();
+
+ // Heartbeats keep the gateway's view fresh while focused.
+ vi.advanceTimersByTime(80_000);
+ expect(sent('ping')).toHaveLength(4);
+ mocks.setFocused(false);
+ vi.advanceTimersByTime(30_000);
+ mocks.setFocused(true);
+ expect(sent('ping')).toHaveLength(5);
+ expect(mocks.invalidate).not.toHaveBeenCalled();
+
+ // Away past the window: the gateway stopped sending this parent's events.
+ mocks.setFocused(false);
+ vi.advanceTimersByTime(60_000);
+ expect(sent('ping')).toHaveLength(5);
+ mocks.setFocused(true);
+ expect(sent('ping')).toHaveLength(6);
+ expect(mocks.invalidate).toHaveBeenCalledTimes(3);
+ expect(mocks.invalidate).toHaveBeenCalledWith({
+ queryKey: ['messages', 'threadReplies', parent],
+ });
+});
+
it('moves the drawer subscription with its source and reopens all remaining owners on reconnect', () => {
mountBlock();
const [source, setSource] = createSignal(parent);
diff --git a/apps/web/src/lib/service-clients/service-connection/client.ts b/apps/web/src/lib/service-clients/service-connection/client.ts
index ebc04526cb..24c67082be 100644
--- a/apps/web/src/lib/service-clients/service-connection/client.ts
+++ b/apps/web/src/lib/service-clients/service-connection/client.ts
@@ -21,12 +21,18 @@ interface TrackedEntity {
entityType: TrackEntityMessage['entity_type'];
count: number;
heartbeat: ReturnType<typeof setInterval>;
+ /** When this tab last told the gateway it is watching, by `open` or `ping`. */
+ lastSeen: number;
refreshCallbacks: Map<EntityRefresh, number>;
}
const trackedEntities: Map<EntityId, TrackedEntity> = new Map();
type EntityTarget = Pick<TrackEntityMessage, 'entity_id' | 'entity_type'>;
type EntityRefresh = (entity: EntityTarget) => void;
+// The gateway sends an entity's events only to connections that opened or
+// pinged it this recently (connection_gateway's DEFAULT_TIMEOUT_THRESHOLD).
+const GATEWAY_ACTIVITY_WINDOW_MS = 60_000;
+
export const connectionGatewayClient = {
async trackEntity(args: TrackEntityMessage) {
const tracked = trackedEntities.get(args.entity_id);
@@ -45,9 +51,12 @@ export const connectionGatewayClient = {
action: 'ping',
});
}, 20_000),
+ lastSeen: Date.now(),
refreshCallbacks: new Map(),
});
}
+ } else if (args.action === 'ping') {
+ if (tracked) tracked.lastSeen = Date.now();
} else if (args.action === 'close') {
if (!tracked) return ok({});
else if (tracked.count > 1) {
@@ -67,7 +76,7 @@ export const connectionGatewayClient = {
},
};
-/** Share tracking and heartbeats; refresh once on subscription and reconnect. */
+/** Share tracking and heartbeats; refresh once on subscription, reconnect, and refocus after a long absence. */
export function useEntitySubscription(
entity: Accessor<EntityTarget | undefined>,
onRefresh?: EntityRefresh
@@ -109,17 +118,46 @@ export function useEntitySubscription(
*/
export function useReopenTrackedEntitiesOnReconnect(): void {
createReconnectEffect(ws, () => {
- for (const [
- entity_id,
- { entityType, refreshCallbacks },
- ] of trackedEntities) {
- const entity = { entity_id, entity_type: entityType };
+ for (const [entity_id, tracked] of trackedEntities) {
+ const entity = { entity_id, entity_type: tracked.entityType };
ws.send({
type: 'track_entity',
...entity,
action: 'open',
});
- for (const onRefresh of refreshCallbacks.keys()) onRefresh(entity);
+ tracked.lastSeen = Date.now();
+ for (const onRefresh of tracked.refreshCallbacks.keys())
+ onRefresh(entity);
}
});
}
+
+/**
+ * Pings every tracked entity as soon as the tab regains focus, since the heartbeat pauses in
+ * the background. A tab that went unseen longer than the gateway's activity window was left
+ * out of the entity's events meanwhile, so its views refresh as they do after a reconnect.
+ */
+export function useRefreshTrackedEntitiesOnFocus(): void {
+ createEffect(
+ on(
+ isTabFocused,
+ (focused) => {
+ if (!focused) return;
+ const now = Date.now();
+ for (const [entity_id, tracked] of trackedEntities) {
+ const entity = { entity_id, entity_type: tracked.entityType };
+ const missedEvents =
+ now - tracked.lastSeen >= GATEWAY_ACTIVITY_WINDOW_MS;
+ void connectionGatewayClient.trackEntity({
+ ...entity,
+ action: 'ping',
+ });
+ if (missedEvents)
+ for (const onRefresh of tracked.refreshCallbacks.keys())
+ onRefresh(entity);
+ }
+ },
+ { defer: true }
+ )
+ );
+}
diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsx
index 2e03b6cf02..a08339bfb2 100644
--- a/apps/web/src/routes/Root.tsx
+++ b/apps/web/src/routes/Root.tsx
@@ -90,7 +90,10 @@ import {
import { useChatRenameWebsocketSync } from '@queries/chat';
import { QuerySyncProvider } from '@queries/sync/SyncProvider';
import { MutationUndoProvider } from '@queries/undo';
-import { useReopenTrackedEntitiesOnReconnect } from '@service-connection/client';
+import {
+ useRefreshTrackedEntitiesOnFocus,
+ useReopenTrackedEntitiesOnReconnect,
+} from '@service-connection/client';
import { ws as connectionGatewayWebsocket } from '@service-connection/websocket';
import { MetaProvider, Title } from '@solidjs/meta';
import {
@@ -344,6 +347,7 @@ function ConfiguredGlobalAppStateProvider(props: ParentProps) {
const notifInterface = usePlatformNotificationState();
useChatRenameWebsocketSync();
useReopenTrackedEntitiesOnReconnect();
+ useRefreshTrackedEntitiesOnFocus();
if (isNativeMobilePlatform()) {
useInvalidateQueriesOnReconnect();