Skip to content

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

Go
19.5 KB
Raw Blame
import {
  infiniteQueryOptions,
  queryOptions,
  useQuery,
  type InfiniteData,
  type QueryClient,
} from "@tanstack/react-query";
import { useEffect, useRef } from "react";
import { api } from "../api";
import type { TaskMessagePayload } from "../types/events";
import type {
  ChatMessagesPage,
  ChatQuickActionsFailureState,
  ChatQuickActionsPendingState,
  ChatSession,
} from "../types/chat";

/**
 * How long a quick-actions pending marker may stay unresolved before a client
 * gives up and clears it (MUL-5149). Used to stamp the marker's absolute
 * `expires_at` deadline at creation, and by `useQuickActionsPendingTimeout` to
 * clear it — a shared deadline survives chat-surface switches instead of
 * re-arming a fresh window on each remount.
 *
 * Sized from the server's own budget: suggestions are generated by a bounded
 * (8s) LLM call, leaving room for the write and the realtime broadcast. Keep
 * this above `chatQuickActionsTimeout` in the backend — a window shorter than
 * the work it waits on makes every slow-but-successful pass look like a
 * failure, then silently swap the pills in afterwards.
 */
export const QUICK_ACTIONS_PENDING_TIMEOUT_MS = 12_000;

// Sessions, pinned agents, pending tasks, and the running indicator explicitly
// bind requests to the workspace UUID in their query key. Other session/task
// queries still use ApiClient's current workspace header, which callers must
// keep aligned with the resource's workspace and any wsId in the query key.

export const chatKeys = {
  all: (wsId: string) => ["chat", wsId] as const,
  /** Full sessions list (active + archived); the dropdown splits locally. */
  sessions: (wsId: string) => [...chatKeys.all(wsId), "sessions"] as const,
  session: (wsId: string, id: string) => [...chatKeys.all(wsId), "session", id] as const,
  messagesAll: () => ["chat", "messages"] as const,
  messages: (sessionId: string) => [...chatKeys.messagesAll(), sessionId] as const,
  messagesPageAll: () => ["chat", "messages-page"] as const,
  messagesPage: (sessionId: string) => [...chatKeys.messagesPageAll(), sessionId] as const,
  pendingTaskAll: () => ["chat", "pending-task"] as const,
  pendingTask: (sessionId: string) => [...chatKeys.pendingTaskAll(), sessionId] as const,
  /** Client-only marker: this session's last turn awaits a quick-actions supplement. */
  quickActionsPendingAll: () => ["chat", "quick-actions-pending"] as const,
  quickActionsPending: (sessionId: string) =>
    [...chatKeys.quickActionsPendingAll(), sessionId] as const,
  /** Client-only signal: this session's last refresh regeneration failed. */
  quickActionsFailureAll: () => ["chat", "quick-actions-failure"] as const,
  quickActionsFailure: (sessionId: string) =>
    [...chatKeys.quickActionsFailureAll(), sessionId] as const,
  draftRestoresAll: () => ["chat", "draft-restores"] as const,
  /** Durable deferred-cancellation draft restores for a session (#5219). */
  draftRestores: (sessionId: string) => [...chatKeys.draftRestoresAll(), sessionId] as const,
  wakeupsAll: () => ["chat", "wakeups"] as const,
  /** A conversation's wakeups: active ones plus those that ended recently. */
  wakeups: (sessionId: string) => [...chatKeys.wakeupsAll(), sessionId] as const,
  /** The caller's wakeups across their conversations in this workspace. */
  myWakeups: (wsId: string) => [...chatKeys.all(wsId), "my-wakeups"] as const,
  /** Aggregate of in-flight chat tasks for the current user — FAB reads this. */
  pendingTasks: (wsId: string) => [...chatKeys.all(wsId), "pending-tasks"] as const,
  /** Per-user pinned agents for the quick-agent bar. */
  pinnedAgents: (wsId: string) => [...chatKeys.all(wsId), "pinned-agents"] as const,
  /**
   * Boolean "does the user have any in-flight chat task" — the FAB's cheap
   * running indicator. Separate cache from the detailed `pendingTasks` list so
   * the FAB (closed-window) and ChatWindow (open) can subscribe independently.
   */
  pendingTasksHasAny: (wsId: string) =>
    [...chatKeys.all(wsId), "pending-tasks", "has-any"] as const,
  /** Per-task execution messages — shared with issue agent cards. */
  taskMessagesAll: () => ["task-messages"] as const,
  taskMessages: (taskId: string) => [...chatKeys.taskMessagesAll(), taskId] as const,
};

const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

export function isTaskMessageTaskId(taskId: string | null | undefined): taskId is string {
  return typeof taskId === "string" && UUID_PATTERN.test(taskId);
}

export function chatSessionsOptions(wsId: string) {
  return queryOptions({
    queryKey: chatKeys.sessions(wsId),
    queryFn: () => api.listChatSessions({ status: "all" }, { workspaceId: wsId }),
    staleTime: Infinity,
  });
}

/** Last-activity timestamp used to rank the IM list (newest first). */
function sessionActivityTime(s: ChatSession): number {
  return new Date(s.last_message?.created_at ?? s.updated_at).getTime();
}

/**
 * Orders the chat list the same way the server does: pinned chats first, then
 * everyone else by most-recent activity. Used both to render the list and to
 * re-sort the cache after an optimistic pin/unpin or a WS patch, so a mutated
 * flat cache never renders out of order. Returns a new array; stable for equal
 * keys (Array.prototype.sort is stable), so pinned rows keep their server
 * order when pin timestamps aren't carried in the list payload.
 */
export function sortChatSessions(sessions: ChatSession[]): ChatSession[] {
  // Parse dates once per session, rather than on each comparison.
  return sessions
    .map((session) => ({ session, activity: sessionActivityTime(session) }))
    .sort((a, b) => {
      const ap = a.session.pinned ? 1 : 0;
      const bp = b.session.pinned ? 1 : 0;
      if (ap !== bp) return bp - ap;
      return b.activity - a.activity;
    })
    .map(({ session }) => session);
}

/**
 * Number of sessions that should light up the quick-chat FAB unread badge.
 * `chatSessionsOptions` fetches `status=all` (active + archived) so the thread
 * list can render an Archived view, but archived sessions must NOT contribute
 * to the badge: they are read-only and hidden from the default history list, so
 * a badge sourced from one is uncleared-able — the user can't open it to mark it
 * read. Archiving now also drops the external-channel binding server-side, so no
 * new unread should land on an archived session; this filter is the front-end
 * half of that guarantee (MUL-4372).
 */
export function countUnreadChatSessions(sessions: ChatSession[]): number {
  return sessions.filter((s) => s.has_unread && s.status !== "archived").length;
}

export function chatPinnedAgentsOptions(wsId: string) {
  return queryOptions({
    queryKey: chatKeys.pinnedAgents(wsId),
    queryFn: () => api.listChatPinnedAgents({ workspaceId: wsId }),
    staleTime: Infinity,
  });
}

export function chatSessionOptions(wsId: string, id: string) {
  return queryOptions({
    queryKey: chatKeys.session(wsId, id),
    queryFn: () => api.getChatSession(id),
    enabled: !!id,
    staleTime: Infinity,
  });
}

export function chatMessagesOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.messages(sessionId),
    queryFn: () => api.listChatMessages(sessionId),
    enabled: !!sessionId,
    staleTime: Infinity,
  });
}

export function chatMessagesPageOptions(sessionId: string, limit = 50) {
  return infiniteQueryOptions({
    queryKey: chatKeys.messagesPage(sessionId),
    queryFn: ({ pageParam }) =>
      api.listChatMessagesPage(sessionId, { before: pageParam, limit }),
    initialPageParam: null as { created_at: string; id: string } | null,
    getNextPageParam: (lastPage) =>
      lastPage.has_more ? lastPage.next_cursor ?? undefined : undefined,
    enabled: !!sessionId,
    staleTime: Infinity,
  });
}

/**
 * Pending task for a chat session — the "is something still running?" signal.
 * Refetched via WS invalidation in useRealtimeSync when chat:message / chat:done
 * / task:completed / task:failed arrive.
 */
export function pendingChatTaskOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.pendingTask(sessionId),
    queryFn: () => api.getPendingChatTask(sessionId),
    enabled: !!sessionId,
    staleTime: Infinity,
  });
}

/**
 * Durable deferred-cancellation draft restores for a session (#5219).
 * staleTime 0 deliberately overrides the app-wide Infinity default: this is
 * the recovery path for a client that MISSED the chat:cancel_finalized
 * broadcast, so it must actually refetch on every composer mount (an
 * Infinity-fresh cache would pin the first result forever). WS reconnects
 * additionally invalidate chatKeys.draftRestoresAll() in useRealtimeSync,
 * and the initiator's realtime handler invalidates this key when the event
 * does arrive. The response is tiny (usually empty), so the extra fetches
 * are negligible.
 */
export function chatDraftRestoresOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.draftRestores(sessionId),
    queryFn: () => api.listChatDraftRestores(sessionId),
    enabled: !!sessionId,
    staleTime: 0,
  });
}

/** Kept fresh by chat:wakeup_changed; the countdowns tick client-side. */
export function chatWakeupsOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.wakeups(sessionId),
    queryFn: () => api.listChatSessionWakeups(sessionId),
    enabled: !!sessionId,
    staleTime: Infinity,
  });
}

/**
 * How many trailing assistant turns' task timelines to warm after prefetching
 * a session's newest message page. Keeps the visible tail from expanding
 * asynchronously when `AssistantMessage` upgrades from plain text to its
 * collapsible `TimelineView`, while capping cache entries for MUL-6396.
 */
const PREFETCH_TAIL_TASK_LIMIT = 2;

/**
 * Warms a chat session's conversation queries in parallel so archiving and
 * advancing to the next thread — or clicking an adjacent row — renders from
 * cache without flashing the skeleton or asynchronously popping in bottom
 * strips (wakeups). All warmed queries use `staleTime: Infinity`, so an
 * already-warm session costs nothing.
 */
export async function prefetchChatSession(
  qc: QueryClient,
  sessionId: string,
): Promise<void> {
  if (!sessionId) return;
  await Promise.all([
    qc.prefetchInfiniteQuery(chatMessagesPageOptions(sessionId)),
    qc.prefetchQuery(pendingChatTaskOptions(sessionId)),
    qc.prefetchQuery(chatWakeupsOptions(sessionId)),
  ]);

  const newestMessages =
    qc.getQueryData<InfiniteData<ChatMessagesPage>>(chatKeys.messagesPage(sessionId))
      ?.pages?.[0]?.messages ?? [];
  const tailTaskIds: string[] = [];
  const seen = new Set<string>();
  for (let i = newestMessages.length - 1; i >= 0 && tailTaskIds.length < PREFETCH_TAIL_TASK_LIMIT; i--) {
    const m = newestMessages[i];
    if (!m || m.role !== "assistant" || !isTaskMessageTaskId(m.task_id) || seen.has(m.task_id)) {
      continue;
    }
    seen.add(m.task_id);
    tailTaskIds.push(m.task_id);
  }
  if (tailTaskIds.length > 0) {
    await Promise.all(tailTaskIds.map((taskId) => qc.prefetchQuery(taskMessagesOptions(taskId))));
  }
}

export function myChatWakeupsOptions(wsId: string) {
  return queryOptions({
    queryKey: chatKeys.myWakeups(wsId),
    queryFn: () => api.listMyChatWakeups(),
    enabled: !!wsId,
    staleTime: Infinity,
  });
}

/**
 * Timeline for a single task — rendered by both the live chat view (while a
 * task is running) and AssistantMessage (for completed tasks). WS
 * `task:message` events seed this cache in real time via useRealtimeSync.
 */
export function taskMessagesOptions(taskId: string) {
  return queryOptions({
    queryKey: chatKeys.taskMessages(taskId),
    queryFn: () => api.listTaskMessages(taskId),
    enabled: isTaskMessageTaskId(taskId),
    staleTime: Infinity,
    // Every write to this cache — this fetch, a backfill, or a realtime batch —
    // folds into what is already there instead of replacing it. Without this a
    // response that resolves after a live frame was written would drop that
    // seq, and staleTime:Infinity means nothing would ever fetch it again.
    structuralSharing: (prev, next) =>
      unionTaskMessagesBySeq(
        prev as TaskMessagePayload[] | undefined,
        next as TaskMessagePayload[],
      ),
  });
}

/** A visible run follows WS updates and backfills on mount and completion. */
export function useTaskMessages(taskId: string, isLive: boolean, enabled = true) {
  const query = useQuery({
    ...taskMessagesOptions(taskId),
    enabled: enabled && isTaskMessageTaskId(taskId),
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
  });
  const previous = useRef({ isLive, enabled });
  const { refetch } = query;
  useEffect(() => {
    if (enabled && isTaskMessageTaskId(taskId)
      && (!previous.current.enabled || (previous.current.isLive && !isLive))) {
      void refetch({ cancelRefetch: false });
    }
    previous.current = { isLive, enabled };
  }, [taskId, isLive, enabled, refetch]);
  return query;
}

/**
 * Merge task-message batches into one seq-ordered, seq-deduplicated list for
 * the shared `["task-messages", taskId]` cache. Existing entries win on
 * conflict, and the original array reference is preserved when nothing new
 * arrives so React Query observers don't re-render on duplicate events.
 *
 * The one exception is a tool call the server sent twice: an agent that
 * restricts its tool details streams the call to the whole workspace without
 * them, and to the people allowed them a second time whole. Whichever copy
 * lands first, the whole one is what a reader keeps.
 *
 * Both the realtime `task:message` handler (a single payload) and the
 * transcript backfill (a full refetch) write this cache. Routing both through
 * one helper keeps a forced backfill from blind-replacing a seq the WebSocket
 * already delivered — and keeps a late WS event from being lost to an
 * in-flight backfill.
 */
export function mergeTaskMessagesBySeq(
  existing: readonly TaskMessagePayload[],
  incoming: readonly TaskMessagePayload[],
): TaskMessagePayload[] {
  if (incoming.length === 0) return existing as TaskMessagePayload[];
  const bySeq = new Map(existing.map((m) => [m.seq, m]));
  let changed = false;
  for (const msg of incoming) {
    const known = bySeq.get(msg.seq);
    if (!known || (known.details_hidden && !msg.details_hidden)) {
      bySeq.set(msg.seq, msg);
      changed = true;
    }
  }
  if (!changed) return existing as TaskMessagePayload[];
  return [...bySeq.values()].sort((a, b) => a.seq - b.seq);
}

/**
 * Union two task-message lists by seq, with `authoritative` winning on conflict.
 *
 * This is the rule every write to the `["task-messages", taskId]` cache goes
 * through, wired in as `structuralSharing` on the query itself so a fetch
 * result cannot replace the array wholesale.
 *
 * That matters because a normal query response and the realtime stream race:
 * the timeline is fetched on first open, and any frame that arrives while that
 * request is in flight is written to the cache before the response lands. A
 * plain replace would drop those seqs, and `staleTime: Infinity` means nothing
 * would ever refetch them — the gap would survive until a reload.
 *
 * Server data wins on conflict because the persisted row is the authority.
 * Rows the response did not mention are kept rather than deleted — a response
 * snapshotted before a seq was persisted must not erase it.
 *
 * The `base` reference is returned unchanged when nothing differs, so an event
 * that adds nothing does not re-render every subscriber.
 */
export function unionTaskMessagesBySeq(
  base: readonly TaskMessagePayload[] | undefined,
  authoritative: readonly TaskMessagePayload[],
): TaskMessagePayload[] {
  if (!base || base.length === 0) {
    return [...authoritative].sort((a, b) => a.seq - b.seq);
  }

  const bySeq = new Map(base.map((m) => [m.seq, m]));
  let changed = false;
  for (const msg of authoritative) {
    if (bySeq.get(msg.seq) !== msg) {
      bySeq.set(msg.seq, msg);
      changed = true;
    }
  }
  if (!changed) return base as TaskMessagePayload[];
  return [...bySeq.values()].sort((a, b) => a.seq - b.seq);
}

/**
 * True when this client holds a timeline cache entry for `taskId` — i.e. the
 * task was opened at some point and has not been garbage-collected since.
 *
 * Deliberately NOT "a view is mounted right now". Observer count would be a
 * tighter bound but an unsafe one: with `staleTime: Infinity` a task that
 * briefly drops to zero observers (an unmount/remount while navigating) would
 * discard frames, and the remount would read the surviving cache as fresh and
 * never fetch them back. Entry presence has no such gap — either the entry is
 * there and keeps accumulating, or it is gone and the next open fetches the
 * whole timeline. The cost is a bounded tail: writes do not postpone the GC
 * timer, so an entry outlives its last viewer by at most one `gcTime`.
 *
 * The realtime layer uses this to decide whether a `task:message` frame is
 * worth caching. Every client in the workspace receives every run's frames,
 * but only a handful of runs are ever opened; without this gate every client
 * accumulates the transcript of runs its user will never look at (MUL-6396).
 *
 * Presence, not data: mounting a `useQuery` registers the entry before the
 * fetch resolves, so a frame that lands mid-backfill is still kept. Dropping
 * a frame for an unregistered task is safe — the row is persisted before it
 * is broadcast, so whoever opens the task next fetches it from the server.
 */
export function isTaskMessageTimelineHeld(
  qc: QueryClient,
  taskId: string,
): boolean {
  return qc.getQueryCache().find({ queryKey: chatKeys.taskMessages(taskId) }) !== undefined;
}

/**
 * Aggregate of in-flight chat tasks for the current user in this workspace.
 * Drives the FAB "running" indicator while the chat window is minimised —
 * no per-session query is active then, so we need this roll-up.
 */
export function pendingChatTasksOptions(wsId: string) {
  return queryOptions({
    queryKey: chatKeys.pendingTasks(wsId),
    queryFn: () => api.listPendingChatTasks({ workspaceId: wsId }),
    staleTime: Infinity,
  });
}

/**
 * Boolean "is any chat task running for me right now" — the cheap sibling of
 * pendingChatTasksOptions. The FAB uses this (with `enabled: !isOpen`) so the
 * minimised chat button never fetches or holds the full task list; the
 * detailed list is reserved for the open ChatWindow (history + stop flows).
 * Both caches are kept in sync by the task-lifecycle WS handlers.
 */
export function hasPendingChatTasksOptions(wsId: string) {
  return queryOptions({
    queryKey: chatKeys.pendingTasksHasAny(wsId),
    queryFn: () => api.hasAnyPendingChatTasks({ workspaceId: wsId }),
    staleTime: Infinity,
  });
}

/**
 * Client-only cache entry: written by the realtime layer (chat:done raises
 * it, chat:quick_actions resolves it), never fetched from the server —
 * `enabled: false` keeps the queryFn from ever running; observers still
 * re-render on setQueryData.
 */
export function chatQuickActionsPendingOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.quickActionsPending(sessionId),
    queryFn: async (): Promise<ChatQuickActionsPendingState | null> => null,
    enabled: false,
    staleTime: Infinity,
  });
}

/**
 * Client-only cache entry mirroring {@link chatQuickActionsPendingOptions}:
 * the realtime layer writes it off a failed chat:quick_actions, a view reads
 * it once to toast "couldn't refresh," then clears it. Never fetched.
 */
export function chatQuickActionsFailureOptions(sessionId: string) {
  return queryOptions({
    queryKey: chatKeys.quickActionsFailure(sessionId),
    queryFn: async (): Promise<ChatQuickActionsFailureState | null> => null,
    enabled: false,
    staleTime: Infinity,
  });
}