Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

11.9 KB
Raw Blame
import {
  sharedContextLabel,
  type CoreContext,
  type CoreProject,
  type CoreSession,
  type SessionBackgroundView,
} from "./core-bridge.ts";
import { descendantsOf } from "./subagent-activity.ts";
import { goalFloorLabel, goalWorkedLabel } from "./goal-strip.ts";
import { relTime } from "./ui.ts";

type ProjectAwareContext = CoreContext & { project?: CoreProject };

type RecentGroupKind = "personal" | "project" | "channel" | "group";

export interface RecentProjectSeed {
  scopeId: string;
  name: string | null;
  kind?: RecentGroupKind;
}

export type RecentItem =
  | { kind: "session"; session: CoreSession }
  | { kind: "project"; scopeId: string; name: string | null; groupKind: RecentGroupKind; sessions: CoreSession[] };

export function activityOf(s: CoreSession): number {
  return s.lastActivityAt ?? s.createdAt;
}

export type ChatBrowseStatus = "active" | "waiting" | "archived";

export function surfaceOf(s: Pick<CoreSession, "surface">): "web" | "slack" | "core" {
  return s.surface === "web" || s.surface === "slack" ? s.surface : "core";
}

const AUTOMATION_RUN_LABELS: Record<string, string> = {
  cron: "Cron run",
  webhook: "Webhook run",
  loop: "Loop run",
};

export function automationRunLabel(s: Pick<CoreSession, "surface">): string | null {
  return (s.surface && AUTOMATION_RUN_LABELS[s.surface]) || null;
}

export function sidebarSessions(sessions: readonly CoreSession[]): CoreSession[] {
  return sessions.filter((session) => !session.parentSessionId && !automationRunLabel(session));
}

export function splitPinned<T extends Pick<CoreSession, "pinned">>(sessions: readonly T[]): { pinned: T[]; rest: T[] } {
  const pinned: T[] = [];
  const rest: T[] = [];
  for (const s of sessions) (s.pinned ? pinned : rest).push(s);
  return { pinned, rest };
}

export function chatBrowseStatusMatches(
  session: Pick<CoreSession, "archived" | "awaitingInput">,
  status: ChatBrowseStatus,
): boolean {
  if (status === "archived") return Boolean(session.archived);
  if (session.archived) return false;
  return status === "waiting" ? Boolean(session.awaitingInput) : !session.awaitingInput;
}

export function recentProjectSeeds(contexts: readonly ProjectAwareContext[]): RecentProjectSeed[] {
  return contexts.map((context): RecentProjectSeed => {
    if (context.project)
      return { scopeId: context.scopeId, name: context.project.name.trim() || null, kind: "project" };
    if (context.kind === "personal") return { scopeId: context.scopeId, name: "Personal", kind: "personal" };
    if (context.kind === "group")
      return { scopeId: context.scopeId, name: sharedContextLabel(context.scopeId, context.name), kind: "group" };
    return { scopeId: context.scopeId, name: sharedContextLabel(context.scopeId, context.name), kind: "channel" };
  });
}

export function groupProjectSessions(
  sessions: readonly CoreSession[],
  projectSeeds: readonly RecentProjectSeed[],
): RecentItem[] {
  const seeds = new Map(projectSeeds.map((seed) => [seed.scopeId, seed]));
  const projects = new Map<string, Extract<RecentItem, { kind: "project" }>>();
  const items: RecentItem[] = [];
  for (const session of [...sessions].sort((a, b) => activityOf(b) - activityOf(a))) {
    const seed = seeds.get(session.scopeId);
    if (!seed) {
      items.push({ kind: "session", session });
      continue;
    }
    let project = projects.get(session.scopeId);
    if (!project) {
      project = {
        kind: "project",
        scopeId: session.scopeId,
        name: seed.name,
        groupKind: seed.kind ?? "project",
        sessions: [],
      };
      projects.set(session.scopeId, project);
      items.push(project);
    }
    project.sessions.push(session);
  }
  for (const seed of projectSeeds) {
    if (projects.has(seed.scopeId)) continue;
    const kind = seed.kind ?? "project";
    if (kind === "channel" || kind === "group") continue;
    items.push({ kind: "project", scopeId: seed.scopeId, name: seed.name, groupKind: kind, sessions: [] });
  }
  return items;
}

export function recencyGroup(ms: number, now = Date.now()): string {
  const d = new Date(now);
  const dayStart = (back: number): number => new Date(d.getFullYear(), d.getMonth(), d.getDate() - back).getTime();
  if (ms >= dayStart(0)) return "Today";
  if (ms >= dayStart(1)) return "Yesterday";
  if (ms >= dayStart(6)) return "Previous 7 days";
  if (ms >= dayStart(29)) return "Previous 30 days";
  return "Older";
}

export function withPendingSession(list: CoreSession[], pending: CoreSession): CoreSession[] {
  return [pending, ...list.filter((s) => s.threadRef !== pending.threadRef)];
}

/** An unsent new chat the user walked away from, with nothing worth keeping. */
export function isAbandonedNewChat(state: {
  threadRef: string | null;
  nextThreadRef: string | null;
  sessionId: string | null;
  pendingSend: string | null;
  hasHumanMessage: boolean;
  draft: string;
  attachments: number;
}): boolean {
  const ref = state.threadRef;
  if (!ref || ref === state.nextThreadRef) return false;
  if (state.sessionId !== null || state.pendingSend === ref) return false;
  if (state.hasHumanMessage) return false;
  if (state.draft.trim() || state.attachments > 0) return false;
  return true;
}

export function withoutUnsentPending(list: CoreSession[], threadRef: string): CoreSession[] {
  return list.filter((s) => s.id !== "" || s.threadRef !== threadRef);
}

export function bumpActivity(list: CoreSession[], threadRef: string, at: number): CoreSession[] {
  return list.map((s) => (s.threadRef === threadRef ? { ...s, lastActivityAt: at } : s));
}

export function upsertSessions(prev: CoreSession[], rows: readonly CoreSession[]): CoreSession[] {
  if (!rows.length) return prev;
  const incoming = new Map(rows.map((row) => [row.id, row]));
  const threads = new Set(rows.map((row) => row.threadRef));
  const kept = prev.filter((row) => !incoming.has(row.id) && !threads.has(row.threadRef));
  return [...kept, ...rows];
}

export interface PageWindow {
  archived: boolean;
  surface?: string;
  floor: number | null;
}

function inPageClass(row: CoreSession, window: PageWindow): boolean {
  if (!row.id || row.parentSessionId || automationRunLabel(row)) return false;
  if (Boolean(row.archived) !== window.archived) return false;
  if (window.surface && row.surface !== window.surface) return false;
  return true;
}

export function mergeFirstPage(
  prev: CoreSession[],
  page: { sessions: readonly CoreSession[]; pinned?: readonly CoreSession[] },
  window: PageWindow,
  openIds: readonly string[] = [],
): CoreSession[] {
  const served = new Set([...page.sessions, ...(page.pinned ?? [])].map((row) => row.id));
  const open = new Set(openIds);
  const kept = prev.filter((row) => {
    if (served.has(row.id) || open.has(row.id) || !inPageClass(row, window)) return true;
    if (row.pinned && !window.archived) return false;
    return window.floor !== null && activityOf(row) < window.floor;
  });
  return upsertSessions(kept, [...(page.pinned ?? []), ...page.sessions]);
}

export function mergeChildren(prev: CoreSession[], rootId: string, children: readonly CoreSession[]): CoreSession[] {
  const below = new Set(descendantsOf(prev, rootId).map(({ session }) => session.id));
  const served = new Set(children.map((row) => row.id));
  return upsertSessions(
    prev.filter((row) => !below.has(row.id) || served.has(row.id)),
    children,
  );
}

export function markWorking(list: CoreSession[], threadRef: string): CoreSession[] {
  return list.map((s) => (s.threadRef === threadRef ? { ...s, working: true } : s));
}

export function clearWorking(list: CoreSession[], threadRef: string): CoreSession[] {
  return list.map((s) => (s.threadRef === threadRef ? { ...s, working: false } : s));
}

export type SessionRow = CoreSession & { stateAt?: number };

export interface SessionStateDelta {
  threadRef: string;
  state: "working" | "awaiting_approval" | "idle";
  at?: number;
}

export function applySessionState(
  list: SessionRow[],
  delta: SessionStateDelta,
): { list: SessionRow[]; matched: boolean } {
  let matched = false;
  const next = list.map((s) => {
    if (s.threadRef !== delta.threadRef) return s;
    matched = true;
    if (delta.at !== undefined && s.stateAt !== undefined && delta.at < s.stateAt) return s;
    return {
      ...s,
      working: delta.state === "working",
      awaitingInput: delta.state === "awaiting_approval",
      ...(delta.at !== undefined ? { stateAt: delta.at } : {}),
    };
  });
  return { list: matched ? next : list, matched };
}

export interface RowIndicators {
  working: boolean;
  awaiting: boolean;
  background: BackgroundCounts | null;
}

export interface BackgroundCounts {
  jobs: number;
  watches: number;
  crons: number;
  subagents: number;
  goal: boolean;
  label: string;
}

export function backgroundLabel(
  jobs: number,
  watches: number,
  crons: number,
  subagents = 0,
  subagentsWaiting = 0,
  goal?: { activeMs: number; runningSince?: number; floor?: Record<string, number> },
  now = Date.now(),
): BackgroundCounts | null {
  const parts: string[] = [];
  if (goal)
    parts.push(
      `goal · ${goalWorkedLabel(goal.activeMs + (goal.runningSince ? Math.max(0, now - goal.runningSince) : 0), goalFloorLabel(goal.floor ?? null))}`,
    );
  if (subagents > 0) parts.push(`${subagents} subagent${subagents === 1 ? "" : "s"} running`);
  if (subagentsWaiting > 0)
    parts.push(`${subagentsWaiting} subagent${subagentsWaiting === 1 ? " needs" : "s need"} you`);
  if (jobs > 0) parts.push(`${jobs} background job${jobs === 1 ? "" : "s"} running`);
  if (watches > 0) parts.push(`${watches} watch${watches === 1 ? "" : "es"} armed`);
  if (crons > 0) parts.push(`${crons} cron${crons === 1 ? "" : "s"} scheduled here`);
  return parts.length
    ? { jobs, watches, crons, subagents: subagents + subagentsWaiting, goal: Boolean(goal), label: parts.join(" · ") }
    : null;
}

export function watchActivityLabel(w: { lastFiredAt?: number }): string {
  return w.lastFiredAt ? `still watching · last check ${relTime(w.lastFiredAt)}` : "still watching";
}

export function rowIndicators(s: CoreSession, liveThreads: ReadonlySet<string> | string | null): RowIndicators {
  const live = typeof liveThreads === "string" ? new Set([liveThreads]) : (liveThreads ?? new Set<string>());
  const children = s.subagents ?? { running: 0, waiting: 0 };
  return {
    working: Boolean(s.working) || (Boolean(s.threadRef) && live.has(s.threadRef)),
    awaiting: Boolean(s.awaitingInput) || children.waiting > 0,
    background: backgroundLabel(
      s.backgroundJobs ?? 0,
      s.watches ?? 0,
      s.crons ?? 0,
      children.running,
      children.waiting,
      s.goal,
    ),
  };
}

export function conversationBackground(
  list: CoreSession[],
  sessionId: string | null,
  threadRef: string | null,
): RowIndicators["background"] {
  const row = list.find((s) => (sessionId ? s.id === sessionId : Boolean(threadRef) && s.threadRef === threadRef));
  return row ? rowIndicators(row, null).background : null;
}

export function shouldStartProactiveOpener(state: {
  started: boolean;
  sessionId: string | null;
  scopeId: string | null;
  messageCount: number;
  loaded: boolean;
  sessions: readonly Pick<CoreSession, "id" | "surface">[];
}): boolean {
  return (
    !state.started &&
    state.sessionId === null &&
    state.scopeId === null &&
    state.messageCount === 0 &&
    state.loaded &&
    !state.sessions.some((session) => session.id && !automationRunLabel(session))
  );
}

export function cronRowMeta(c: SessionBackgroundView["crons"][number]): string {
  const next = c.nextFireAt ? `next fire ${nextFireIn(c.nextFireAt)}` : "paused";
  if (!c.lastFire) return next;
  if (c.lastFire.status === "running") return `${next} · running now`;
  return `${next} · last ${c.lastFire.status ?? "fired"} ${relTime(c.lastFire.firedAt)}`;
}

function nextFireIn(at: number): string {
  const mins = Math.round((at - Date.now()) / 60_000);
  if (mins <= 0) return "due now";
  if (mins < 60) return `in ${mins}m`;
  if (mins < 1440) return `in ${Math.floor(mins / 60)}h ${String(mins % 60).padStart(2, "0")}m`;
  return `in ${Math.floor(mins / 1440)}d`;
}