All files / src/util chatAttachments.ts

97.01% Statements 65/67
91.42% Branches 32/35
77.77% Functions 7/9
100% Lines 60/60

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161                                  21x   60x 6x 6x 6x 5x 5x     5x 5x   5x 6x 5x         55x 55x 1x 1x 1x 1x 1x 1x   1x 2x 1x       54x           64x 64x 7x 9x                                 21x 62x 62x 56x         21x                   21x                       9x 9x 6x 6x 3x   3x 3x 3x 3x   6x 6x       21x   21x                       21x         6x 6x 6x 9x 9x 9x 9x   5x     5x 1x 1x   4x    
import type { AttachmentRef } from "@/objects/Model";
import type { FileRouter, UploadedFileRef } from "@/services/api/routers/FileRouter";
import type { ParseUserMessage } from "@/util/runningTurns";
 
/**
 * Parses a stored user message that may contain an attached-file context
 * block injected by the backend before the user's actual question, so a chat
 * shows the question with the documents as chips rather than their text.
 *
 * Three historical formats are handled for backward compatibility:
 *   1. XML (current):   <documents>...<source>name</source>...</documents>\n\n{question}
 *   2. Bracket-sep:     [Attached file: name]\ncontent\n\n---\n\n{question}
 *   3. System messages: handled separately in each chat's history loop (old
 *      backend format)
 *
 * Shared by the agent and model chats, which each carried a copy.
 */
export const parseUserMessageAttachments: ParseUserMessage = (content) => {
  // Format 1 — XML documents block
  if (content.startsWith("<documents>")) {
    const endTag = "</documents>";
    const endIdx = content.indexOf(endTag);
    if (endIdx >= 0) {
      const docsBlock = content.slice(0, endIdx + endTag.length);
      const displayContent = content
        .slice(endIdx + endTag.length)
        .replace(/^\n+/, "");
      const attachments: { name: string }[] = [];
      const re = /<source>(.+?)<\/source>/g;
      let hit: RegExpExecArray | null;
      while ((hit = re.exec(docsBlock)) !== null)
        attachments.push({ name: hit[1] });
      return { displayContent, attachments };
    }
  }
 
  // Format 2 — bracket separator
  const SEP = "\n\n---\n\n";
  if (content.startsWith("[Attached file:")) {
    const sepIdx = content.indexOf(SEP);
    Eif (sepIdx >= 0) {
      const fileSection = content.slice(0, sepIdx);
      const displayContent = content.slice(sepIdx + SEP.length);
      const attachments: { name: string }[] = [];
      const re = /\[Attached file: (.+?)\]/g;
      let hit: RegExpExecArray | null;
      while ((hit = re.exec(fileSection)) !== null)
        attachments.push({ name: hit[1] });
      return { displayContent, attachments };
    }
  }
 
  return { displayContent: content, attachments: [] };
};
 
/** The documents a stored message keeps beside its words
 *  (`meta.attachments`, svc-core since 24 October 2026). */
export function storedAttachments(meta: unknown): AttachmentRef[] {
  const refs = (meta as { attachments?: unknown } | null | undefined)?.attachments;
  if (!Array.isArray(refs)) return [];
  return refs.flatMap((ref) =>
    ref && typeof ref === "object" && typeof ref.name === "string" && ref.name
      ? [
          {
            name: ref.name,
            ...(typeof ref.id === "string" ? { id: ref.id } : {}),
            ...(typeof ref.mime_type === "string" ? { mime_type: ref.mime_type } : {}),
          },
        ]
      : [],
  );
}
 
/**
 * A user message's words and the documents it attached: kept beside the
 * words (`meta.attachments`) since 24 October 2026, pasted in front of them
 * before that (`parseUserMessageAttachments`).
 */
export const messageAttachments: ParseUserMessage = (content, meta) => {
  const stored = storedAttachments(meta);
  if (stored.length > 0) return { displayContent: content, attachments: stored };
  return parseUserMessageAttachments(content);
};
 
/** Types a browser is let show in a tab of their own. Never HTML or SVG:
 *  opened from a blob, either would run as this app. */
const SHOWN_IN_A_TAB: ReadonlySet<string> = new Set([
  "application/pdf",
  "image/png",
  "image/jpeg",
  "image/gif",
  "image/webp",
]);
 
/** How long a document's blob URL lives once opened: the new tab has read
 *  it by then. */
const BLOB_URL_LIFETIME_MS = 60_000;
 
/**
 * Open an attached document as it was uploaded: a PDF or an image in a new
 * tab, anything else saved under its name. Resolves false when there is
 * nothing to open — deleted from the library, or uploaded before originals
 * were kept.
 */
export async function openAttachment(
  files: Pick<FileRouter, "fetchContent">,
  ref: AttachmentRef & { id: string },
): Promise<boolean> {
  const content = await files.fetchContent(ref.id, ref.name);
  if (!content) return false;
  const url = URL.createObjectURL(content.blob);
  if (SHOWN_IN_A_TAB.has(content.blob.type)) {
    window.open(url, "_blank", "noopener,noreferrer");
  } else {
    const link = document.createElement("a");
    link.href = url;
    link.download = content.filename;
    link.click();
  }
  setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_LIFETIME_MS);
  return true;
}
 
/** How often a chat asks whether an upload's text has been read. */
export const READ_POLL_MS = 1500;
/** Failed asks in a row (a deploy, a dropped connection) before giving up. */
const READ_POLL_ERRORS = 3;
 
/**
 * Upload `file` to the workspace's library and wait until svc-core has read
 * its text: resolves with the document once `ready`, rejects with why once
 * it `failed`, and deletes it then, since a chat cannot use it.
 *
 * svc-core reads it after answering, because docling takes minutes on a long
 * PDF: waiting inside the upload, the request was cut off by svc-bff (20 s)
 * and Cloudflare (100 s). The chat keeps the file's chip spinning, and Send
 * held, until this settles.
 */
export const uploadAndRead = async (
  files: Pick<FileRouter, "uploadFile" | "getFile" | "deleteFile">,
  file: File,
  pollMs: number = READ_POLL_MS,
): Promise<UploadedFileRef | null> => {
  let doc = await files.uploadFile(file);
  let errors = 0;
  while (doc?.status === "reading") {
    await new Promise((resolve) => setTimeout(resolve, pollMs));
    try {
      doc = (await files.getFile(doc.id)) ?? doc;
      errors = 0;
    } catch (e) {
      if (++errors >= READ_POLL_ERRORS) throw e;
    }
  }
  if (doc?.status === "failed") {
    await files.deleteFile(doc.id).catch(() => undefined);
    throw new Error(doc.error || "It could not be read.");
  }
  return doc;
};