Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

20.1 KB
Raw Blame
import type {
  ContextCompactionMark,
  HostedSearchRound,
  MessageUsage,
  UiMessage,
} from "@pi-desktop/shared";
import {
  addUsage,
  hostedSearchRounds,
  withoutReasoningReplayPlaceholder,
} from "@pi-desktop/shared";
import { getToolAction, isDelegationStartTool } from "./tool-display";
import { messageContentFacts } from "./transcript-summary";

export type AssistantActivityItem =
  | { kind: "thinking"; message: UiMessage }
  | {
      kind: "tool";
      message: UiMessage;
      /** Present on a `Task` call: what the delegate it spawned did. */
      delegate?: SubagentRun;
    }
  | {
      kind: "hostedSearch";
      message: UiMessage;
      /** One provider search round of the message; each round is a row. */
      round: HostedSearchRound;
    };

/** One row a delegate produced, in the order the delegate produced it. */
export type SubagentRunItem =
  | { kind: "thinking"; message: UiMessage }
  | { kind: "tool"; message: UiMessage }
  | { kind: "answer"; message: UiMessage };

/**
 * Everything one delegate did inside a single `Task` call (ADR 0062).
 *
 * Delegate rows arrive on the session stream interleaved with the parent's —
 * parallel delegates guarantee it — so they are collected by the `Task` call
 * that spawned them and rendered under it. That mirrors the model's view: the
 * parent only ever sees the report, never these rows.
 */
export type SubagentRun = {
  /** Definition name, when the runtime attributed the rows to one. */
  agentName?: string;
  items: SubagentRunItem[];
};

export type AssistantTurnPart =
  | { kind: "message"; message: UiMessage; sourceMessageId?: string }
  | {
      kind: "activity";
      items: AssistantActivityItem[];
      endedAt?: string;
    };

export type AssistantTurnEntry = {
  kind: "assistant-turn";
  id: string;
  anchorId?: string;
  parts: AssistantTurnPart[];
};

export type TranscriptEntry =
  | { kind: "message"; message: UiMessage }
  | { kind: "compaction"; mark: ContextCompactionMark }
  | AssistantTurnEntry;

export function messageThinking(message: UiMessage): string {
  if (typeof message.thinking !== "string") return "";
  // An echoed replay placeholder is not the model's reasoning (#1945).
  const thinking = withoutReasoningReplayPlaceholder(message.thinking);
  return thinking.trim() ? thinking : "";
}

function isVisibleMessage(message: UiMessage): boolean {
  if (message.role === "system" && message.modelSystem) return false;
  return !(
    message.role === "assistant" &&
    !messageContentFacts(message).hasContent &&
    !messageThinking(message) &&
    !message.hostedSearch &&
    !message.error
  );
}

/** A `Task` start call belongs on the delegation card; parent thinking, workspace
 * tools, and lifecycle rows (TaskWait/TaskList/TaskStop) do not (D319). */
function isDelegationStartActivity(item: AssistantActivityItem): boolean {
  return item.kind === "tool" && isDelegationStartTool(item.message.toolName);
}

/**
 * A `Bash` call or a run alias is a run row (ADR
 * turn-process-and-thinking-display). With commands expanded it renders as its
 * own row inside the turn's process disclosure; with commands folded it stays in
 * the activity group it ran among. Adjacent calls are still built as separate
 * activity parts, so entry topology does not depend on the preference.
 */
export function isStandaloneRunActivity(
  item: AssistantActivityItem,
): item is Extract<AssistantActivityItem, { kind: "tool" }> {
  return item.kind === "tool" && getToolAction(item.message.toolName) === "run";
}

/** Delegate rows grouped by the `Task` call that produced them, chains merged. */
function collectSubagentRuns(
  messages: readonly UiMessage[],
): Map<string, SubagentRun> {
  const latestCall = chainLatestCalls(messages);
  const runs = new Map<string, SubagentRun>();
  for (const message of messages) {
    const parent = message.parentToolCallId;
    if (!parent) continue;
    const key = latestCall(parent);
    let run = runs.get(key);
    if (!run) {
      run = { items: [] };
      runs.set(key, run);
    }
    if (message.agentName && !run.agentName) run.agentName = message.agentName;
    if (message.role === "tool") {
      run.items.push({ kind: "tool", message });
      continue;
    }
    // A delegate turn can carry reasoning and text at once, and both are worth
    // showing: the text is the only place its narration and report exist.
    const thinking = messageThinking(message);
    if (thinking) run.items.push({ kind: "thinking", message });
    if (messageContentFacts(message).hasContent || message.error) {
      run.items.push({ kind: "answer", message });
    }
  }
  return runs;
}

/**
 * The delegation-chain structure of one transcript (ADR 0279).
 *
 * `callByDelegationId` maps each Task result's `delegationId` to the call that
 * returned it; `childOf` links a resumed call to the call it resumed. Shared
 * by the delegation card grouping and the subagent transcript tab so both read
 * the same chain semantics from one place.
 */
export function delegationChainMaps(messages: readonly UiMessage[]): {
  callByDelegationId: Map<string, string>;
  childOf: Map<string, string>;
} {
  const callByDelegationId = new Map<string, string>();
  const childOf = new Map<string, string>();
  for (const message of messages) {
    if (message.role !== "tool" || !isDelegationStartTool(message.toolName)) {
      continue;
    }
    const toolCallId = message.toolCallId;
    if (!toolCallId) continue;
    const result = message.toolResult;
    const details =
      result && typeof result === "object" && !Array.isArray(result)
        ? (result as { details?: unknown }).details
        : undefined;
    const delegationId =
      details && typeof details === "object" && !Array.isArray(details)
        ? (details as { delegationId?: unknown }).delegationId
        : undefined;
    if (typeof delegationId === "string" && delegationId) {
      callByDelegationId.set(delegationId, toolCallId);
    }
    const args = message.toolArgs;
    const resume =
      args && typeof args === "object" && !Array.isArray(args)
        ? (args as { resume?: unknown }).resume
        : undefined;
    const prior =
      typeof resume === "string" && resume.trim()
        ? callByDelegationId.get(resume.trim())
        : undefined;
    if (prior) childOf.set(prior, toolCallId);
  }
  return { callByDelegationId, childOf };
}

// Map each Task call to the last call of its chain (ADR 0279): a resumed
// delegation is one delegate session continued by a later Task call, so the
// chain's rows all belong on the latest card, where they read as one
// continuing conversation rather than a card per call.
function chainLatestCalls(
  messages: readonly UiMessage[],
): (toolCallId: string) => string {
  const { childOf } = delegationChainMaps(messages);
  const latest = new Map<string, string>();
  return (toolCallId: string): string => {
    const cached = latest.get(toolCallId);
    if (cached) return cached;
    let current = toolCallId;
    const seen = new Set<string>([current]);
    for (;;) {
      const next = childOf.get(current);
      if (!next || seen.has(next)) break;
      seen.add(next);
      current = next;
    }
    latest.set(toolCallId, current);
    return current;
  };
}

function appendAssistantTurnMessage(
  current: AssistantTurnEntry,
  message: UiMessage,
  delegate?: SubagentRun,
) {
  const pushActivity = (item: AssistantActivityItem) => {
    const last = current.parts[current.parts.length - 1];
    const standalone = isStandaloneRunActivity(item);
    const lastStandalone =
      last?.kind === "activity" &&
      last.items.length === 1 &&
      isStandaloneRunActivity(last.items[0]);
    // A delegation card is only the Task fan-out. Mixing the parent's later
    // Read/Grep/thinking into that group painted them as subagent work (D319).
    // A standalone run row never merges with a neighbour, so adjacent Bash
    // calls each keep their own row.
    if (
      last?.kind === "activity" &&
      last.items.length > 0 &&
      !standalone &&
      !lastStandalone &&
      isDelegationStartActivity(last.items[0]) === isDelegationStartActivity(item)
    ) {
      last.items.push(item);
      return;
    }
    current.parts.push({ kind: "activity", items: [item] });
  };

  if (message.role === "tool") {
    pushActivity({
      kind: "tool",
      message,
      ...(delegate ? { delegate } : {}),
    });
    return;
  }
  const thinking = messageThinking(message);
  if (thinking) pushActivity({ kind: "thinking", message });
  for (const round of hostedSearchRounds(message.hostedSearch)) {
    pushActivity({ kind: "hostedSearch", message, round });
  }
  const hasContent = messageContentFacts(message).hasContent;
  if (hasContent || !thinking || message.error) {
    current.parts.push({ kind: "message", message });
    if (!current.anchorId && hasContent) {
      current.anchorId = message.id;
    }
  }
}

function finishAssistantTurn(entry: AssistantTurnEntry) {
  for (let index = 0; index < entry.parts.length; index += 1) {
    const part = entry.parts[index];
    const next = entry.parts[index + 1];
    if (
      part.kind === "activity" &&
      next?.kind === "message" &&
      !part.items.some((item) => item.message.id === next.message.id)
    ) {
      part.endedAt = next.message.createdAt;
    }
  }
}

/** Project the already scoped child messages of one Task call as one turn. */
export function buildDelegationReply(callId: string, messages: readonly UiMessage[]): AssistantTurnEntry {
  const entry: AssistantTurnEntry = { kind: "assistant-turn", id: callId, parts: [] };
  for (const message of messages) {
    if ((message.role === "assistant" || message.role === "tool") && isVisibleMessage(message)) {
      appendAssistantTurnMessage(entry, message);
    }
  }
  finishAssistantTurn(entry);
  return entry;
}

/**
 * Group provider-level assistant fragments and tool rows into user-level turns.
 * Providers end an assistant message before each tool call, but that transport
 * boundary is not a separate conversational response.
 *
 * `compactions` (oldest first) each produce a divider row right after the
 * message they cover, mirroring how the runtime splices its checkpoint entry
 * after the same anchor. A mark whose anchor is no longer in the transcript —
 * rewritten, forked away — has nowhere to sit and is dropped.
 */
export function buildTranscriptEntries(
  messages: UiMessage[],
  compactions: readonly ContextCompactionMark[] = [],
): {
  entries: TranscriptEntry[];
  visible: UiMessage[];
} {
  const runs = collectSubagentRuns(messages);
  // Delegate rows are not transcript rows of their own: they hang off their
  // `Task` call, so they stay out of the turn stream and the minimap.
  const visible = messages.filter(
    (message) => !message.parentToolCallId && isVisibleMessage(message),
  );
  const anchored = new Map<string, ContextCompactionMark[]>();
  for (const mark of compactions) {
    const marks = anchored.get(mark.throughMessageId);
    if (marks) marks.push(mark);
    else anchored.set(mark.throughMessageId, [mark]);
  }
  const entries: TranscriptEntry[] = [];
  let turn: AssistantTurnEntry | undefined;

  const ensureTurn = (message: UiMessage) => {
    if (turn) return turn;
    turn = {
      kind: "assistant-turn",
      id: message.id,
      parts: [],
    };
    entries.push(turn);
    return turn;
  };

  const appendMessage = (message: UiMessage) => {
    if (message.role === "user" || message.role === "system") {
      turn = undefined;
      entries.push({ kind: "message", message });
      return;
    }

    const delegate = message.role === "tool" && message.toolCallId
      ? runs.get(message.toolCallId) : undefined;
    appendAssistantTurnMessage(ensureTurn(message), message, delegate);
  };

  let previousRootTurnId: string | undefined;
  for (const message of visible) {
    const rootTurnId = typeof message.turnId === "string" ? message.turnId.trim() : undefined;
    if (rootTurnId) {
      if (previousRootTurnId && rootTurnId !== previousRootTurnId) turn = undefined;
      previousRootTurnId = rootTurnId;
    }
    appendMessage(message);
    const marks = anchored.get(message.id);
    if (!marks) continue;
    // The row is a divider, so whatever turn it lands inside ends there and the
    // next assistant fragment opens a new one.
    turn = undefined;
    for (const mark of marks) entries.push({ kind: "compaction", mark });
  }

  for (const entry of entries) {
    if (entry.kind === "assistant-turn") finishAssistantTurn(entry);
  }

  return { entries, visible };
}

/**
 * Whether two delegate runs render the same rows.
 *
 * `buildTranscriptEntries` rebuilds run objects on every message change, so
 * memoized activity groups cannot compare them by identity; without this a
 * delegate's rows would either never update or re-render on every tick.
 */
export function subagentRunsEqual(
  previous: SubagentRun | undefined,
  next: SubagentRun | undefined,
): boolean {
  if (previous === next) return true;
  if (!previous || !next) return false;
  if (
    previous.agentName !== next.agentName ||
    previous.items.length !== next.items.length
  ) {
    return false;
  }
  return previous.items.every(
    (item, index) =>
      item.kind === next.items[index].kind &&
      item.message === next.items[index].message,
  );
}

export function reuseReadonlyMap<K, V>(
  previous: ReadonlyMap<K, V> | undefined,
  next: ReadonlyMap<K, V>,
  valuesEqual: (left: V, right: V) => boolean = Object.is,
): ReadonlyMap<K, V> {
  if (!previous || previous.size !== next.size) return next;
  for (const [key, value] of next) {
    if (!previous.has(key) || !valuesEqual(previous.get(key) as V, value)) {
      return next;
    }
  }
  return previous;
}

function reuseActivityItem(
  previous: AssistantActivityItem | undefined,
  next: AssistantActivityItem,
): AssistantActivityItem {
  if (!previous || previous.kind !== next.kind || previous.message !== next.message) {
    return next;
  }
  if (previous.kind === "tool" && next.kind === "tool") {
    if (subagentRunsEqual(previous.delegate, next.delegate)) return previous;
    if (!next.delegate || !previous.delegate) return next;
    const items = next.delegate.items.map((item, index) => {
      const prior = previous.delegate?.items[index];
      return prior && prior.kind === item.kind && prior.message === item.message
        ? prior
        : item;
    });
    const delegate =
      previous.delegate.agentName === next.delegate.agentName &&
      previous.delegate.items.length === items.length &&
      items.every((item, index) => item === previous.delegate!.items[index])
        ? previous.delegate
        : { ...next.delegate, items };
    return delegate === previous.delegate ? previous : { ...next, delegate };
  }
  return previous;
}

function reuseTurnPart(
  previous: AssistantTurnPart | undefined,
  next: AssistantTurnPart,
): AssistantTurnPart {
  if (!previous || previous.kind !== next.kind) return next;
  if (previous.kind === "message" && next.kind === "message") {
    return previous.message === next.message ? previous : next;
  }
  if (previous.kind === "activity" && next.kind === "activity") {
    if (previous.endedAt !== next.endedAt) {
      const items = next.items.map((item, index) =>
        reuseActivityItem(previous.items[index], item),
      );
      return { ...next, items };
    }
    const items = next.items.map((item, index) =>
      reuseActivityItem(previous.items[index], item),
    );
    if (
      items.length === previous.items.length &&
      items.every((item, index) => item === previous.items[index])
    ) {
      return previous;
    }
    return { ...next, items };
  }
  return next;
}

function reuseTranscriptEntry(
  previous: TranscriptEntry | undefined,
  next: TranscriptEntry,
): TranscriptEntry {
  if (!previous || previous.kind !== next.kind) return next;
  if (previous.kind === "message" && next.kind === "message") {
    return previous.message === next.message ? previous : next;
  }
  if (previous.kind === "compaction" && next.kind === "compaction") {
    return previous.mark === next.mark ||
      (previous.mark.id === next.mark.id &&
        previous.mark.throughMessageId === next.mark.throughMessageId &&
        previous.mark.generation === next.mark.generation &&
        previous.mark.summaryTokens === next.mark.summaryTokens &&
        previous.mark.summarized === next.mark.summarized &&
        previous.mark.fallback === next.mark.fallback)
      ? previous
      : next;
  }
  if (previous.kind === "assistant-turn" && next.kind === "assistant-turn") {
    if (previous.id !== next.id) return next;
    const parts = next.parts.map((part, index) =>
      reuseTurnPart(previous.parts[index], part),
    );
    if (
      previous.anchorId === next.anchorId &&
      parts.length === previous.parts.length &&
      parts.every((part, index) => part === previous.parts[index])
    ) {
      return previous;
    }
    return { ...next, parts };
  }
  return next;
}

/**
 * Keep object identity for unchanged transcript rows so memoized activity
 * groups can bail out when only the live tail token changed.
 */
export function reuseTranscriptEntries(
  previous: readonly TranscriptEntry[] | undefined,
  next: TranscriptEntry[],
): TranscriptEntry[] {
  if (!previous || previous.length === 0) return next;
  const shared = next.map((entry, index) =>
    reuseTranscriptEntry(previous[index], entry),
  );
  if (
    shared.length === previous.length &&
    shared.every((entry, index) => entry === previous[index])
  ) {
    return previous as TranscriptEntry[];
  }
  return shared;
}

export function assistantTurnMessages(
  entry: AssistantTurnEntry,
): UiMessage[] {
  return entry.parts.flatMap((part) =>
    part.kind === "message" ? [part.message] : [],
  );
}

/**
 * The rows these entries actually render, in transcript order.
 *
 * The minimap resolves a click by finding the marker's `data-minimap-id` node in
 * the scroller, so it must be built from the mounted entries rather than from
 * every loaded message (D261). Fed the full set while the transcript window
 * withholds older rows, it would draw dashes whose click target does not exist
 * and jump nowhere.
 */
export function transcriptEntryMessages(
  entries: readonly TranscriptEntry[],
): UiMessage[] {
  return entries.flatMap((entry) => {
    if (entry.kind === "message") return [entry.message];
    if (entry.kind === "assistant-turn") return assistantTurnMessages(entry);
    return [];
  });
}

export function assistantTurnTools(entry: AssistantTurnEntry): UiMessage[] {
  return entry.parts.flatMap((part) =>
    part.kind === "activity"
      ? part.items.flatMap((item) =>
          item.kind === "tool" ? [item.message] : [],
        )
      : [],
  );
}

export function assistantTurnResponseDuration(
  entry: AssistantTurnEntry,
): number | undefined {
  const durations = assistantTurnMessages(entry).flatMap((message) =>
    typeof message.responseDurationMs === "number" &&
    Number.isFinite(message.responseDurationMs) &&
    message.responseDurationMs > 0
      ? [message.responseDurationMs]
      : [],
  );
  if (durations.length === 0) return undefined;
  return durations.reduce((total, duration) => total + duration, 0);
}

export function assistantTurnResponseOutputTokens(
  entry: AssistantTurnEntry,
): number | undefined {
  const counts = assistantTurnMessages(entry).flatMap((message) => {
    const value = message.usage?.outputTokens ?? message.responseOutputTokens;
    return typeof value === "number" && Number.isFinite(value) && value > 0
      ? [value]
      : [];
  });
  if (counts.length === 0) return undefined;
  return counts.reduce((total, count) => total + count, 0);
}

export function assistantTurnResponseOutputIsEstimated(
  entry: AssistantTurnEntry,
): boolean {
  return assistantTurnMessages(entry).some(
    (message) =>
      (!message.usage || message.usage.outputTokens <= 0) &&
      typeof message.responseOutputTokens === "number" &&
      message.responseOutputTokens > 0,
  );
}

export { getAssistantTurnContent as assistantTurnContent } from "./transcript-summary";

export function assistantTurnUsage(
  entry: AssistantTurnEntry,
): MessageUsage | undefined {
  const usages = assistantTurnMessages(entry).flatMap((message) =>
    message.usage ? [message.usage] : [],
  );
  if (usages.length === 0) return undefined;

  return usages.reduce<MessageUsage | undefined>((total, usage) => addUsage(total, usage), undefined);
}