Skip to content

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

Go
14.6 KB
Raw Blame
/**
 * Mobile-owned WS cache patchers for the chat domain.
 *
 * Pure functions over QueryClient — no React, no WS plumbing. The
 * `use-chat-sessions-realtime` and `use-chat-session-realtime` hooks
 * translate WS events into calls into this module.
 *
 * Why mobile-owned (and not importing from web's chat ws-updaters):
 *   - Web binds its updaters to `chatKeys` from packages/core/chat/queries.ts,
 *     a different runtime instance than mobile's data/queries/chat.ts. Keys
 *     are compared structurally so it'd *appear* to work, but binding cache
 *     mutation to a foreign key factory invites silent drift the moment
 *     either side adjusts its key shape.
 *   - Mobile has a smaller cache surface (no taskMessages live timeline in
 *     v1, no per-user pending-tasks aggregate).
 *
 * Cache shapes (the design contract):
 *   - chatKeys.sessions(wsId)       → ChatSession[]
 *   - chatKeys.messages(sessionId)  → ChatMessage[]   (flat, ASC oldest→newest)
 *   - chatKeys.pendingTask(sessionId)→ ChatPendingTask (empty `{}` = no in-flight)
 */
import type { QueryClient } from "@tanstack/react-query";
import {
  enqueuePendingChatTask,
  removePendingChatTask,
} from "@multica/core/chat/pending";
import type {
  ChatDonePayload,
  ChatMessage,
  ChatPendingTask,
  ChatQuickActionsPayload,
  ChatSession,
  ChatSessionDeletedPayload,
  SendChatMessageResponse,
  TaskMessagePayload,
  TaskQueuedPayload,
  TaskDispatchPayload,
} from "@multica/core/types";
import { chatKeys } from "@/data/queries/chat";

// Sessions list (ChatSession[] keyed by wsId)

export function patchSessionListAfterRename(
  qc: QueryClient,
  wsId: string | null,
  payload: {
    chat_session_id: string;
    title?: string;
    updated_at?: string;
  },
) {
  qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
    old?.map((s) =>
      s.id === payload.chat_session_id
        ? {
            ...s,
            title: payload.title ?? s.title,
            updated_at: payload.updated_at ?? s.updated_at,
          }
        : s,
    ),
  );
}

export function dropSessionFromList(
  qc: QueryClient,
  wsId: string | null,
  payload: ChatSessionDeletedPayload,
) {
  qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
    old?.filter((s) => s.id !== payload.chat_session_id),
  );
  qc.removeQueries({ queryKey: chatKeys.messages(payload.chat_session_id) });
  qc.removeQueries({
    queryKey: chatKeys.pendingTask(payload.chat_session_id),
  });
}

export function flipSessionUnread(
  qc: QueryClient,
  wsId: string | null,
  sessionId: string,
  hasUnread: boolean,
) {
  qc.setQueryData<ChatSession[]>(chatKeys.sessions(wsId), (old) =>
    old?.map((s) =>
      s.id === sessionId ? { ...s, has_unread: hasUnread } : s,
    ),
  );
}

// Messages cache (ChatMessage[] keyed by sessionId)

/**
 * Apply `chat:done` to the messages cache.
 *
 * When the payload carries the freshly-persisted assistant message inline
 * (message_id + content + created_at), patch the cache directly so the
 * assistant bubble lands in the same render tick that clears pendingTask
 * — no live-timeline → final-bubble flicker.
 *
 * Older servers (pre-#2123 in web's commit history) sent only chat_session_id
 * + task_id. Detect that and fall back to invalidate; we'll refetch the
 * messages list and accept a one-frame window with no bubble.
 *
 * The inline patch never carries attachments: `ChatDonePayload` has no
 * attachments field by contract, yet an assistant reply may have images/files
 * bound to it server-side. So after the inline patch we ALWAYS invalidate the
 * messages list to refetch the authoritative rows (which include
 * `attachments`). Mirrors web's `use-realtime-sync.ts`, which invalidates
 * unconditionally after its inline patch. The patch is kept purely for the
 * instant, flicker-free bubble; the refetch is what makes attachments appear.
 */
export function applyChatDoneToCache(
  qc: QueryClient,
  payload: ChatDonePayload,
) {
  if (
    payload.message_id &&
    (payload.content != null || (payload.quick_actions?.length ?? 0) > 0) &&
    payload.created_at
  ) {
    const assistantMsg: ChatMessage = {
      id: payload.message_id,
      chat_session_id: payload.chat_session_id,
      role: "assistant",
      content: payload.content ?? "",
      task_id: payload.task_id,
      created_at: payload.created_at,
      elapsed_ms: payload.elapsed_ms ?? null,
      // Mirror web's applyChatDoneToCache: carry the kind so a no_response turn
      // renders its notice inline; missing → "message" for older servers
      // (MUL-4351).
      message_kind: payload.message_kind ?? "message",
      ...(payload.quick_actions !== undefined
        ? { quick_actions: payload.quick_actions }
        : {}),
    };
    qc.setQueryData<ChatMessage[]>(
      chatKeys.messages(payload.chat_session_id),
      (old) => {
        if (!old) return [assistantMsg];
        // Echo guard — server may re-emit on reconnect.
        if (old.some((m) => m.id === assistantMsg.id)) return old;
        return [...old, assistantMsg];
      },
    );
  }
  // Refetch the authoritative message list so any attachments bound to the
  // assistant reply (absent from the event payload) are pulled in.
  qc.invalidateQueries({
    queryKey: chatKeys.messages(payload.chat_session_id),
  });
  // A queued successor may already exist. Refetch the server-authoritative
  // head instead of clearing it and briefly presenting the session as idle.
  invalidatePendingTask(qc, payload.chat_session_id);
}

/**
 * Apply a `chat:quick_actions` supplement to the messages cache.
 *
 * The daemon generates quick actions in a background pass AFTER the turn
 * finishes, so they arrive on their own event well after `chat:done` already
 * invalidated + refetched the messages list (which came back with none). With
 * `staleTime: Infinity` nothing refetches again, so without this patch an
 * active mobile session would never render async-generated quick actions until
 * a manual pull-to-refresh or refocus.
 *
 * Patch the identified assistant message's `quick_actions` in place. The
 * payload's list is already server-validated, so — like web — this only
 * patches; no invalidate (mobile's cellular "patch over invalidate" rule). An
 * empty/missing list is terminal ("no suggestions this turn") and a no-op:
 * the message already renders no chips.
 *
 * Mirrors web's `applyChatQuickActionsToCache` in
 * packages/core/realtime/use-realtime-sync.ts. Mobile has a single flat
 * messages cache and no pending-placeholder marker, so it patches only that
 * one cache.
 */
export async function applyChatQuickActionsToCache(
  qc: QueryClient,
  payload: ChatQuickActionsPayload,
) {
  const actions = payload.quick_actions ?? [];
  if (actions.length === 0) return;
  // 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. The messages query is staleTime: Infinity, so such an overwrite
  // would never self-heal (MUL-5149 stale-refetch race). Cancel before
  // setQueryData: cancelQueries reverts to the pre-fetch state, so patching
  // first would be undone by the revert.
  await qc.cancelQueries({
    queryKey: chatKeys.messages(payload.chat_session_id),
  });
  qc.setQueryData<ChatMessage[]>(
    chatKeys.messages(payload.chat_session_id),
    (old) =>
      old?.map((m) =>
        m.id === payload.message_id ? { ...m, quick_actions: actions } : m,
      ),
  );
}

// Pending task (ChatPendingTask keyed by sessionId)

export function seedPendingTaskFromQueued(
  qc: QueryClient,
  payload: TaskQueuedPayload,
) {
  if (!payload.chat_session_id) return;
  // A follow-up can be queued while another task is active. The event does
  // not carry enough queue state to replace that active head safely.
  invalidatePendingTask(qc, payload.chat_session_id);
  // Guidance the running reply could not take is re-queued by moving its
  // message to a new turn. Only the refetched row carries that owner, which
  // is what moves it out of the transcript and into the queued rows. A turn
  // whose message already names it (this device's reconciled send) needs no
  // second refetch.
  const messages = qc.getQueryData<ChatMessage[]>(
    chatKeys.messages(payload.chat_session_id),
  );
  if (!messages?.some((message) => message.task_id === payload.task_id)) {
    qc.invalidateQueries({
      queryKey: chatKeys.messages(payload.chat_session_id),
    });
  }
}

export function promotePendingTaskToRunning(
  qc: QueryClient,
  payload: TaskDispatchPayload,
) {
  if (!payload.chat_session_id) return;
  qc.setQueryData<ChatPendingTask>(
    chatKeys.pendingTask(payload.chat_session_id),
    (old) => {
      // Only upgrade if it's the task we already know about. A stale
      // dispatch event for a finished task shouldn't reanimate the pill.
      if (!old || old.task_id !== payload.task_id) return old;
      return { ...old, status: "running" };
    },
  );
  invalidatePendingTask(qc, payload.chat_session_id);
  qc.invalidateQueries({
    queryKey: chatKeys.messages(payload.chat_session_id),
  });
}

export function invalidatePendingTask(
  qc: QueryClient,
  sessionId: string,
) {
  qc.invalidateQueries({ queryKey: chatKeys.pendingTask(sessionId) });
}

export function seedAcceptedPendingTask(
  qc: QueryClient,
  payload: {
    chat_session_id: string;
    task_id: string;
    created_at: string;
    message_id?: string;
    content?: string;
    optimistic_task_id?: string;
    supports_queue?: boolean;
    queued?: boolean;
  },
) {
  qc.setQueryData<ChatPendingTask>(
    chatKeys.pendingTask(payload.chat_session_id),
    (old) => {
      const task = {
        task_id: payload.task_id,
        status: "queued",
        created_at: payload.created_at,
        ...(payload.message_id ? { message_id: payload.message_id } : {}),
        ...(payload.content !== undefined ? { content: payload.content } : {}),
      };
      let next: ChatPendingTask;
      if (
        payload.queued === true &&
        payload.optimistic_task_id &&
        old?.task_id === payload.optimistic_task_id
      ) {
        // The server knows an authoritative predecessor exists, but this
        // client has not loaded it yet. Retain the optimistic root as a
        // non-network placeholder until the invalidation fills that head;
        // dropping it here would briefly unlock the composer and remove the
        // status line while leaving only a queue row.
        next = enqueuePendingChatTask(old, task, true);
      } else {
        const reconciled = payload.optimistic_task_id
          ? removePendingChatTask(old, payload.optimistic_task_id)
          : old;
        next = enqueuePendingChatTask(reconciled, task, payload.queued);
      }
      if (payload.supports_queue === true || old?.supports_queue === true) {
        next.supports_queue = true;
      }
      return next;
    },
  );
  invalidatePendingTask(qc, payload.chat_session_id);
}

/**
 * Reconcile this device's optimistic send with the server's acceptance.
 *
 * The message row takes its own input owner and timestamp: guidance that
 * joins a reply belongs to that reply's root request (which differs from
 * `task_id` when the reply is a retry) and is newer than the task. Servers
 * before steering omit both fields, and for a new turn the task's values are
 * the message's own.
 *
 * Steered guidance creates no turn, so only the local placeholder leaves the
 * pending cache; the active head keeps its identity and elapsed timer. Every
 * other acceptance is a turn the pending state must track.
 */
export function reconcileAcceptedChatSend(
  qc: QueryClient,
  payload: {
    chat_session_id: string;
    optimistic_message_id: string;
    optimistic_task_id: string;
    content: string;
    result: SendChatMessageResponse;
  },
) {
  const { chat_session_id: sessionId, result } = payload;
  qc.setQueryData<ChatMessage[]>(chatKeys.messages(sessionId), (old) =>
    old?.map((message) =>
      message.id === payload.optimistic_message_id
        ? {
            ...message,
            id: result.message_id,
            task_id: result.message_task_id ?? result.task_id,
            created_at: result.message_created_at ?? result.created_at,
          }
        : message,
    ),
  );
  if (result.steered === true) {
    qc.setQueryData<ChatPendingTask>(chatKeys.pendingTask(sessionId), (old) =>
      removePendingChatTask(old, payload.optimistic_task_id),
    );
    invalidatePendingTask(qc, sessionId);
  } else {
    seedAcceptedPendingTask(qc, {
      chat_session_id: sessionId,
      task_id: result.task_id,
      created_at: result.created_at,
      message_id: result.message_id,
      content: payload.content,
      optimistic_task_id: payload.optimistic_task_id,
      supports_queue: result.supports_queue,
      queued: result.queued,
    });
  }
  qc.invalidateQueries({ queryKey: chatKeys.messages(sessionId) });
}

// Task messages (live timeline, keyed by taskId)

/**
 * Append a `task:message` payload into the per-task timeline cache.
 *
 * - De-dupes on `seq` (server may re-emit on flaky network). A reader of a
 *   restricted agent's tool details gets both the stripped and the full copy
 *   of a tool call, so a full copy replaces a `details_hidden` one, as
 *   `mergeTaskMessagesBySeq` does on web.
 * - Sorts by `seq` ASC after insert so reordered late-arriving rows still
 *   render in execution order.
 * - Creates the cache entry on first event (empty default), so the timeline
 *   is visible even before the user opens the assistant bubble that drives
 *   the lazy fetch.
 *
 * Mirrors `packages/core/realtime/use-realtime-sync.ts` ~675-689 (web's
 * single global handler). Mobile attaches per-session via
 * `use-chat-session-realtime` instead — see the WS strategy note in
 * `apps/mobile/CLAUDE.md` for why mobile prefers per-record mounts.
 */
export function appendTaskMessage(
  qc: QueryClient,
  payload: TaskMessagePayload,
) {
  qc.setQueryData<TaskMessagePayload[]>(
    chatKeys.taskMessages(payload.task_id),
    (old = []) => {
      const index = old.findIndex((m) => m.seq === payload.seq);
      if (index === -1) return [...old, payload].sort((a, b) => a.seq - b.seq);
      if (!old[index]!.details_hidden || payload.details_hidden) return old;
      return old.map((m, i) => (i === index ? payload : m));
    },
  );
}

export async function refreshTaskMessages(qc: QueryClient, taskId: string) {
  const queryKey = chatKeys.taskMessages(taskId);
  // Invalidation alone reuses an unfinished first load. Cancel it first,
  // retaining any WS rows received since it began instead of reverting them.
  await qc.cancelQueries({ queryKey }, { revert: false, silent: true });
  await qc.invalidateQueries({ queryKey });
}