Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
99.3 KB
Raw Blame
"use client";
import { docKeys } from "../docs/queries";
import { applyDocUpdated } from "../docs/realtime";

import { weixinKeys } from "../weixin/queries";


import { useEffect, useRef } from "react";
import { forgetLocalSearchIndex } from "../search-index/instance";
import { useQueryClient, type InfiniteData, type QueryClient, type QueryFilters } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import {
  holdSyncCauses,
  registerRealtimeSyncTarget,
  runWithSyncCauses,
  type SyncCauses,
} from "../api/realtime-observer";
import type { WSMessage } from "../types/events";
import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
import { createLogger } from "../logger";
import { clearWorkspaceStorage } from "../platform/storage-cleanup";
import { defaultStorage } from "../platform/storage";
import { getCurrentWsId, getCurrentSlug } from "../platform/workspace-storage";
import { issueKeys } from "../issues/queries";
import type { SidebarIssuesRequest } from "../issues/sidebar-list";
import { refreshIssueUnread } from "../issues/unread";
import { refreshSubscribedIssues, subscribedIssueKeys } from "../issues/subscribed";
import { projectKeys } from "../projects/queries";
import { pinKeys } from "../pins/queries";
import { autopilotKeys } from "../autopilots/queries";
import { runtimeKeys } from "../runtimes/queries";
import { labelKeys } from "../labels/queries";
import { propertyKeys } from "../properties/queries";
import { issueStatusKeys } from "../issue-statuses/queries";
import { issueWorkflowKeys } from "../issue-workflows/queries";
import { issueViewKeys } from "../issue-views/queries";
import { issueViewPrefKeys } from "../issue-views/preferences";
import {
  agentTaskSnapshotKeys,
  workspaceWorkingAgentsKeys,
  agentActivityKeys,
  agentRunCountsKeys,
  agentTasksKeys,
} from "../agents/queries";
import { githubKeys } from "../github/queries";
import { useGitHubConnectionStore } from "../github/connection-store";
import { larkKeys } from "../lark/queries";
import { slackKeys } from "../slack/queries";
import { dingtalkKeys } from "../dingtalk/queries";
import { wecomKeys } from "../wecom/queries";
import { telegramKeys } from "../telegram/queries";
import {
  onIssueCreated,
  onIssueUpdated,
  onIssueDuplicateMarkChanged,
  onIssueDeleted,
  onIssueLabelsChanged,
  onIssuePropertiesChanged,
  onIssueMetadataChanged,
  onIssueAuxiliaryRevision,
  onIssueReactionAdded,
  onIssueReactionRemoved,
  invalidateIssueOwnerProjections,
  invalidateProjectProgress,
} from "../issues/ws-updaters";
import {
  invalidateLastActivitySortedIssueLists,
  invalidateUpdatedAtSortedIssueLists,
} from "../issues/cache-coordinator";
import { onInboxNew, onInboxInvalidate, onInboxIssueStatusChanged, onInboxIssueDeleted, onInboxSummaryInvalidate } from "../inbox/ws-updaters";
import { noteInboxAutoArchive } from "../inbox/auto-archive";
import {
  notificationPreferenceOptions,
  notificationPreferenceKeys,
} from "../notification-preferences/queries";
import { workspaceKeys, workspaceListOptions } from "../workspace/queries";
import { memberLimitKeys } from "../billing/member-limit";
import { isWorkspaceDeletePending } from "../workspace/pending-delete";
import {
  showSystemNotification,
  systemNotificationSuppressedByFocus,
  type SystemNotificationPayload,
} from "../platform/system-notification";
import type { Workspace } from "../types/workspace";
import type { AgentTask } from "../types/agent";
import {
  chatKeys,
  isTaskMessageTimelineHeld,
  mergeTaskMessagesBySeq,
  sortChatSessions,
  QUICK_ACTIONS_PENDING_TIMEOUT_MS,
} from "../chat/queries";
import { useChatStore } from "../chat";
import { connectedAppsKeys } from "../connected-apps/queries";
import { upsertChatMessageToCaches } from "../chat/message-cache";
import {
  promotePendingChatTask,
  removePendingChatTask,
} from "../chat/pending";
import { resolvePostAuthDestination, useHasOnboarded } from "../paths";
import type {
  IssueTableFacetsRequest,
  IssueTableQuerySpec,
  MemberAddedPayload,
  WorkspaceDeletedPayload,
  WorkspaceUpdatedPayload,
  MemberRemovedPayload,
  IssueUpdatedPayload,
  IssueCreatedPayload,
  IssueDeletedPayload,
  IssueAttachmentsChangedPayload,
  IssueLabelsChangedPayload,
  IssueUnreadChangedPayload,
  IssueMetadataChangedPayload,
  IssuePropertiesChangedPayload,
  InboxNewPayload,
  InboxBatchArchivedPayload,
  InboxItem,
  NotificationPreferenceResponse,
  CommentCreatedPayload,
  CommentUpdatedPayload,
  CommentDeletedPayload,
  CommentResolvedPayload,
  CommentUnresolvedPayload,
  ActivityCreatedPayload,
  ReactionAddedPayload,
  ReactionRemovedPayload,
  IssueReactionAddedPayload,
  IssueReactionRemovedPayload,
  SubscriberAddedPayload,
  SubscriberRemovedPayload,
  TaskMessagePayload,
  TaskQueuedPayload,
  TaskDispatchPayload,
  TaskRunningPayload,
  TaskWaitingLocalDirectoryPayload,
  TaskCompletedPayload,
  TaskFailedPayload,
  TaskCancelledPayload,
  ChatDonePayload,
  ChatReplyNotificationPayload,
  ChatQuickActionsPayload,
  ChatQuickActionsPendingState,
  ChatQuickActionsFailureState,
  ChatCancelFinalizedPayload,
  ChatWakeupChangedPayload,
  ChatWakeup,
  ChatMessage,
  ChatMessageEventPayload,
  ChatPendingTask,
  ChatMessagesPage,
  ChatSession,
  ChatSessionCreatedPayload,
  InvitationCreatedPayload,
} from "../types";

const chatWsLogger = createLogger("chat.ws");

/**
 * Window over which incoming `task:message` frames are batched into a single
 * timeline cache write (MUL-6396).
 *
 * The first frame after an idle window lands immediately; that is the
 * user-visible leading edge. It also arms a fixed 100ms window for subsequent
 * frames, not reset by later ones, so a sustained stream still costs at most
 * one additional merge/render per window instead of one per frame.
 */
const TASK_MESSAGE_FLUSH_MS = 100;

const logger = createLogger("realtime-sync");

export function invalidateChatMessageQueries(
  qc: QueryClient,
  sessionId: string,
) {
  qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
  qc.invalidateQueries({ queryKey: chatKeys.messagesPage(sessionId) });
}

// refetchPendingChatAggregate marks the current user's cross-session pending
// aggregate stale so it is refetched from the permission-filtering endpoint
// (/api/chat/pending-tasks[/has-any]).
//
// SECURITY (review on PR #5018 / MUL-4159): this is deliberately an
// invalidate, NOT an optimistic setQueryData. Chat `task:*` events are a
// workspace fanout delivered to every member with no creator / agent
// visibility in the payload, so optimistically writing the aggregate from them
// would let one member's task flip another member's FAB to has_pending=true,
// bypassing the server-side permission filter. Invalidation forces the
// authoritative, creator+agent-scoped server response to be the source of
// truth. The has-any key is nested under pendingTasks, so invalidating
// pendingTasks refreshes both the detailed list and the boolean fast-path.
export function refetchPendingChatAggregate(
  qc: QueryClient,
  wsId: string | null | undefined,
) {
  if (!wsId) return;
  qc.invalidateQueries({ queryKey: chatKeys.pendingTasks(wsId) });
}

/**
 * Apply a chat:message event: write the turn's USER message into the message
 * caches, then reconcile authoritatively (MUL-5711).
 *
 * The payload has always carried the whole message; this handler used to read
 * `chat_session_id` off it and drop the rest, which made a human's own prompt
 * the one row that reached the transcript ONLY through the refetch below. Any
 * client that did not write it locally — a second window or device, a send
 * whose HTTP response failed after the server committed, a surface mounting
 * mid-flight — lost it whenever that refetch was dropped, most reliably to the
 * chat:quick_actions cancel. Both caches are staleTime: Infinity, so nothing
 * re-fetched afterwards and the prompt stayed missing until a remount.
 *
 * Only `role: "user"` is written. SendChatMessage is the event's one producer,
 * and an assistant row fabricated from this payload would carry no elapsed_ms /
 * message_kind / quick_actions while still claiming the id that
 * applyChatDoneToCache is about to write properly.
 *
 * The invalidate stays: this payload has no `attachments`, so the reconciling
 * refetch is what fills them in for clients that did not send the message.
 */
export function applyChatMessageToCache(
  qc: QueryClient,
  payload: ChatMessageEventPayload,
) {
  const sessionId = payload.chat_session_id;
  if (payload.role === "user" && payload.message_id) {
    upsertChatMessageToCaches(qc, sessionId, {
      id: payload.message_id,
      chat_session_id: sessionId,
      role: "user",
      content: payload.content ?? "",
      task_id: payload.task_id ?? null,
      created_at: payload.created_at ?? new Date().toISOString(),
    });
  }
  invalidateChatMessageQueries(qc, sessionId);
  qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
}

export function applyChatDoneToCache(
  qc: QueryClient,
  payload: ChatDonePayload,
) {
  const sessionId = payload.chat_session_id;
  const taskId = payload.task_id;
  const messageId = payload.message_id;
  const content = payload.content;
  if (messageId && (content !== undefined || (payload.quick_actions?.length ?? 0) > 0)) {
    const assistant: ChatMessage = {
      id: messageId,
      chat_session_id: sessionId,
      role: "assistant",
      content: content ?? "",
      task_id: taskId,
      created_at: payload.created_at ?? new Date().toISOString(),
      elapsed_ms: payload.elapsed_ms ?? null,
      // Carry the kind so a no_response turn renders its placeholder inline
      // without waiting for the reconciling refetch (MUL-4351). Missing →
      // "message" for older servers.
      message_kind: payload.message_kind ?? "message",
      ...(payload.quick_actions !== undefined
        ? { quick_actions: payload.quick_actions }
        : {}),
    };
    // Idempotent against reconnect replay and against a refetch that already
    // landed this row.
    upsertChatMessageToCaches(qc, sessionId, assistant);
  }
  // Replacement is in the messages list now; remove only this task. If a
  // follow-up is queued, it becomes the next head in the same render tick.
  qc.setQueryData<ChatPendingTask>(
    chatKeys.pendingTask(sessionId),
    (old) => removePendingChatTask(old, taskId),
  );
  // Raise/clear the quick-actions placeholder marker. Kept OUTSIDE the
  // message caches deliberately: the authoritative refetch below replaces
  // those, and a flag stored on the message would vanish with it. Explicit
  // `=== true` — older servers omit the field entirely.
  qc.setQueryData<ChatQuickActionsPendingState | null>(
    chatKeys.quickActionsPending(sessionId),
    payload.quick_actions_pending === true && messageId
      ? {
          message_id: messageId,
          task_id: taskId,
          expires_at: Date.now() + QUICK_ACTIONS_PENDING_TIMEOUT_MS,
        }
      : null,
  );
  // Authoritative refetch reconciles redaction / migrations / clients
  // that took the fallback branch above.
  invalidateChatMessageQueries(qc, sessionId);
  qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
}

/**
 * Apply a chat:quick_actions supplement: patch the identified assistant
 * message's quick_actions in both message caches and resolve the pending
 * placeholder. An empty/missing list is terminal ("no suggestions this
 * turn") — the placeholder still resolves.
 *
 * `payload.failed` marks a resolution whose regeneration failed: the carried
 * actions are the turn's UNCHANGED prior pills, so the patch is a no-op, but a
 * failure signal is raised for a view to toast — otherwise an explicit refresh
 * that failed would look identical to one that succeeded with the same
 * suggestions (MUL-5149 review).
 */
export async function applyChatQuickActionsToCache(
  qc: QueryClient,
  payload: ChatQuickActionsPayload,
) {
  const sessionId = payload.chat_session_id;
  const actions = payload.quick_actions ?? [];
  const patch = (m: ChatMessage): ChatMessage =>
    m.id === payload.message_id ? { ...m, quick_actions: actions } : m;
  if (actions.length > 0) {
    // chat:done's invalidate may still have a messages refetch in flight that
    // read the assistant row BEFORE the daemon persisted these actions. Cancel
    // it first so its actions-less response can't land after — and overwrite —
    // the patch below. Both message caches are staleTime: Infinity, so such an
    // overwrite would never self-heal (MUL-5149 stale-refetch race). Cancelling
    // before setQueryData is required: cancelQueries reverts to the pre-fetch
    // state, so patching first would be undone by the revert.
    await Promise.all([
      qc.cancelQueries({ queryKey: chatKeys.messages(sessionId) }),
      qc.cancelQueries({ queryKey: chatKeys.messagesPage(sessionId) }),
    ]);
    qc.setQueryData<ChatMessage[] | undefined>(
      chatKeys.messages(sessionId),
      (old) => old?.map(patch),
    );
    qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
      chatKeys.messagesPage(sessionId),
      (old) =>
        old
          ? {
              ...old,
              pages: old.pages.map((page) => ({
                ...page,
                messages: page.messages.map(patch),
              })),
            }
          : old,
    );
    // Settle the cancel (MUL-5711). cancelQueries defaults to `revert: true`,
    // so the line above does more than ignore the in-flight response — it rolls
    // the cache back to the snapshot taken when that fetch STARTED, dropping
    // rows only that response carried (a peer's user message, anything that
    // landed while this surface was unmounted). With staleTime: Infinity and no
    // further trigger, the hole survived until a remount. Re-invalidating costs
    // one request per supplement and cannot lose the pills: the server persists
    // the actions BEFORE broadcasting this event (SupplementChatQuickActions),
    // so the refetch this schedules reads them back.
    invalidateChatMessageQueries(qc, sessionId);
  }
  // Resolve the marker only when it belongs to THIS message: a late
  // supplement for turn N must not clear the marker turn N+1's chat:done
  // just raised (near-unreachable — the daemon cancels stale passes — but
  // the guard costs one comparison).
  qc.setQueryData<ChatQuickActionsPendingState | null>(
    chatKeys.quickActionsPending(sessionId),
    (current) =>
      current && current.message_id !== payload.message_id ? current : null,
  );
  // Raise a one-shot failure signal on an explicit refresh whose regeneration
  // failed. A view consumes it to toast and clears it; the `at` nonce keeps a
  // repeat failure on the same turn from being deduped away.
  if (payload.failed === true) {
    qc.setQueryData<ChatQuickActionsFailureState | null>(
      chatKeys.quickActionsFailure(sessionId),
      { message_id: payload.message_id, at: Date.now() },
    );
  }
}

type ChatSessionUpdatedPayload = {
  chat_session_id: string;
  title?: string;
  project_id?: string | null;
  pinned?: boolean;
  status?: "active" | "archived";
  updated_at?: string;
};

/**
 * Patch the cached sessions row for a `chat:session_updated` event (rename,
 * pin/unpin, archive/unarchive from any tab/device) instead of refetching the
 * whole list. `pinned` is present only on pin/unpin events and `status` only on
 * archive/unarchive; a plain rename omits both, so absent fields leave existing
 * state untouched. When either changes we re-sort so the row lands in the right
 * place (pin → top; archive → the other list) like the server order.
 *
 * Archiving MUST also zero the row's unread here: the server payload carries
 * only status/updated_at, and chatSessionsOptions is `staleTime: Infinity`, so a
 * stale cache in another tab/device would otherwise keep an archived session's
 * unread badge lit forever — the same MUL-4360 stuck-badge bug, one surface over.
 * This mirrors the archive mutation's optimistic patch and the backend deriving
 * unread_count=0 for archived rows. Unarchive does NOT fabricate a count — the
 * true unread state comes back from the server refetch (last_read_at is
 * untouched), so we leave the row's unread fields as-is for `active`.
 */
export function applyChatSessionUpdatedToCache(
  qc: QueryClient,
  wsId: string,
  payload: ChatSessionUpdatedPayload,
): void {
  qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) => {
    if (!old) return old;
    const next = old.map((s) =>
      s.id === payload.chat_session_id
        ? {
            ...s,
            title: payload.title ?? s.title,
            ...("project_id" in payload ? { project_id: payload.project_id } : {}),
            pinned: payload.pinned ?? s.pinned,
            status: payload.status ?? s.status,
            updated_at: payload.updated_at ?? s.updated_at,
            ...(payload.status === "archived"
              ? { unread_count: 0, has_unread: false }
              : {}),
          }
        : s,
    );
    return payload.pinned === undefined && payload.status === undefined
      ? next
      : sortChatSessions(next);
  });
}

function removeChatMessageFromPageCache(
  qc: QueryClient,
  sessionId: string,
  messageId: string,
) {
  qc.setQueryData<InfiniteData<ChatMessagesPage> | undefined>(
    chatKeys.messagesPage(sessionId),
    (old) => {
      if (!old) return old;
      return {
        ...old,
        pages: old.pages.map((page) => ({
          ...page,
          messages: page.messages.filter((m) => m.id !== messageId),
        })),
      };
    },
  );
}

export function removeChatMessageFromCaches(
  qc: QueryClient,
  sessionId: string,
  messageId: string,
) {
  qc.setQueryData<ChatMessage[]>(
    chatKeys.messages(sessionId),
    (old) => old?.filter((m) => m.id !== messageId) ?? old,
  );
  removeChatMessageFromPageCache(qc, sessionId, messageId);
}

/**
 * Apply a chat:cancel_finalized event (#5219): the deferred outcome of a
 * cancelled chat task, settled after the daemon's transcript flush.
 *
 * - outcome "stopped": a late "Stopped." assistant row was persisted —
 *   insert it exactly like a chat:done message.
 * - outcome "restored": the triggering user message was deleted — drop it
 *   from the caches. The deleted prompt itself never rides this
 *   workspace-wide broadcast: it is durable server-side and only the
 *   initiator's client refetches it through the creator-authorized
 *   draft-restores query, which the session's composer applies and consumes.
 *
 * The draft-restores invalidation is gated to the task's initiator and fails
 * closed when initiator_user_id is missing — nothing is lost either way,
 * because the durable restore is fetched again on the next composer mount or
 * network reconnect. Cache patches stay unconditional — they are no-ops for
 * anyone not viewing the session.
 */
export function applyChatCancelFinalizedToCache(
  qc: QueryClient,
  payload: ChatCancelFinalizedPayload,
  currentUserId?: string,
) {
  const sessionId = payload.chat_session_id;
  if (!sessionId) return;
  if (payload.outcome === "stopped") {
    applyChatDoneToCache(qc, {
      chat_session_id: sessionId,
      task_id: payload.task_id,
      message_id: payload.message_id,
      content: payload.content,
      elapsed_ms: payload.elapsed_ms,
      created_at: payload.created_at,
      message_kind: payload.message_kind,
    });
    return;
  }
  if (payload.outcome === "restored") {
    if (payload.message_id) {
      removeChatMessageFromCaches(qc, sessionId, payload.message_id);
    }
    // Deferred finalization can arrive after a queued successor was promoted.
    // Remove only the cancelled task so a late restore cannot hide newer work.
    qc.setQueryData<ChatPendingTask>(
      chatKeys.pendingTask(sessionId),
      (old) => removePendingChatTask(old, payload.task_id),
    );
    invalidateChatMessageQueries(qc, sessionId);
    qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
    const isInitiator =
      !!payload.initiator_user_id &&
      !!currentUserId &&
      payload.initiator_user_id === currentUserId;
    if (isInitiator) {
      void qc.invalidateQueries({ queryKey: chatKeys.draftRestores(sessionId) });
    }
  }
}

/**
 * Apply a workspace:updated event directly to the cached workspace list.
 * If the incoming `issue_prefix` differs from what's currently cached, also
 * invalidates issueKeys.all for that workspace, since every issue's rendered
 * identifier (`MUL-123`) is recomputed from the workspace prefix at read time.
 *
 * If the workspace isn't in the cached list (first observation), we
 * conservatively invalidate — the prefix is effectively "new" relative to
 * what's cached, so any issues already loaded under the old prefix would
 * be stale anyway.
 */
export function applyWorkspaceUpdatedToCache(
  qc: QueryClient,
  payload: WorkspaceUpdatedPayload,
): void {
  const next = payload.workspace;
  if (next?.id) {
    const list = qc.getQueryData<Workspace[]>(workspaceKeys.list());
    const cached = list?.find((w) => w.id === next.id) ?? null;
    if (cached && cached.issue_prefix !== next.issue_prefix) {
      qc.invalidateQueries({ queryKey: issueKeys.all(next.id) });
    }
    if (cached && list) {
      qc.setQueryData<Workspace[]>(
        workspaceKeys.list(),
        list.map((workspace) => (workspace.id === next.id ? next : workspace)),
      );
      return;
    }
    // Do not seed an absent list with one workspace: staleTime is Infinity,
    // so doing so would hide every other membership until a hard refresh.
    qc.invalidateQueries({ queryKey: issueKeys.all(next.id) });
  }
  qc.invalidateQueries({ queryKey: workspaceKeys.list() });
}

/**
 * Resolves the slug of the workspace an inbox item originated from, via the
 * cached workspace list (fetched once when the cache is cold).
 *
 * Desktop notification routing must pin to the *source* workspace of the
 * inbox item, not the currently active one: the user can be on workspace B
 * when an `inbox:new` for workspace A arrives, and macOS Notification Center
 * holds banners across workspace switches. Returns null when the workspace
 * cannot be resolved — callers must NOT fall back to the current slug (that
 * recreates the wrong-workspace routing this exists to prevent, #3766) and
 * should show the notification without a deep link instead.
 */
export async function resolveInboxSourceSlug(
  qc: QueryClient,
  workspaceId: string,
): Promise<string | null> {
  if (!workspaceId) return null;
  try {
    const workspaces = await qc.ensureQueryData(workspaceListOptions());
    return workspaces?.find((w) => w.id === workspaceId)?.slug ?? null;
  } catch {
    // Workspace list unavailable (e.g. network hiccup): degrade to a
    // link-less notification rather than guessing a slug.
    return null;
  }
}

/**
 * Handles an `inbox:new` event end-to-end: inbox cache invalidation, the
 * focus / mute checks, and the native OS banner. Exported so the handler
 * behavior (not just slug resolution) is testable.
 *
 * Every workspace-scoped read here keys on the ITEM's workspace
 * (`item.workspace_id`), never the currently active one (#3766): the cache
 * invalidation must refresh the source workspace's inbox list / unread
 * count / dock badge, the mute check must honor the source workspace's
 * preference, and the deep link must carry the source workspace's slug.
 */
export async function handleInboxNew(
  qc: QueryClient,
  item: InboxItem,
): Promise<void> {
  const sourceWsId = item.workspace_id;
  if (sourceWsId) void onInboxNew(qc, sourceWsId, item);
  // A new item in ANY workspace can light the workspace-switcher dot, so
  // refresh the cross-workspace summary regardless of the active workspace.
  void onInboxSummaryInvalidate(qc);
  // Moving to in_progress is routine progress (an agent picking the issue
  // up), the same exception the server's delegated-handoff rule makes. The
  // row still lands in the inbox; it just doesn't interrupt with a banner.
  if (item.type === "status_changed" && item.details?.to === "in_progress") return;
  // Fire a native OS notification only when the app isn't focused. When
  // the user is already looking at Multica, the inbox sidebar's unread
  // styling is enough — no need to interrupt with a banner. `desktopAPI`
  // is injected by the preload script; its absence (web app) skips silently.
  if (systemNotificationSuppressedByFocus()) return;
  // Resolve the source workspace's slug once: it pins BOTH the mute check
  // and the deep link to the workspace the inbox item BELONGS to, never the
  // currently active one. Reading `getCurrentSlug()` here was the source of
  // wrong-workspace routing (#3766): an `inbox:new` from workspace A arriving
  // while workspace B is active emitted a notification carrying B's slug and
  // A's issue id, deep-linking to an issue B doesn't have.
  const slug = await resolveInboxSourceSlug(qc, sourceWsId);
  // Respect the SOURCE workspace's system-notification preference. Keying the
  // query on `sourceWsId` is not enough: the request resolves its workspace
  // from the `X-Workspace-Slug` header, which follows the ACTIVE workspace —
  // so a cold-cache lookup while viewing B would read B's mute setting and
  // cache it under A's key. Passing the source slug scopes the fetch to A.
  // When the slug can't be resolved we read only an already-warm cache
  // (populated earlier with the correct workspace context) rather than fetch
  // with the wrong one; on network failure we fall through to the default
  // ("all") rather than swallow the banner.
  if (sourceWsId) {
    try {
      const prefData = slug
        ? await qc.ensureQueryData(
            notificationPreferenceOptions(sourceWsId, slug),
          )
        : qc.getQueryData<NotificationPreferenceResponse>(
            notificationPreferenceKeys.all(sourceWsId),
          );
      if (prefData?.preferences?.system_notifications === "muted") return;
    } catch {
      // Fall through with default behavior.
    }
  }
  // `issueKey` matches the inbox page's URL selector (issue id when the
  // item is attached to an issue, otherwise the inbox item id). `itemId`
  // is the inbox row's own id, needed to fire markInboxRead on click.
  // A null slug (workspace list unavailable / item from a workspace this
  // client can't see) still shows the banner — the user should learn about
  // the inbox item — but with an empty slug so the click is a no-op
  // (the inbox bridge ignores empty slugs) instead of routing wrong.
  const payload: SystemNotificationPayload = {
    slug: slug ?? "",
    itemId: item.id,
    issueKey: item.issue_id ?? item.id,
    title: item.title,
    body: item.body ?? "",
  };
  showSystemNotification(payload);
}

export function createChatReplyNotifier(
  qc: QueryClient,
  getUserId: () => string | undefined,
): (payload: ChatReplyNotificationPayload) => Promise<void> {
  const seen = new Set<string>();
  return async (payload) => {
    const messageId = payload.message_id;
    const userId = getUserId();
    if (!payload.workspace_id || !messageId || !payload.chat_session_id || !userId || seen.has(messageId)) return;
    seen.add(messageId);
    if (seen.size > 1_000) seen.delete(seen.values().next().value!);
    if (systemNotificationSuppressedByFocus()) return;

    const slug = await resolveInboxSourceSlug(qc, payload.workspace_id);
    if (!slug) return;
    try {
      const { preferences } = await qc.ensureQueryData(notificationPreferenceOptions(payload.workspace_id, slug));
      if (preferences.system_notifications === "muted" || preferences.chat_replies === "muted") return;
    } catch {
      // Match the existing default-on system-notification behavior.
    }
    if (getUserId() !== userId || systemNotificationSuppressedByFocus()) return;
    showSystemNotification({
      slug,
      itemId: `chat:${messageId}`,
      chatSessionId: payload.chat_session_id,
      title: payload.title,
      body: payload.body,
    });
  };
}

/**
 * Invalidates workspace and account caches. Used after reconnect and when a
 * new WSClient instance is detected (workspace switch) to recover events
 * missed while disconnected.
 */
function invalidateWorkspaceScopedQueries(qc: QueryClient): void {
  const wsId = getCurrentWsId();
  if (wsId) {
    qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
    void refreshIssueUnread(qc, wsId);
    qc.invalidateQueries({ queryKey: subscribedIssueKeys.all(wsId) });
    // Through the inbox's own entry point, not a plain invalidate: a reconnect
    // can land during the list's first load, and a plain invalidate would be
    // answered by the request already on the wire (see refreshInboxQuery).
    void onInboxInvalidate(qc, wsId);
    qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
    qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
    qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });
    qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
    qc.invalidateQueries({ queryKey: workspaceKeys.invitations(wsId) });
    qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: agentActivityKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: agentRunCountsKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: chatKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: labelKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
    // A catalog edit missed while disconnected would otherwise sit behind the
    // 5-minute staleTime — long enough to offer a status the server already
    // archived, or to keep painting its old name.
    qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: issueViewPrefKeys.all(wsId) });
    qc.invalidateQueries({ queryKey: docKeys.all(wsId) });
  }
  // Cross-workspace, so outside the wsId guard: a reconnect may have missed
  // inbox events from any workspace, so re-pull the switcher-dot summary.
  void onInboxSummaryInvalidate(qc);
  // Account invitations can change while only the socket is disconnected,
  // with no browser focus or online event to trigger the fallback refetch.
  qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
  // Per-issue caches are keyed without wsId, so the issueKeys.all(wsId)
  // prefix above does not reach them. They rely entirely on WS events for
  // freshness (staleTime: Infinity), so events missed while disconnected
  // left them stale until a full reload — the inbox showed an agent's new
  // comment while the issue timeline didn't (#3953). Inactive caches only
  // get marked stale here and refetch on next mount; the one mounted issue
  // refetches immediately, same as its own useWSReconnect already does.
  qc.invalidateQueries({ queryKey: issueKeys.timelineAll() });
  qc.invalidateQueries({ queryKey: issueKeys.subscribersAll() });
  qc.invalidateQueries({ queryKey: issueKeys.usageAll() });
  qc.invalidateQueries({ queryKey: issueKeys.attachmentsAll() });
  qc.invalidateQueries({ queryKey: issueKeys.tasksAll() });
  // Per-chat-session caches are also keyed without wsId, so the
  // chatKeys.all(wsId) prefix above only reaches session lists / aggregates.
  // Message streams rely on WS invalidation with staleTime: Infinity; recover
  // sessions that missed chat/task events while the socket was disconnected.
  qc.invalidateQueries({ queryKey: chatKeys.messagesAll() });
  qc.invalidateQueries({ queryKey: chatKeys.messagesPageAll() });
  qc.invalidateQueries({ queryKey: chatKeys.pendingTaskAll() });
  qc.invalidateQueries({ queryKey: chatKeys.taskMessagesAll() });
  // A chat:cancel_finalized broadcast missed while disconnected is exactly
  // what the durable draft-restore rows exist for (#5219) — re-pull them so
  // a mounted composer recovers the prompt without a remount.
  qc.invalidateQueries({ queryKey: chatKeys.draftRestoresAll() });
  qc.invalidateQueries({ queryKey: chatKeys.wakeupsAll() });
  qc.invalidateQueries({ queryKey: workspaceKeys.list() });
}

async function refreshWorkingAgentQueries(
  qc: QueryClient,
  wsId: string,
  causes: SyncCauses,
): Promise<void> {
  const filters: QueryFilters[] = [
    { queryKey: workspaceWorkingAgentsKeys.all(wsId) },
    { queryKey: agentTaskSnapshotKeys.all(wsId) },
    {
      queryKey: issueKeys.tableAll(wsId),
      predicate: ({ queryKey }) => {
        const kind = queryKey[3];
        let spec: IssueTableQuerySpec | undefined;
        if (kind === "facets") {
          const request = queryKey[4] as IssueTableFacetsRequest;
          if (request.facets.some((facet) => facet.kind === "working_agents")) return true;
          spec = request.query;
        } else if (kind === "rows" || kind === "groups") {
          spec = queryKey[4] as IssueTableQuerySpec;
        }
        // An explicit empty id list is still a working filter: its next
        // projection may contain newly started work. Other facets also
        // depend on this membership, not only rows and group descriptors.
        return spec?.filters.working_only === true ||
          spec?.filters.idle_only === true ||
          spec?.filters.working_issue_ids !== undefined;
      },
    },
    {
      queryKey: issueKeys.sidebarAll(wsId),
      predicate: ({ queryKey }) => {
        const request = queryKey[4] as SidebarIssuesRequest | undefined;
        return request?.table.filters.working_only === true || request?.table.filters.idle_only === true;
      },
    },
  ];
  // A lifecycle event during the FIRST fetch must not dedupe onto a response
  // captured before that event. With staleTime=Infinity it could otherwise
  // leave a completed run visible until another event happens to arrive.
  await Promise.all(filters.map((filter) => qc.cancelQueries(filter)));
  await runWithSyncCauses(causes, () =>
    Promise.all(filters.map((filter) => qc.invalidateQueries(filter))),
  );
}

type SyncEventHandler = Parameters<WSClient["on"]>[1];

/**
 * `ws.on` / `ws.onAny` that remember realtime sync's own handlers, so the dev
 * toolbar can replay a frame through them alone. Other subscribers stay out
 * of a replay: some answer an event with a server write, such as reading the
 * inbox notification of the issue on screen.
 */
function replayableSubscriptions(ws: WSClient) {
  const handlers = new Map<string, Set<SyncEventHandler>>();
  const anyHandlers = new Set<(msg: WSMessage) => void>();
  return {
    on(event: Parameters<WSClient["on"]>[0], handler: SyncEventHandler) {
      const set = handlers.get(event) ?? new Set();
      handlers.set(event, set);
      set.add(handler);
      const unsubscribe = ws.on(event, handler);
      return () => {
        set.delete(handler);
        unsubscribe();
      };
    },
    onAny(handler: (msg: WSMessage) => void) {
      anyHandlers.add(handler);
      const unsubscribe = ws.onAny(handler);
      return () => {
        anyHandlers.delete(handler);
        unsubscribe();
      };
    },
    replay(msg: WSMessage) {
      for (const handler of handlers.get(msg.type) ?? []) {
        handler(msg.payload, msg.actor_id, msg.actor_type);
      }
      for (const handler of anyHandlers) handler(msg);
    },
  };
}

function invalidateSquadMemberStatusQueries(qc: QueryClient, wsId: string): void {
  qc.invalidateQueries({
    predicate: (query) => {
      const key = query.queryKey;
      return (
        key[0] === "workspaces" &&
        key[1] === wsId &&
        key[2] === "squads" &&
        key[4] === "members-status"
      );
    },
  });
}

export interface RealtimeSyncStores {
  authStore: UseBoundStore<StoreApi<AuthState>>;
}

/**
 * Centralized WS -> store sync. Called once from WSProvider.
 *
 * Uses the "WS as invalidation signal + refetch" pattern:
 * - onAny handler extracts event prefix and calls the matching store refresh
 * - Debounce per-prefix prevents rapid-fire refetches (e.g. bulk issue updates)
 * - Precise handlers only for side effects (toast, navigation, self-check)
 *
 * Per-issue events (comments, activity, reactions, subscribers) are handled
 * both here (invalidation fallback) and by per-page useWSEvent hooks (granular
 * updates). Daemon register events invalidate runtimes globally; heartbeats
 * are skipped to avoid excessive refetches.
 *
 * @param client - WebSocket client instance (null when not yet connected)
 * @param stores - Platform-created Zustand store instances for auth and workspace
 * @param onToast - Optional callback for showing toast messages (platform-specific)
 */
export function useRealtimeSync(
  client: WSClient | null,
  stores: RealtimeSyncStores,
  onToast?: (message: string, type?: "info" | "error") => void,
) {
  const { authStore } = stores;
  const qc = useQueryClient();

  // Captured via ref so the (rare) hasOnboarded change doesn't re-subscribe
  // every WS handler in this effect. The resolver reads `.current` at the
  // moment workspace-loss fires, which is what we want.
  const hasOnboarded = useHasOnboarded();
  const hasOnboardedRef = useRef(hasOnboarded);
  hasOnboardedRef.current = hasOnboarded;

  // Main sync: onAny -> refreshMap with debounce
  useEffect(() => {
    if (!client) return;
    const ws = replayableSubscriptions(client);
    const releaseSyncTarget = registerRealtimeSyncTarget({
      replay: ws.replay,
      drop: () => client.drop(),
    });

    const refreshMap: Record<string, () => void> = {
      inbox: () => {
        const wsId = getCurrentWsId();
        if (wsId) void onInboxInvalidate(qc, wsId);
        // inbox:read / inbox:archived / inbox:unarchived / batch events arrive
        // here. They can originate from a workspace other than the active one
        // (personal events fan out to all the user's connections), so always
        // refresh the cross-workspace summary — its dot must clear when another
        // workspace's items are read/archived, and light again when an unread
        // item is restored from the archive.
        void onInboxSummaryInvalidate(qc);
      },
      agent: () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
          // Squad members status is derived per agent, so any agent
          // change (status flip, archive, runtime swap) needs to refresh the
          // per-squad members-status cache without refetching the static squad
          // list summary.
          invalidateSquadMemberStatusQueries(qc, wsId);
        }
      },
      member: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });
      },
      // workspace:updated is handled by the specific handler below
      // (compares prefixes to decide whether to also invalidate issues).
      // This generic fallback still fires for workspace:deleted (paired
      // with the specific navigation handler) and any future workspace:*
      // events without dedicated handlers.
      workspace: () => {
        qc.invalidateQueries({ queryKey: workspaceKeys.list() });
      },
      // app_request:changed carries ids only; refetch through the
      // authorized list endpoints.
      app_request: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: connectedAppsKeys.requests(wsId) });
      },
      app_call: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: connectedAppsKeys.calls(wsId) });
      },
      skill: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
      },
      project: () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });
          // Workflow responses include the projects using them. Creating,
          // deleting or changing a project also changes that usage list.
          qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
          // The issue table can filter on a project's status, so a
          // project create/update/delete changes which issues a filtered
          // window holds. The payload carries no previous status to compare
          // against, and project writes are rare, so refresh the table
          // queries unconditionally rather than guess.
          qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
          // Deleting a project deletes the saved views scoped to it.
          qc.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });
        }
      },
      squad: () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });
          // squad:deleted triggers assignee transfer — refresh issues too.
          qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
        }
      },
      label: () => {
        // Label catalogs are independently scoped to issues, agents, and
        // skills. The generic event prefix does not carry the scope into this
        // dispatcher, so refresh all three resource projections. Issue rows
        // embed label snapshots; agent/skill label pickers use their resource
        // cache plus the shared label query tree.
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: ["labels", wsId] });
          qc.invalidateQueries({ queryKey: issueKeys.all(wsId) });
          invalidateProjectProgress(qc, wsId);
          qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
          qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });
        }
      },
      // The issue status catalog (MUL-6243). An admin edits it in the settings
      // page; every other tab and device is rendering statuses out of it.
      //
      // Invalidate only — the event carries no entry to merge. Issue caches are
      // deliberately NOT dragged along: a row stores the status KEY, and its
      // name, color and category are resolved from this catalog at render time
      // (`useStatusLabel`, `colorOf`), so refetching the catalog is what makes a
      // rename repaint. Pulling every board and list with it would turn one
      // admin rename into a workspace-wide refetch storm on every connected
      // client. (MUL-6458)
      issue_status: () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: issueStatusKeys.all(wsId) });
          // Creating or archiving a status also adds it to, or drops it from,
          // the stored Default workflow.
          qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
          // Status-group order is server-owned and depends on catalog positions.
          // Rows/facets and unrelated groupings do not change on catalog edits.
          qc.invalidateQueries({
            queryKey: [...issueKeys.tableAll(wsId), "groups"],
            predicate: (query) => {
              const group = query.queryKey[5];
              return !!group && typeof group === "object" && "kind" in group && group.kind === "status";
            },
          });
        }
      },
      // Workspace workflows (MUL-7420). Same contract as the status catalog:
      // the event carries no row, so every write answers with one list read.
      issue_workflow: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: issueWorkflowKeys.all(wsId) });
      },
      pin: () => {
        const wsId = getCurrentWsId();
        const userId = authStore.getState().user?.id;
        if (wsId && userId) qc.invalidateQueries({ queryKey: pinKeys.all(wsId, userId) });
      },
      issue_view: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: issueViewKeys.all(wsId) });
      },
      // The member's own preferences, saved on another tab or device.
      issue_view_preference: () => {
        const wsId = getCurrentWsId();
        if (!wsId) return;
        // A document with a write still in flight here refetches when that
        // write settles; refetching it now could paint an older copy over the
        // optimistic one. Every other document refreshes now.
        qc.invalidateQueries({
          queryKey: issueViewPrefKeys.all(wsId),
          predicate: (query) => qc.isMutating({ mutationKey: query.queryKey, exact: true }) === 0,
        });
      },
      daemon: () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });
          // Shared agents may carry a redacted runtime liveness projection;
          // refetch it when a daemon changes state even if its private runtime
          // is absent from this member's runtime list.
          qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
          // Runtime online/offline transitions move the derived status
          // for every agent that hosts on this runtime, which shifts the
          // working/idle/offline pill on the squad page.
          invalidateSquadMemberStatusQueries(qc, wsId);
        }
      },
      autopilot: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });
      },
      github_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: githubKeys.installations(wsId) });
      },
      lark_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: larkKeys.installations(wsId) });
      },
      slack_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: slackKeys.installations(wsId) });
      },
      dingtalk_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: dingtalkKeys.installations(wsId) });
      },
      vcs_connection: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: ["vcs", wsId] });
      },
      wecom_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: wecomKeys.installations(wsId) });
      },
      weixin_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: weixinKeys.installations(wsId) });
      },
      telegram_installation: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: telegramKeys.installations(wsId) });
      },
      pull_request: () => {
        // PR list is keyed by issue id, not workspace, so we invalidate all
        // PR queries — the open issue detail page will refetch its own list.
        qc.invalidateQueries({ queryKey: ["github", "pull-requests"] });
      },
      environment: () => {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({ queryKey: issueKeys.environmentsAll(wsId) });
      },
      // Task history and aggregates follow lifecycle changes. Activity
      // membership, including the presence snapshot, uses the bounded
      // refresh below so it cancels a pre-event first load without repeatedly
      // cancelling its own slow refreshes. task:message stays in specificEvents.
      task: () => {
        const wsId = getCurrentWsId();
        if (!wsId) return;
        // 30d activity series shares the same lifecycle signal — any task
        // completion / failure shifts the histogram. (Dispatch alone
        // doesn't change a completed_at-anchored series, but invalidating
        // here keeps the WS-handler shape uniform; the resulting refetch
        // is cheap.) Both the list (trailing 7d slice) and the detail
        // panel read off this single cache.
        qc.invalidateQueries({ queryKey: agentActivityKeys.last30d(wsId) });
        // 30-day run count likewise increments per task lifecycle event.
        qc.invalidateQueries({ queryKey: agentRunCountsKeys.last30d(wsId) });
        // Per-agent task list (Activity tab "Recent work"). Prefix match
        // catches every agent's list — the per-agent detail key sits
        // under agentTasks/<wsId>/<agentId>.
        qc.invalidateQueries({ queryKey: agentTasksKeys.all(wsId) });
        // Squad members-status reads the same task lifecycle to flip
        // working ↔ idle for each agent member.
        invalidateSquadMemberStatusQueries(qc, wsId);
        // Comment trigger previews answer "who would a send wake right
        // now" — the pending-task dedup guard makes that answer
        // queue-dependent, so any task lifecycle change must refresh an
        // open composer's chips (e.g. an agent finishing its run becomes
        // triggerable again mid-typing).
        qc.invalidateQueries({ queryKey: issueKeys.commentTriggerPreviewAll() });
        // Issue-trigger previews (assign/status/create/batch) are deliberately
        // NOT invalidated here. Unlike comment triggers, the assign source
        // (create / assignee change) cancels existing tasks before enqueuing, so
        // a task event can never change its verdict; only the status source's
        // pending dedup could, and that preview is advisory — the write path
        // re-evaluates authoritatively, so a rare stale label is harmless.
        // Refetching every mounted preview on every workspace task event caused
        // visible flicker, so the preview now refetches only on input change
        // (signature), mirroring its query design (MUL-3375).
      },
    };

    const workingAgentTimers = new Map<string, ReturnType<typeof setTimeout>>();
    const workingAgentInFlight = new Set<string>();
    const workingAgentDirty = new Set<string>();
    const workingAgentCauses = new Map<string, SyncCauses>();
    let disposed = false;
    const scheduleWorkingAgentRefresh = (wsId: string) => {
      // Flush one second after the FIRST event in a batch. Later events do
      // not postpone it, so continuous activity cannot starve the projection.
      // Capture the workspace now: navigation must not redirect a queued
      // refresh into a different workspace's cache.
      workingAgentDirty.add(wsId);
      workingAgentCauses.set(wsId, holdSyncCauses(workingAgentCauses.get(wsId)));
      if (workingAgentTimers.has(wsId) || workingAgentInFlight.has(wsId)) return;
      workingAgentTimers.set(wsId, setTimeout(async () => {
        workingAgentTimers.delete(wsId);
        workingAgentDirty.delete(wsId);
        workingAgentInFlight.add(wsId);
        const causes = workingAgentCauses.get(wsId) ?? [];
        workingAgentCauses.delete(wsId);
        try {
          await refreshWorkingAgentQueries(qc, wsId, causes);
        } finally {
          workingAgentInFlight.delete(wsId);
          // Serialize slow requests: cancelling our own refresh every second
          // would starve it under a continuous stream. Events received while
          // it runs still get one trailing refresh, including the final stop.
          if (!disposed && workingAgentDirty.has(wsId)) scheduleWorkingAgentRefresh(wsId);
        }
      }, 1_000));
    };

    // A project's last_activity_at is the newest activity among its issues,
    // so every event that advances an issue's activity can move it. Refresh
    // at most once a second, one second after the first event: agents comment
    // and edit in bursts, and the list recomputes stats for every project.
    const projectActivityTimers = new Map<string, ReturnType<typeof setTimeout>>();
    const scheduleProjectActivityRefresh = (wsId: string) => {
      if (projectActivityTimers.has(wsId)) return;
      projectActivityTimers.set(wsId, setTimeout(() => {
        projectActivityTimers.delete(wsId);
        qc.invalidateQueries({ queryKey: projectKeys.list(wsId) });
      }, 1_000));
    };

    const timers = new Map<string, ReturnType<typeof setTimeout>>();
    const timerCauses = new Map<string, SyncCauses>();
    const debouncedRefresh = (prefix: string, fn: () => void) => {
      const existing = timers.get(prefix);
      if (existing) clearTimeout(existing);
      const causes = holdSyncCauses(timerCauses.get(prefix));
      if (causes.length > 0) timerCauses.set(prefix, causes);
      timers.set(
        prefix,
        setTimeout(() => {
          timers.delete(prefix);
          timerCauses.delete(prefix);
          runWithSyncCauses(causes, fn);
        }, 100),
      );
    };

    // Event types handled by specific handlers below -- skip generic refresh
    const specificEvents = new Set([
      "workspace:updated",
      "issue:updated", "issue:created", "issue:deleted", "issue_attachments:changed", "issue_labels:changed", "issue_unread:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new",
      "comment:created", "comment:updated", "comment:deleted",
      "comment:resolved", "comment:unresolved",
      "activity:created",
      "reaction:added", "reaction:removed",
      "issue_reaction:added", "issue_reaction:removed",
      "subscriber:added", "subscriber:removed",
      "daemon:heartbeat",
      // Chat events are handled explicitly below; do not double-invalidate.
      "chat:message", "chat:done", "chat:reply_notification", "chat:quick_actions", "chat:cancel_finalized", "chat:wakeup_changed", "chat:session_read",
      "chat:session_created", "chat:session_deleted", "chat:session_updated",
      // task:message stays out of the prefix path because it fires per
      // streamed message during a long run — invalidating the snapshot on
      // every message would flood the network. Specific chat handlers below
      // still receive it via ws.on() (a separate subscription channel).
      "task:message",
      // task:completed / task:failed deliberately NOT here. They reach both
      // onAny (task-prefix invalidation and bounded activity refresh) and the
      // chat-specific ws.on() handlers below through independent subscriptions.
    ]);

    const unsubAny = ws.onAny((msg) => {
      if (specificEvents.has(msg.type)) return;
      const prefix = msg.type.split(":")[0] ?? "";
      if (prefix === "task" && msg.type !== "task:progress") {
        const payload = msg.payload as { issue_id?: unknown; doc_id?: unknown };
        const issueId = typeof payload?.issue_id === "string" && payload.issue_id ? payload.issue_id : null;
        const docId = typeof payload?.doc_id === "string" && payload.doc_id ? payload.doc_id : null;
        const wsId = getCurrentWsId();
        // A doc discussion run only changes that doc's run status.
        if (docId) {
          if (wsId) debouncedRefresh(`doc-task:${docId}`, () => {
            qc.invalidateQueries({ queryKey: docKeys.tasks(wsId, docId) });
          });
        } else debouncedRefresh(`issue-task:${issueId ?? "all"}`, () => {
          qc.invalidateQueries({ queryKey: issueId ? issueKeys.tasks(issueId) : issueKeys.tasksAll() });
          // Events don't carry the ancestor chain needed to scope subtree projections.
          if (issueId) qc.invalidateQueries({ queryKey: issueKeys.tasksAll(), predicate: (q) => q.queryKey[3] === "subtree" });
          qc.invalidateQueries({ queryKey: issueId ? issueKeys.usage(issueId) : issueKeys.usageAll() });
        });
      }
      if (prefix === "agent" || (prefix === "task" && msg.type !== "task:progress")) {
        const wsId = getCurrentWsId();
        if (wsId) scheduleWorkingAgentRefresh(wsId);
      }
      if (msg.type === "skill:deleted") {
        const wsId = getCurrentWsId();
        if (wsId) {
          // Agent lists and details embed skill summaries used by duplication.
          debouncedRefresh("skill:deleted", () => {
            qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });
          });
        }
      }
      const refresh = refreshMap[prefix];
      if (refresh) debouncedRefresh(prefix, refresh);
    });

    // --- Specific event handlers (granular cache updates) ---
    // No self-event filtering: actor_id identifies the USER, not the TAB.
    // Filtering by actor_id would block other tabs of the same user.
    // Instead, both mutations and WS handlers use dedup checks to be idempotent.

    const unsubGitHubInstallationCreated = ws.on("github_installation:created", (payload) => {
      useGitHubConnectionStore.getState().complete(payload);
    });

    const unsubIssueUpdated = ws.on("issue:updated", (p) => {
      const payload = p as IssueUpdatedPayload;
      const { issue } = payload;
      if (payload.status_changed || payload.parent_changed || payload.stage_changed || payload.blockers_changed) {
        const wsId = getCurrentWsId();
        if (wsId) qc.invalidateQueries({queryKey: issueKeys.all(wsId)});
      }
      if (!issue?.id) return;
      const subtreeFilter = {
        queryKey: issueKeys.tasksAll(),
        predicate: (q: { queryKey: readonly unknown[] }) => q.queryKey[3] === "subtree",
      };
      if (payload.parent_changed) {
        qc.invalidateQueries(subtreeFilter);
      } else if (payload.title_changed) {
        qc.setQueriesData<AgentTask[]>(subtreeFilter, (tasks) => tasks?.map((task) =>
          task.issue_id === issue.id ? { ...task, issue_title: issue.title } : task,
        ));
      }
      // Whose issue it is decides each subscriber's delivery tier, and a
      // reassignment can change that without any subscriber event (MUL-9360).
      if (payload.assignee_changed) {
        qc.invalidateQueries({ queryKey: issueKeys.subscribers(issue.id) });
      }
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssueUpdated(qc, wsId, issue, {
          assigneeChanged: payload.assignee_changed,
          statusChanged: payload.status_changed,
          projectChanged: payload.project_changed,
        });
        onIssueDuplicateMarkChanged(
          qc,
          wsId,
          issue.id,
          payload.duplicate_of_issue_id,
          payload.prev_duplicate_of_issue_id,
        );
        if (issue.status) {
          onInboxIssueStatusChanged(qc, wsId, issue.id, issue.status);
        }
      }
    });

    const unsubIssueCreated = ws.on("issue:created", (p) => {
      const { issue } = p as IssueCreatedPayload;
      if (!issue) return;
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssueCreated(qc, wsId, issue);
        // A new issue created waiting on others shows up under their `blocking`.
        if ((issue.parent_issue_id && issue.stage != null) || issue.blocked_by?.some((b) => b.via === "manual")) qc.invalidateQueries({queryKey:issueKeys.all(wsId)});
      }
    });

    const unsubIssueDeleted = ws.on("issue:deleted", (p) => {
      const { issue_id } = p as IssueDeletedPayload;
      if (!issue_id) return;
      qc.invalidateQueries({ queryKey: issueKeys.tasksAll(), predicate: (q) => q.queryKey[3] === "subtree" });
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssueDeleted(qc, wsId, issue_id);
        qc.invalidateQueries({queryKey:issueKeys.all(wsId)});
        void onInboxIssueDeleted(qc, wsId, issue_id);
      }
    });

    const unsubIssueLabelsChanged = ws.on("issue_labels:changed", (p) => {
      const { issue_id, labels, issue_revision } = p as IssueLabelsChangedPayload;
      if (!issue_id) return;
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssueLabelsChanged(qc, wsId, issue_id, labels ?? [], issue_revision);
        scheduleProjectActivityRefresh(wsId);
      }
    });

    // Personal; may belong to a workspace other than the open one.
    const unsubIssueUnreadChanged = ws.on("issue_unread:changed", (p) => {
      const { workspace_id } = p as IssueUnreadChangedPayload;
      if (workspace_id) void refreshIssueUnread(qc, workspace_id);
    });

    const unsubIssueAttachmentsChanged = ws.on("issue_attachments:changed", (p) => {
      const { issue_id, issue_revision } = p as IssueAttachmentsChangedPayload;
      if (!issue_id) return;
      qc.invalidateQueries({ queryKey: issueKeys.attachments(issue_id) });
      const wsId = getCurrentWsId();
      if (wsId) onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
    });

    const unsubIssueMetadataChanged = ws.on("issue_metadata:changed", (p) => {
      const { issue_id, metadata, issue_revision } = p as IssueMetadataChangedPayload;
      if (!issue_id) return;
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssueMetadataChanged(qc, wsId, issue_id, metadata ?? {}, issue_revision);
        scheduleProjectActivityRefresh(wsId);
      }
    });

    const unsubIssuePropertiesChanged = ws.on("issue_properties:changed", (p) => {
      const { issue_id, properties, issue_revision } = p as IssuePropertiesChangedPayload;
      if (!issue_id) return;
      const wsId = getCurrentWsId();
      if (wsId) {
        onIssuePropertiesChanged(qc, wsId, issue_id, properties ?? {}, issue_revision);
        scheduleProjectActivityRefresh(wsId);
        // Value set/unset shifts usage counts only; the plain catalog is
        // unchanged. Only the settings view observes the counted list.
        qc.invalidateQueries({ queryKey: propertyKeys.withUsage(wsId) });
      }
    });

    // Definition changes (create / rename / options / archive) — refetch the
    // catalog; issue caches keep raw value bags so they stay valid.
    const unsubPropertyChanged = ["property:created", "property:updated"].map((event) =>
      ws.on(event as "property:created" | "property:updated", () => {
        const wsId = getCurrentWsId();
        if (wsId) {
          qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });
          // Group order, supported group types, and unavailable option values
          // are derived from the property definition, not just issue rows.
          qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });
        }
      }),
    );

    const unsubInboxNew = ws.on("inbox:new", async (p) => {
      const { item } = p as InboxNewPayload;
      if (!item) return;
      await handleInboxNew(qc, item);
    });

    // Recorded before the refresh the generic inbox handler schedules, so the
    // Inbox knows why the open notification left once the list drops it.
    const unsubInboxBatchArchived = ws.on("inbox:batch-archived", (p) => {
      noteInboxAutoArchive(p as InboxBatchArchivedPayload);
    });

    // --- Timeline event handlers (global fallback) ---
    // These events are also handled granularly by useIssueTimeline when
    // IssueDetail is mounted. This global handler exists to mark the
    // timeline cache stale for issues whose IssueDetail is *not* mounted,
    // so stale data isn't served on next mount (staleTime: Infinity, set on
    // the QueryClient default, relies on this).
    //
    // `refetchType: "none"` is the load-bearing detail: without it, an
    // active IssueDetail observer would refetch the entire timeline on
    // every comment / activity / reaction event. The refetch replaces
    // every entry's reference and busts React.memo on every CommentCard
    // subtree (visible during AI streaming as a flash across all sibling
    // threads, MUL-1941). Inactive observers don't refetch either way;
    // when IssueDetail mounts later, the stale flag triggers the refetch
    // through `refetchOnMount`. Active observers stay fresh via the
    // granular setQueryData handlers in `useIssueTimeline`.
    const invalidateTimeline = (issueId: string) => {
      qc.invalidateQueries({
        queryKey: issueKeys.timeline(issueId),
        refetchType: "none",
      });
    };
    // The issue attachment list is the complete file inventory, labelled with
    // each file's comment. Only comment writes bind, rebind or delete comment
    // files; activity, reactions and resolutions leave it as it is.
    const invalidateCommentFiles = (issueId: string) => {
      qc.invalidateQueries({ queryKey: issueKeys.attachments(issueId) });
    };

    // Only the tree lists docs and folders; an open doc's body and comments
    // are not touched by these.
    const docUnsubs = ([
      "doc:created", "doc_folder:created", "doc_folder:updated", "doc_folder:deleted",
    ] as const).map((event) => ws.on(event, () => {
      const wsId = getCurrentWsId();
      if (wsId) void qc.invalidateQueries({ queryKey: docKeys.tree(wsId) });
    }));
    docUnsubs.push(ws.on("doc:updated", (p) => {
      const wsId = getCurrentWsId();
      if (wsId) applyDocUpdated(qc, wsId, p);
    }));
    docUnsubs.push(ws.on("doc:deleted", (p) => {
      const wsId = getCurrentWsId();
      if (!wsId) return;
      void qc.invalidateQueries({ queryKey: docKeys.tree(wsId) });
      const docId = (p as { doc_id?: string } | undefined)?.doc_id;
      if (docId) void qc.invalidateQueries({ queryKey: docKeys.detail(wsId, docId) });
    }));
    // A discussion changed on one doc: refetch that doc's comments only.
    docUnsubs.push(ws.on("doc_comment:changed", (p) => {
      const wsId = getCurrentWsId();
      const docId = (p as { doc_id?: string } | undefined)?.doc_id;
      if (wsId && docId) void qc.invalidateQueries({ queryKey: docKeys.comments(wsId, docId) });
    }));
    const unsubCommentCreated = ws.on("comment:created", (p) => {
      const { comment, issue_revision: issueRevision } = p as CommentCreatedPayload;
      if (!comment?.issue_id) return;
      invalidateTimeline(comment.issue_id);
      invalidateCommentFiles(comment.issue_id);
      // A new comment bumps the parent issue's updated_at server-side
      // (MUL-5009), so any open board/list sorted by "Updated date" has
      // drifted. Refetch just those keys to re-sort the commented card into
      // place; every other sort is untouched. Only comment:created bumps
      // updated_at, so the other comment events below deliberately do not.
      const wsId = getCurrentWsId();
      if (wsId) {
        invalidateUpdatedAtSortedIssueLists(qc, wsId);
        invalidateLastActivitySortedIssueLists(qc, wsId);
        scheduleProjectActivityRefresh(wsId);
        // A comment carries only the aggregate owner revision, not a full
        // Issue snapshot. Mark stale projections for an authoritative fetch
        // without making a later full snapshot look older than the cache.
        if (issueRevision) {
          onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issueRevision);
        } else {
          invalidateIssueOwnerProjections(qc, wsId, comment.issue_id);
        }
      }
    });

    const unsubCommentUpdated = ws.on("comment:updated", (p) => {
      const { comment, issue_revision } = p as CommentUpdatedPayload;
      if (!comment?.issue_id) return;
      invalidateTimeline(comment.issue_id);
      invalidateCommentFiles(comment.issue_id);
      const wsId = getCurrentWsId();
      if (wsId) {
        invalidateLastActivitySortedIssueLists(qc, wsId);
        scheduleProjectActivityRefresh(wsId);
        if (issue_revision) {
          onIssueAuxiliaryRevision(qc, wsId, comment.issue_id, issue_revision);
        } else {
          invalidateIssueOwnerProjections(qc, wsId, comment.issue_id);
        }
      }
    });

    const unsubCommentDeleted = ws.on("comment:deleted", (p) => {
      const { issue_id, issue_revision } = p as CommentDeletedPayload;
      if (!issue_id) return;
      invalidateTimeline(issue_id);
      invalidateCommentFiles(issue_id);
      const wsId = getCurrentWsId();
      if (wsId) {
        invalidateLastActivitySortedIssueLists(qc, wsId);
        scheduleProjectActivityRefresh(wsId);
        if (issue_revision) {
          onIssueAuxiliaryRevision(qc, wsId, issue_id, issue_revision);
        } else {
          invalidateIssueOwnerProjections(qc, wsId, issue_id);
        }
      }
    });

    const unsubCommentResolved = ws.on("comment:resolved", (p) => {
      const { comment } = p as CommentResolvedPayload;
      if (comment?.issue_id) invalidateTimeline(comment.issue_id);
    });

    const unsubCommentUnresolved = ws.on("comment:unresolved", (p) => {
      const { comment } = p as CommentUnresolvedPayload;
      if (comment?.issue_id) invalidateTimeline(comment.issue_id);
    });

    const unsubActivityCreated = ws.on("activity:created", (p) => {
      const { issue_id } = p as ActivityCreatedPayload;
      if (issue_id) invalidateTimeline(issue_id);
    });

    const unsubReactionAdded = ws.on("reaction:added", (p) => {
      const { issue_id } = p as ReactionAddedPayload;
      if (issue_id) invalidateTimeline(issue_id);
    });

    const unsubReactionRemoved = ws.on("reaction:removed", (p) => {
      const { issue_id } = p as ReactionRemovedPayload;
      if (issue_id) invalidateTimeline(issue_id);
    });

    // --- Issue-level reactions & subscribers (global fallback) ---

    const unsubIssueReactionAdded = ws.on("issue_reaction:added", (p) => {
      const { issue_id, reaction, issue_revision } = p as IssueReactionAddedPayload;
      const wsId = getCurrentWsId();
      if (issue_id && wsId) {
        onIssueReactionAdded(qc, wsId, issue_id, reaction, issue_revision);
      }
    });

    const unsubIssueReactionRemoved = ws.on("issue_reaction:removed", (p) => {
      const { issue_id, issue_revision, ...removed } = p as IssueReactionRemovedPayload;
      const wsId = getCurrentWsId();
      if (issue_id && wsId) {
        onIssueReactionRemoved(qc, wsId, issue_id, removed, issue_revision);
      }
    });

    // The viewer's own subscription changing also moves issues in and out of
    // views filtered by the "subscribed" relation.
    const onSubscriberChanged = (p: SubscriberAddedPayload | SubscriberRemovedPayload) => {
      if (!p.issue_id) return;
      qc.invalidateQueries({ queryKey: issueKeys.subscribers(p.issue_id) });
      const wsId = getCurrentWsId();
      if (wsId && p.user_type === "member" && p.user_id === authStore.getState().user?.id) {
        void refreshSubscribedIssues(qc, wsId);
      }
    };
    const unsubSubscriberAdded = ws.on("subscriber:added", (p) =>
      onSubscriberChanged(p as SubscriberAddedPayload),
    );
    const unsubSubscriberRemoved = ws.on("subscriber:removed", (p) =>
      onSubscriberChanged(p as SubscriberRemovedPayload),
    );

    // --- Side-effect handlers (toast, navigation) ---

    // After the current workspace disappears (deleted or we were kicked out),
    // navigate to another workspace the user still has access to, or to the
    // create-workspace page. We use a full-page navigation: this reliably
    // tears down any in-flight queries / subscriptions tied to the dead
    // workspace without relying on framework-specific routers from here in
    // core.
    const relocateAfterWorkspaceLoss = async (lostWsId: string) => {
      const wsList = await qc.fetchQuery({
        ...workspaceListOptions(),
        staleTime: 0,
      });
      const remaining = wsList.filter((w) => w.id !== lostWsId);
      const target = resolvePostAuthDestination(
        remaining,
        hasOnboardedRef.current,
      );
      if (typeof window !== "undefined") {
        // eslint-disable-next-line no-restricted-syntax -- in-app path, not an external URL; core has no router to hand it to
        window.location.assign(target);
      }
    };

    const unsubWsUpdated = ws.on("workspace:updated", (p) => {
      applyWorkspaceUpdatedToCache(qc, p as WorkspaceUpdatedPayload);
    });

    const unsubWsDeleted = ws.on("workspace:deleted", (p) => {
      const { workspace_id } = p as WorkspaceDeletedPayload;
      // Self-initiated delete: useDeleteWorkspace owns storage cleanup and
      // navigation (both run after the DELETE resolves). Reacting here too
      // would race that flow's navigation with a full-page relocate — the
      // CancelledError + reload combo this guard exists to prevent. This
      // handler only serves deletes initiated elsewhere (other user/device).
      if (isWorkspaceDeletePending(workspace_id)) return;
      // Any deleted workspace, not only the current one: its local search
      // copy must not outlive it.
      void forgetLocalSearchIndex(workspace_id);
      // Event payload has UUID; look up slug from cached workspace list
      // since clearWorkspaceStorage keys are namespaced by slug.
      const wsList = qc.getQueryData<{ id: string; slug: string }[]>(workspaceKeys.list()) ?? [];
      const deletedSlug = wsList.find((w) => w.id === workspace_id)?.slug;
      if (deletedSlug) clearWorkspaceStorage(defaultStorage, deletedSlug);
      if (getCurrentWsId() === workspace_id) {
        logger.warn("current workspace deleted, switching");
        onToast?.("This workspace was deleted", "info");
        relocateAfterWorkspaceLoss(workspace_id);
      }
    });

    const unsubMemberRemoved = ws.on("member:removed", (p) => {
      const { user_id, workspace_id } = p as MemberRemovedPayload;
      const myUserId = authStore.getState().user?.id;
      if (user_id === myUserId) {
        const lostWsId = workspace_id || getCurrentWsId();
        if (lostWsId) void forgetLocalSearchIndex(lostWsId);
        const slug = getCurrentSlug();
        const wsId = getCurrentWsId();
        if (slug && wsId) {
          clearWorkspaceStorage(defaultStorage, slug);
          logger.warn("removed from workspace, switching");
          onToast?.("You were removed from this workspace", "info");
          relocateAfterWorkspaceLoss(wsId);
        }
      }
    });

    const unsubMemberAdded = ws.on("member:added", (p) => {
      const { member, workspace_name } = p as MemberAddedPayload;
      const myUserId = authStore.getState().user?.id;
      if (member.user_id === myUserId) {
        qc.invalidateQueries({ queryKey: workspaceKeys.list() });
        qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
        onToast?.(
          `You joined ${workspace_name ?? "a workspace"}`,
          "info",
        );
      }
    });

    // invitation:created — notify the invitee of a new pending invitation
    const unsubInvitationCreated = ws.on("invitation:created", (p) => {
      const { workspace_name } = p as InvitationCreatedPayload;
      qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
      onToast?.(
        `You were invited to ${workspace_name ?? "a workspace"}`,
        "info",
      );
    });

    // invitation:accepted / declined / revoked — refresh invitation lists.
    // The workspace broadcast reaches every online member, so the admin lists
    // refresh unconditionally. The account-level pending list is gated on the
    // acting user: only the invitee who concluded the invite (possibly from
    // another surface or device) needs an immediate refresh even while its
    // cached list is fresh. Without the gate every accept/decline fanout
    // refetches the list once per online member. The actor arrives in the frame
    // envelope (the handler's second argument), not the event payload.
    const unsubInvitationAccepted = ws.on(
      "invitation:accepted",
      (_payload, actorId) => {
        const currentWsId = getCurrentWsId();
        if (currentWsId) {
          qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
          qc.invalidateQueries({ queryKey: workspaceKeys.members(currentWsId) });
        }
        if (actorId === authStore.getState().user?.id) {
          qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
        }
      },
    );
    const unsubInvitationDeclined = ws.on(
      "invitation:declined",
      (_payload, actorId) => {
        const currentWsId = getCurrentWsId();
        if (currentWsId) {
          qc.invalidateQueries({ queryKey: workspaceKeys.invitations(currentWsId) });
          // A declined invitation frees its member slot.
          qc.invalidateQueries({ queryKey: memberLimitKeys.all(currentWsId) });
        }
        if (actorId === authStore.getState().user?.id) {
          qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
        }
      },
    );
    const unsubInvitationRevoked = ws.on("invitation:revoked", () => {
      qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
    });

    // --- Chat / task events (global, survives ChatWindow unmount) ---
    //
    // Single source of truth: the Query cache. No Zustand writes here — the
    // earlier mirror caused a race where the cache and store disagreed
    // during the invalidate → refetch window and the UI rendered duplicates.
    //
    // task:message is written directly into the task-messages cache so the
    // live timeline updates in place. chat:message / chat:done /
    // task:completed / task:failed invalidate messages + pending-task so the
    // DB remains authoritative.

    // Two guards stand between the workspace-wide message firehose and the
    // renderer (MUL-6396). `task:message` is broadcast to EVERY client for
    // EVERY run in the workspace, but only the handful of runs a user actually
    // opens is ever rendered:
    //
    // 1. Frames are kept only for a task this client already holds a timeline
    //    entry for — opened at some point, and not yet garbage-collected. The
    //    old `(old = [])` default built that entry on first sight instead, so
    //    every client accumulated the transcript of every run its user would
    //    never open, unbounded tool input included.
    // 2. Frames that survive that gate are coalesced into one cache write per
    //    window, so a burst costs one merge and one render instead of N.
    //
    // The entry can be collected between the two, which is why the flush
    // re-checks rather than trusting the gate — see flushTaskMessages.
    const taskMessageBatches = new Map<string, TaskMessagePayload[]>();
    let taskMessageFlushTimer: ReturnType<typeof setTimeout> | null = null;
    let taskMessageCauses: SyncCauses = [];

    const writeTaskMessageBatch = (taskId: string, batch: TaskMessagePayload[]) => {
      // Re-check, because a queued batch may be up to one window old and
      // `setQueryData` does NOT postpone garbage collection — query-core arms
      // that timer when the last observer leaves and never again on write.
      // Closing a transcript while its run keeps streaming therefore has the
      // entry disappear mid-window, and writing then REBUILDS it holding only
      // this batch. With the app-wide `staleTime: Infinity` the next open
      // would read that stub as fresh and never fetch, so everything before it
      // would be missing until the window is reloaded. Dropping the batch
      // instead costs nothing: the rows are persisted, so the next open fetches
      // the whole timeline.
      if (!isTaskMessageTimelineHeld(qc, taskId)) return;
      qc.setQueryData<TaskMessagePayload[]>(
        chatKeys.taskMessages(taskId),
        (old = []) => mergeTaskMessagesBySeq(old, batch),
      );
    };

    const flushTaskMessages = () => {
      taskMessageFlushTimer = null;
      const causes = taskMessageCauses;
      taskMessageCauses = [];

      runWithSyncCauses(causes, () => {
        for (const [taskId, batch] of taskMessageBatches) {
          writeTaskMessageBatch(taskId, batch);
        }
      });
      taskMessageBatches.clear();
    };

    const unsubTaskMessage = ws.on("task:message", (p) => {
      const payload = p as TaskMessagePayload;
      // Cheap Map lookup, and it runs before anything allocates — this is the
      // hot path for every run in the workspace, not just the visible ones.
      if (!isTaskMessageTimelineHeld(qc, payload.task_id)) return;

      // Leading edge: render the first frame after an idle window now. The
      // timer is still armed so the remainder of a burst is coalesced and a
      // continuous stream cannot render more than once per fixed window after
      // this one immediate write.
      if (!taskMessageFlushTimer) {
        writeTaskMessageBatch(payload.task_id, [payload]);
        taskMessageFlushTimer = setTimeout(flushTaskMessages, TASK_MESSAGE_FLUSH_MS);
      } else {
        const batch = taskMessageBatches.get(payload.task_id);
        if (batch) batch.push(payload);
        else taskMessageBatches.set(payload.task_id, [payload]);
        taskMessageCauses = holdSyncCauses(taskMessageCauses);
      }

      chatWsLogger.debug("task:message (global)", {
        task_id: payload.task_id,
        seq: payload.seq,
        type: payload.type,
      });
    });

    // Helpers reused by chat lifecycle handlers.
    //
    // SECURITY (review on PR #5018 / MUL-4159): chat `task:*` events are a
    // *workspace fanout* — every member of the workspace receives them — and
    // the payload carries no creator / agent-visibility. So we must NEVER
    // optimistically write the cross-session pending AGGREGATE
    // (chatKeys.pendingTasks / chatKeys.pendingTasksHasAny) from these events:
    // member B starting a chat task would otherwise flip member A's FAB to
    // has_pending=true, bypassing the server-side permission filter on
    // /api/chat/pending-tasks[/has-any]. Instead we authoritatively (debounced)
    // invalidate the aggregate so it is refetched through the filtering
    // endpoint, which only returns the caller's own creator-owned,
    // accessible-agent tasks.
    //
    // The per-session `pendingTask` cache IS still written directly by the
    // handlers below — it is keyed by chat_session_id and only rendered for a
    // session the user is allowed to open (server-gated), so it is not a
    // cross-user aggregate leak.
    //
    // chat:message is intentionally NOT a trigger (it fires per streamed
    // message and would re-create the request storm MUL-4159 fixed); the
    // aggregate is refreshed only on task lifecycle transitions, which are
    // per-task and low-frequency, then coalesced by the debounce below.
    let aggregateRefreshTimer: ReturnType<typeof setTimeout> | null = null;
    let aggregateCauses: SyncCauses = [];
    const invalidatePendingAggregate = () => {
      if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);
      aggregateCauses = holdSyncCauses(aggregateCauses);
      aggregateRefreshTimer = setTimeout(() => {
        aggregateRefreshTimer = null;
        const causes = aggregateCauses;
        aggregateCauses = [];
        runWithSyncCauses(causes, () => refetchPendingChatAggregate(qc, getCurrentWsId()));
      }, 750);
    };
    const invalidateSessionLists = () => {
      const id = getCurrentWsId();
      if (id) qc.invalidateQueries({ queryKey: chatKeys.sessions(id) });
    };

    const unsubChatMessage = ws.on("chat:message", (p) => {
      const payload = p as ChatMessageEventPayload;
      chatWsLogger.info("chat:message (global)", {
        chat_session_id: payload.chat_session_id,
        role: payload.role,
      });
      // Write the user turn before invalidating so the prompt does not depend
      // on the refetch surviving (MUL-5711) — same shape as chat:done.
      applyChatMessageToCache(qc, payload);
      // NOTE: intentionally does NOT touch the pending aggregate. chat:message
      // fires per streamed message with no status; the aggregate is maintained
      // by the task lifecycle handlers below (MUL-4159).
    });

    const notifyChatReply = createChatReplyNotifier(qc, () => authStore.getState().user?.id);
    const unsubChatReplyNotification = ws.on("chat:reply_notification", (p) => {
      void notifyChatReply(p as ChatReplyNotificationPayload);
    });
    const unsubChatDone = ws.on("chat:done", (p) => {
      const payload = p as ChatDonePayload;
      chatWsLogger.info("chat:done (global)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
        has_message: !!payload.message_id,
      });
      // Inline-insert the assistant message into the messages cache BEFORE
      // clearing pending-task. Both writes land in the same React render
      // tick, so ChatMessageList sees `pendingAlreadyPersisted === true`
      // and the live TimelineView unmounts only after AssistantMessage has
      // mounted — no flicker window. This applies TkDodo's "combine
      // setQueryData (active query) + invalidateQueries (others)" pattern
      // (https://tkdodo.eu/blog/using-web-sockets-with-react-query).
      //
      // Falls back to invalidate-only when the server omits the message
      // payload (older builds). Older clients hitting a newer server also
      // work: they ignore the extra fields and rely on the invalidate
      // below, which keeps the old behavior alive.
      applyChatDoneToCache(qc, payload);
      // NOTE: the pending aggregate is left to the task:completed / task:failed
      // handlers (which carry the task_id needed to remove the right entry).
      // chat:done no longer invalidates it, so a chatty session doesn't refetch
      // the aggregate on every turn (MUL-4159).
      // Assistant message just landed → has_unread may have flipped to true.
      invalidateSessionLists();
    });

    // Late quick-actions supplement from the daemon's background suggestion
    // pass — patches the finished turn's message in place; no invalidate
    // needed (the payload is authoritative and tiny).
    const unsubChatQuickActions = ws.on("chat:quick_actions", (p) => {
      const payload = p as ChatQuickActionsPayload;
      chatWsLogger.info("chat:quick_actions (global)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
        count: payload.quick_actions?.length ?? 0,
      });
      void applyChatQuickActionsToCache(qc, payload);
    });

    // Deferred cancellation outcome (#5219): the server settles the
    // empty/non-empty judgment only after the daemon's transcript flush, so
    // this event arrives seconds after the cancel HTTP response — nothing
    // else re-fetches at that point.
    const unsubChatCancelFinalized = ws.on("chat:cancel_finalized", (p) => {
      const payload = p as ChatCancelFinalizedPayload;
      chatWsLogger.info("chat:cancel_finalized (global)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
        outcome: payload.outcome,
      });
      applyChatCancelFinalizedToCache(qc, payload, authStore.getState().user?.id);
      if (payload.outcome === "stopped") {
        // A Stopped. assistant row just landed → session previews change.
        invalidateSessionLists();
      }
    });

    // A wakeup changed. When it started a turn (task_id), the turn's hidden
    // input row is new too, so the transcript and queue refetch.
    const unsubChatWakeupChanged = ws.on("chat:wakeup_changed", (p) => {
      const payload = p as ChatWakeupChangedPayload;
      chatWsLogger.info("chat:wakeup_changed (global)", payload);
      qc.invalidateQueries({ queryKey: chatKeys.wakeups(payload.chat_session_id) });
      const id = getCurrentWsId();
      if (id) qc.invalidateQueries({ queryKey: chatKeys.myWakeups(id) });
      if (payload.task_id) {
        qc.invalidateQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
        qc.invalidateQueries({ queryKey: chatKeys.messagesPage(payload.chat_session_id) });
        qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
        invalidatePendingAggregate();
        invalidateSessionLists();
      }
    });

    // A wakeup's row shows how its report turn is going (last_task_status),
    // so task lifecycle in a conversation with started wakeups refreshes it.
    const refreshWakeupTurns = (sessionId: string) => {
      const cached = qc.getQueryData<ChatWakeup[]>(chatKeys.wakeups(sessionId));
      if (cached?.some((w) => w.last_task_id)) {
        qc.invalidateQueries({ queryKey: chatKeys.wakeups(sessionId) });
      }
    };

    // Lifecycle events are invalidation hints. They intentionally omit queue
    // previews and message ids, so only the pending-task endpoint can author
    // the complete queue shape.
    const unsubTaskQueued = ws.on("task:queued", (p) => {
      const payload = p as TaskQueuedPayload;
      if (!payload.chat_session_id) return;
      qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      invalidatePendingAggregate();
    });

    // task:dispatch fires when the daemon claims the queued task. The daemon
    // immediately follows with StartTask, so dispatched→running is sub-second.
    // We collapse that window by writing "running" directly — the pill jumps
    // from "Queued" straight to "Thinking", skipping a meaningless "Starting"
    // frame. Stage decision in TaskStatusPill maps "running" + empty
    // taskMessages → "Thinking · Ns".
    const unsubTaskDispatch = ws.on("task:dispatch", (p) => {
      const payload = p as TaskDispatchPayload;
      if (!payload.chat_session_id) return;
      qc.setQueryData<ChatPendingTask>(
        chatKeys.pendingTask(payload.chat_session_id),
        (old) => promotePendingChatTask(old, payload.task_id, "running"),
      );
      invalidateChatMessageQueries(qc, payload.chat_session_id);
      qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      invalidatePendingAggregate();
    });

    // task:running fires when the daemon transitions a previously-parked task
    // (waiting_local_directory) back into the run phase. The dispatch→running
    // path is collapsed in the handler above, so this handler exists mainly to
    // clear a stale `waiting_local_directory` pill — without it, the pill
    // would stay parked even after the daemon resumed work.
    const unsubTaskRunning = ws.on("task:running", (p) => {
      const payload = p as TaskRunningPayload;
      if (!payload.chat_session_id) return;
      qc.setQueryData<ChatPendingTask>(
        chatKeys.pendingTask(payload.chat_session_id),
        (old) => promotePendingChatTask(old, payload.task_id, "running"),
      );
      invalidateChatMessageQueries(qc, payload.chat_session_id);
      qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      refreshWakeupTurns(payload.chat_session_id);
      invalidatePendingAggregate();
    });

    // task:waiting_local_directory fires when the daemon dequeues a task but
    // can't acquire the local_directory path lock — another task on this
    // daemon is in the same directory. Write the status so TaskStatusPill
    // can render the "Waiting for local directory" stage instead of pinning
    // a stale "Starting / Thinking" frame.
    const unsubTaskWaitingLocalDir = ws.on(
      "task:waiting_local_directory",
      (p) => {
        const payload = p as TaskWaitingLocalDirectoryPayload;
        if (!payload.chat_session_id) return;
        qc.setQueryData<ChatPendingTask>(
          chatKeys.pendingTask(payload.chat_session_id),
          (old) =>
            promotePendingChatTask(
              old,
              payload.task_id,
              "waiting_local_directory",
              undefined,
              payload.wait_reason,
            ),
        );
        invalidateChatMessageQueries(qc, payload.chat_session_id);
        qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
        invalidatePendingAggregate();
      },
    );

    // task:cancelled reaches us when:
    //   1. handleStop already cleared the cache locally (this is a no-op confirm)
    //   2. another tab / admin / system cancels — this is the only path that
    //      drops the pending pill in those cases. Without it the pill spins
    //      forever in the second-tab scenario.
    // CancelTask also persists a best-effort assistant snapshot when the
    // stopped chat task had already streamed transcript rows, so refresh the
    // message page along with clearing pending.
    const unsubTaskCancelled = ws.on("task:cancelled", (p) => {
      const payload = p as TaskCancelledPayload;
      if (!payload.chat_session_id) return;
      chatWsLogger.info("task:cancelled (global, chat)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
      });
      qc.setQueryData<ChatPendingTask>(
        chatKeys.pendingTask(payload.chat_session_id),
        (old) => removePendingChatTask(old, payload.task_id),
      );
      qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      invalidateChatMessageQueries(qc, payload.chat_session_id);
      refreshWakeupTurns(payload.chat_session_id);
      invalidatePendingAggregate();
      invalidateSessionLists();
    });

    const unsubTaskCompleted = ws.on("task:completed", (p) => {
      const payload = p as TaskCompletedPayload;
      if (!payload.chat_session_id) return; // issue tasks handled elsewhere
      chatWsLogger.info("task:completed (global, chat)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
      });
      const pendingKey = chatKeys.pendingTask(payload.chat_session_id);
      // chat:done normally clears this turn and refreshes its reply. If the
      // turn is still pending locally, recover the persisted outcome here.
      if (qc.getQueryData<ChatPendingTask>(pendingKey)?.task_id === payload.task_id) {
        invalidateChatMessageQueries(qc, payload.chat_session_id);
        invalidateSessionLists();
      }
      qc.setQueryData<ChatPendingTask>(pendingKey, (old) =>
        removePendingChatTask(old, payload.task_id),
      );
      qc.invalidateQueries({ queryKey: pendingKey });
      refreshWakeupTurns(payload.chat_session_id);
      invalidatePendingAggregate();
    });

    const unsubTaskFailed = ws.on("task:failed", (p) => {
      const payload = p as TaskFailedPayload;
      if (!payload.chat_session_id) return;
      chatWsLogger.warn("task:failed (global, chat)", {
        task_id: payload.task_id,
        chat_session_id: payload.chat_session_id,
      });
      // FailTask writes a failure chat_message (mirroring CompleteTask's
      // success message), so this path mirrors the task:completed handler:
      // clear the pending signal AND invalidate the messages list so the
      // failure bubble shows up without requiring a page refresh. Pre-#1823
      // this branch only flipped pending — the comment "No new message"
      // was true then, but FailTask now persists a row.
      qc.setQueryData<ChatPendingTask>(
        chatKeys.pendingTask(payload.chat_session_id),
        (old) => removePendingChatTask(old, payload.task_id),
      );
      invalidateChatMessageQueries(qc, payload.chat_session_id);
      qc.invalidateQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      refreshWakeupTurns(payload.chat_session_id);
      invalidatePendingAggregate();
      // FailTask persisted a failure chat_message, so the thread list's
      // last_message / unread_count / sort order changed too. Mirror the
      // chat:done (success) path and refresh the sessions list — otherwise the
      // left rail keeps a stale preview until the next full refetch.
      invalidateSessionLists();
    });

    const unsubChatSessionRead = ws.on("chat:session_read", (p) => {
      const payload = p as { chat_session_id: string };
      chatWsLogger.info("chat:session_read (global)", payload);
      invalidateSessionLists();
    });

    const unsubChatSessionCreated = ws.on("chat:session_created", (p) => {
      const payload = p as ChatSessionCreatedPayload;
      chatWsLogger.info("chat:session_created (global)", payload);
      if (payload.workspace_id !== getCurrentWsId()) return;
      invalidateSessionLists();
    });

    // chat:session_updated fires after the creator renames, pins, or archives
    // a session in any tab/device. Patch the cached row inline so the dropdown
    // and badges reflect the change without a full sessions-list refetch — see
    // applyChatSessionUpdatedToCache for why archive must also zero unread.
    const unsubChatSessionUpdated = ws.on("chat:session_updated", (p) => {
      const payload = p as ChatSessionUpdatedPayload;
      chatWsLogger.info("chat:session_updated (global)", payload);
      const id = getCurrentWsId();
      if (!id) return;
      applyChatSessionUpdatedToCache(qc, id, payload);
    });

    // chat:session_deleted fires after a hard delete. The originating tab has
    // already optimistically dropped the row via useDeleteChatSession; this
    // handler keeps OTHER tabs/devices in sync and also clears the active
    // session pointer so a deleted session doesn't keep the chat window
    // pointed at vanished messages.
    const unsubChatSessionDeleted = ws.on("chat:session_deleted", (p) => {
      const payload = p as { chat_session_id: string };
      chatWsLogger.info("chat:session_deleted (global)", payload);
      const id = getCurrentWsId();
      if (id) {
        const drop = (old?: { id: string }[]) =>
          old?.filter((s) => s.id !== payload.chat_session_id);
        qc.setQueryData(chatKeys.sessions(id), drop);
      }
      qc.removeQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
      qc.removeQueries({ queryKey: chatKeys.pendingTask(payload.chat_session_id) });
      invalidatePendingAggregate();

      const chatState = useChatStore.getState?.();
      if (chatState && chatState.activeSessionId === payload.chat_session_id) {
        chatState.setActiveSession(null);
      }
    });

    return () => {
      releaseSyncTarget();
      unsubAny();
      unsubChatWakeupChanged();
      unsubGitHubInstallationCreated();
      unsubIssueUpdated();
      unsubIssueCreated();
      unsubIssueDeleted();
      unsubIssueAttachmentsChanged();
      unsubIssueLabelsChanged();
      unsubIssueUnreadChanged();
      unsubIssueMetadataChanged();
      unsubIssuePropertiesChanged();
      unsubPropertyChanged.forEach((unsub) => unsub());
      unsubInboxNew();
      unsubInboxBatchArchived();
      docUnsubs.forEach(unsub => unsub());
      unsubCommentCreated();
      unsubCommentUpdated();
      unsubCommentDeleted();
      unsubCommentResolved();
      unsubCommentUnresolved();
      unsubActivityCreated();
      unsubReactionAdded();
      unsubReactionRemoved();
      unsubIssueReactionAdded();
      unsubIssueReactionRemoved();
      unsubSubscriberAdded();
      unsubSubscriberRemoved();
      unsubWsUpdated();
      unsubWsDeleted();
      unsubMemberRemoved();
      unsubMemberAdded();
      unsubInvitationCreated();
      unsubInvitationAccepted();
      unsubInvitationDeclined();
      unsubInvitationRevoked();
      unsubTaskMessage();
      unsubChatMessage();
      unsubChatDone();
      unsubChatReplyNotification();
      unsubChatQuickActions();
      unsubChatCancelFinalized();
      unsubTaskQueued();
      unsubTaskDispatch();
      unsubTaskRunning();
      unsubTaskWaitingLocalDir();
      unsubTaskCancelled();
      unsubTaskCompleted();
      unsubTaskFailed();
      unsubChatSessionRead();
      unsubChatSessionCreated();
      unsubChatSessionDeleted();
      unsubChatSessionUpdated();
      if (taskMessageFlushTimer) clearTimeout(taskMessageFlushTimer);
      if (aggregateRefreshTimer) clearTimeout(aggregateRefreshTimer);
      timers.forEach(clearTimeout);
      timers.clear();
      disposed = true;
      workingAgentTimers.forEach(clearTimeout);
      workingAgentTimers.clear();
      projectActivityTimers.forEach(clearTimeout);
      projectActivityTimers.clear();
      workingAgentDirty.clear();
      workingAgentCauses.clear();
    };
  }, [client, qc, authStore, onToast]);

  // Reconnect -> refetch all data to recover missed events
  useEffect(() => {
    if (!client) return;

    const unsub = client.onReconnect(async () => {
      logger.info("reconnected, refetching all data");
      try {
        invalidateWorkspaceScopedQueries(qc);
      } catch (e) {
        logger.error("reconnect refetch failed", e);
      }
    });

    return unsub;
  }, [client, qc]);

  // New WSClient instance (workspace switch) -> invalidate workspace-scoped
  // queries to recover events missed while the previous instance was torn down.
  // Skips the initial assignment to avoid a redundant refetch on first mount.
  const wsInstanceRef = useRef<WSClient | null>(null);
  useEffect(() => {
    if (!client) return;
    if (wsInstanceRef.current === null) {
      // First non-null instance — store and skip invalidation.
      wsInstanceRef.current = client;
      return;
    }
    if (wsInstanceRef.current === client) return;
    wsInstanceRef.current = client;

    logger.info("new WSClient instance detected, invalidating workspace queries");
    invalidateWorkspaceScopedQueries(qc);
  }, [client, qc]);
}