All files / src/util runningTurns.ts

100% Statements 8/8
100% Branches 14/14
100% Functions 3/3
100% Lines 7/7

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68                                                      8x 8x                       7x 6x 2x   4x                 5x                            
import type { AttachmentRef, ChatMessage, Conversation } from "@/objects/Model";
import type { RunningTurn } from "@/objects/Turn";
 
/**
 * Drawing a turn still running on the server (`RunningTurn`) in a chat page
 * that did not start it — the person left mid-answer and came back, or it
 * is running in another window. The page shows the message as it will be
 * stored, a status in place of the live stream, and a Stop that reaches the
 * turn, until svc-core stores it and the conversation holds the answer.
 *
 * `parse` is the page's own reading of a stored user message (the documents
 * a message carries become attachment chips), given its meta.
 */
 
export type ParseUserMessage = (
  content: string,
  meta?: unknown,
) => {
  displayContent: string;
  attachments: AttachmentRef[];
};
 
/** The running turn's message, drawn as the conversation will store it. */
export function turnMessage(
  turn: RunningTurn,
  parse: ParseUserMessage,
): ChatMessage {
  const { displayContent, attachments } = parse(turn.prompt ?? "", turn.meta);
  return {
    role: "user",
    // Null for the moment before the input rules have run.
    content: displayContent || "…",
    sent_at: turn.started_at,
    ...(attachments.length > 0 ? { attachments } : {}),
    ...(turn.meta?.command ? { meta: { command: turn.meta.command } } : {}),
  };
}
 
/** What the answer bubble says while the turn runs elsewhere. */
export function turnStatusMessage(turn: RunningTurn): string {
  if (turn.stopping) return "Stopping…";
  if (turn.status === "awaiting_input") {
    return "Waiting for an answer to its question, in the window that asked it.";
  }
  return "Still answering. The reply appears here when it's ready.";
}
 
/** A conversation the sidebar can list for a turn whose conversation is not
 *  stored yet — a new chat's first answer. */
export function pendingConversation(
  turn: RunningTurn,
  parse: ParseUserMessage,
): Conversation {
  return {
    id: turn.conversation_id,
    created_at: turn.started_at,
    messages: turn.prompt
      ? [
          {
            role: "user",
            content: parse(turn.prompt).displayContent,
            sent_at: turn.started_at,
          },
        ]
      : [],
  } as unknown as Conversation;
}