Skip to content

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

23.0 KB
Raw Blame
import {
  composerMentionText,
  fileReferenceLabel,
  formatFileInsert,
} from "@pi-desktop/shared";
import type { ComposerPluginPart } from "../../../lib/composer-smart-stop";
import type { ComposerFileReference } from "./model";
import { fileLineLabel, type FileLineRange } from "@pi-desktop/shared";

export { type ComposerFileReference } from "./model";

let composerFileReferenceSequence = 0;

const CODE_FILE_PATTERN =
  /\.(cjs|css|go|java|js|json|jsx|kt|mjs|php|py|rb|rs|sh|sql|svelte|swift|toml|ts|tsx|vue|ya?ml)$/i;
const ARCHIVE_FILE_PATTERN = /\.(7z|bz2|gz|jar|rar|tar|zip)$/i;
const SHEET_FILE_PATTERN = /\.(csv|ods|xls|xlsx)$/i;
const AUDIO_FILE_PATTERN = /\.(flac|m4a|mp3|ogg|wav|webm)$/i;
const VIDEO_FILE_PATTERN = /\.(avi|mkv|m4v|mov|mp4|webm)$/i;

/** Paste/scratch files keep absolute paths; `@` entries are workspace-relative. */
export function isPersistedScratchReference(path: string): boolean {
  return path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
}

export function isImageFilePath(path: string): boolean {
  return /\.(avif|bmp|gif|heic|jpe?g|png|tiff?|webp)$/i.test(path);
}

export function formatDroppedDirectoryPath(path: string): string {
  const normalized = path.replace(/[\\/]+$/, "");
  const formatted = formatFileInsert(normalized, "dir");
  // `formatFileInsert` leaves a spaced directory quote open for interactive
  // @ completion. A completed native drop needs a closed token so mixed drops
  // can separate the directory from the following file chip.
  return /\s/.test(normalized) ? `${formatted}"` : formatted;
}

export function createFileReference(
  path: string,
  preferredName?: string,
  sessionId = "",
  metadata?: {
    size?: number;
    localReference?: string;
    kind?: ComposerFileReference["kind"];
    mimeType?: string;
    token?: string;
    lineRange?: FileLineRange;
    plugin?: ComposerPluginPart;
  },
): ComposerFileReference {
  composerFileReferenceSequence += 1;
  return {
    id: `composer-file-${composerFileReferenceSequence}`,
    sessionId,
    path,
    // Catalog and plugin labels are not filenames.
    name:
      isPluginMark(metadata) || metadata?.kind === "session" || metadata?.kind === "agent" || metadata?.kind === "skill"
        ? (preferredName ?? "")
        : fileReferenceLabel(path, preferredName),
    kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),
    ...(metadata?.size !== undefined ? { size: metadata.size } : {}),
    ...(metadata?.localReference ? { localReference: metadata.localReference } : {}),
    ...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),
    ...(metadata?.token ? { token: metadata.token } : {}),
    ...(metadata?.lineRange ? { lineRange: metadata.lineRange } : {}),
    ...(metadata?.plugin ? { plugin: metadata.plugin } : {}),
  };
}

/** A chip a plugin put in the draft that is text, not a file: a mark or the fold. */
export function isPluginMark(reference: { plugin?: ComposerPluginPart } | undefined): boolean {
  const kind = reference?.plugin?.kind;
  return kind === "mark" || kind === "fold";
}

const CHIP_TOKEN_BASE = 0xe000;
const CHIP_TOKEN_END = 0xf8ff;
let chipTokenSequence = 0;

export function nextChipToken(): string {
  const range = CHIP_TOKEN_END - CHIP_TOKEN_BASE + 1;
  chipTokenSequence = (chipTokenSequence + 1) % range;
  return String.fromCodePoint(CHIP_TOKEN_BASE + chipTokenSequence);
}

export function isChipTokenChar(char: string): boolean {
  if (char.length !== 1) return false;
  const code = char.codePointAt(0) ?? 0;
  return code >= CHIP_TOKEN_BASE && code <= CHIP_TOKEN_END;
}

function isChipElement(node: Node): boolean {
  return (
    node.nodeType === Node.ELEMENT_NODE &&
    (node as HTMLElement).classList.contains("composer-chip")
  );
}

/**
 * Placeholder break that keeps an empty last line laid out and caretable.
 * Chromium drops the last break of a block — a trailing "\n" and a trailing
 * `<br>` both end the line above and add none of their own — so a draft that ends
 * with a newline paints one extra break after it. That break belongs to the
 * layout, not to the draft: every read, index and caret path counts it as zero
 * characters. Because it holds no text it cannot be selected, copied or typed,
 * and it never merges into a neighbouring text node.
 */
const TAIL_PLACEHOLDER = "data-composer-tail";

function isTailPlaceholder(node: Node): boolean {
  return (
    node.nodeType === Node.ELEMENT_NODE &&
    (node as HTMLElement).tagName === "BR" &&
    (node as HTMLElement).hasAttribute(TAIL_PLACEHOLDER)
  );
}

function createTailPlaceholder(): HTMLBRElement {
  const br = document.createElement("br");
  br.setAttribute(TAIL_PLACEHOLDER, "");
  return br;
}

/** Paint the line box an empty last line needs, without adding a character. */
function paintTailPlaceholder(el: HTMLElement, value: string): void {
  if (value.endsWith("\n")) el.appendChild(createTailPlaceholder());
}

/**
 * One native edit for an end-of-draft break: the real break plus the layout
 * placeholder. Chromium records it as a single undo step, so undo and redo take
 * the new line and its caret together.
 */
export function tailBreakFragment(): string {
  return `<br><br ${TAIL_PLACEHOLDER}>`;
}

/** Rendered length of a node in draft-string characters (chip = 1 char). */
function editorNodeLength(node: Node): number {
  if (isTailPlaceholder(node)) return 0;
  if (node.nodeType === Node.TEXT_NODE) return (node.nodeValue ?? "").length;
  if (isChipElement(node)) return 1;
  if (node.nodeType === Node.ELEMENT_NODE) {
    const element = node as HTMLElement;
    if (element.tagName === "BR") return 1;
    let total = 0;
    for (const child of Array.from(node.childNodes)) total += editorNodeLength(child);
    return total;
  }
  return 0;
}

/** Read the editable's DOM back into the plain draft string. */
export function readEditorValue(el: HTMLElement): string {
  let out = "";
  const walk = (node: Node, blockStart: boolean): void => {
    if (node.nodeType === Node.TEXT_NODE) {
      out += node.nodeValue ?? "";
      return;
    }
    if (node.nodeType !== Node.ELEMENT_NODE) return;
    const element = node as HTMLElement;
    if (isTailPlaceholder(element)) return;
    if (isChipElement(element)) {
      const token = element.dataset.token ?? "";
      out += isChipTokenChar(token) ? token : "";
      return;
    }
    if (element.tagName === "BR") {
      out += "\n";
      return;
    }
    if (
      element !== el &&
      (element.tagName === "DIV" || element.tagName === "P")
    ) {
      // Native undo can reintroduce block wrappers; normalize them back
      // to newline-separated text so the value round-trips.
      if (!blockStart && out.length > 0 && !out.endsWith("\n")) out += "\n";
      for (const child of Array.from(element.childNodes)) walk(child, out.length === 0);
      return;
    }
    for (const child of Array.from(element.childNodes)) walk(child, blockStart && out.length === 0);
  };
  for (const child of Array.from(el.childNodes)) walk(child, true);
  return out;
}

/** Map a DOM point inside the editable to a draft-string index. */
export function editorIndexAt(
  el: HTMLElement,
  node: Node,
  offset: number,
): number {
  try {
    const range = document.createRange();
    range.selectNodeContents(el);
    range.setEnd(node, offset);
    const fragment = range.cloneContents();
    let total = 0;
    const walk = (parent: DocumentFragment | HTMLElement): void => {
      for (const child of Array.from(parent.childNodes)) {
        if (isTailPlaceholder(child)) continue;
        if (child.nodeType === Node.TEXT_NODE) {
          total += (child.nodeValue ?? "").length;
        } else if (isChipElement(child) || (child as HTMLElement).tagName === "BR") {
          total += 1;
        } else if (child.nodeType === Node.ELEMENT_NODE) {
          walk(child as HTMLElement);
        }
      }
    };
    walk(fragment);
    return total;
  } catch {
    return 0;
  }
}

/** Ordered [start, end] draft-string indices covered by the selection. */
export function editorSelectionRange(el: HTMLElement): { start: number; end: number } {
  const selection = window.getSelection();
  if (!selection || selection.rangeCount === 0) {
    const end = readEditorValue(el).length;
    return { start: end, end };
  }
  const range = selection.getRangeAt(0);
  if (!el.contains(range.startContainer) || !el.contains(range.endContainer)) {
    const end = readEditorValue(el).length;
    return { start: end, end };
  }
  const a = editorIndexAt(el, range.startContainer, range.startOffset);
  const b = editorIndexAt(el, range.endContainer, range.endOffset);
  return { start: Math.min(a, b), end: Math.max(a, b) };
}

/** Draft-string index → DOM caret point. */
function editorCaretPoint(el: HTMLElement, target: number): { node: Node; offset: number } {
  let remaining = target;
  let point: { node: Node; offset: number } | null = null;
  const descend = (parent: Node): boolean => {
    const children = Array.from(parent.childNodes);
    for (let index = 0; index < children.length; index += 1) {
      const child = children[index];
      if (isTailPlaceholder(child)) {
        // The draft ends before the placeholder, so the end-of-draft caret sits
        // at the start of the empty line that placeholder lays out.
        if (point === null && remaining <= 0) {
          point = { node: parent, offset: index };
          return true;
        }
        continue;
      }
      const length = editorNodeLength(child);
      if (child.nodeType === Node.TEXT_NODE) {
        if (point === null && remaining <= length) {
          point = { node: child, offset: remaining };
          return true;
        }
        remaining -= length;
      } else if (isChipElement(child) || (child as HTMLElement).tagName === "BR") {
        if (point === null && remaining <= 1) {
          point = { node: parent, offset: remaining === 0 ? index : index + 1 };
          return true;
        }
        remaining -= 1;
      } else if (child.nodeType === Node.ELEMENT_NODE && descend(child)) {
        return true;
      }
    }
    return false;
  };
  descend(el);
  if (point) return point;
  return { node: el, offset: el.childNodes.length };
}

export function setEditorCaret(el: HTMLElement, index: number): void {
  const point = editorCaretPoint(el, Math.max(0, index));
  const selection = window.getSelection();
  if (!selection) return;
  const maxOffset =
    point.node.nodeType === Node.TEXT_NODE
      ? (point.node.nodeValue ?? "").length
      : point.node.childNodes.length;
  const range = document.createRange();
  range.setStart(point.node, Math.min(point.offset, maxOffset));
  range.collapse(true);
  selection.removeAllRanges();
  selection.addRange(range);
}

/**
 * Keep the empty last line laid out and caretable. Chromium drops the last break
 * of a block, so a draft that ends with a newline paints one extra break after it
 * and counts that break as zero characters everywhere; that keeps the line count,
 * the draft string and its indices unchanged, without a character that could be
 * selected or copied. Text typed into the empty line lands before the placeholder,
 * and after text a final BR is inert but may still anchor native undo.
 */
export function syncTailPlaceholder(el: HTMLElement): void {
  const placeholders = Array.from(
    el.querySelectorAll<HTMLBRElement>(`br[${TAIL_PLACEHOLDER}]`),
  );
  if (readEditorValue(el).endsWith("\n")) {
    const placeholder = placeholders[0] ?? createTailPlaceholder();
    // A native edit can leave text after the placeholder while the line is still
    // empty; the placeholder stays the last node so the line keeps its box.
    if (el.lastChild !== placeholder) el.appendChild(placeholder);
    for (const extra of placeholders.slice(1)) extra.remove();
    return;
  }
  // A final BR after text does not paint another line. Keep its identity:
  // Chromium may need this exact sibling to undo deletion of the preceding LF.
  for (const placeholder of placeholders) {
    if (placeholder !== el.lastChild) placeholder.remove();
  }
}

/** One glyph per file family on attachment chips, as inline SVG strings. */
const CHIP_ICON_SVG: Record<string, string> = {
  dir: '<path d="M3 7V5a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/><path d="M3 9h18"/>',
  image:
    '<rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
  code: '<path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="M14.5 4 9.5 20"/>',
  archive:
    '<rect width="20" height="5" x="2" y="3" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>',
  sheet:
    '<path d="M12 3v18"/><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M3 15h18"/>',
  audio:
    '<path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/>',
  video:
    '<path d="m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5"/><rect x="2" y="6" width="14" height="12" rx="2"/>',
  file: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/>',
  session: '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
  x: '<path d="M18 6 6 18"/><path d="m6 6 12 12"/>',
  plugin:
    '<path d="M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z"/>',
  agent:
    '<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2"/><path d="M20 14h2"/><path d="M15 13v2"/><path d="M9 13v2"/>',
  skill: '<path d="M12 7c-2-2-6-3-10-2v14c4-1 8 0 10 2 2-2 6-3 10-2V5c-4-1-8 0-10 2Zm0 0v14"/>',
  fold: '<rect width="14" height="14" x="8" y="8" rx="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
};

function chipIconKey(reference: ComposerFileReference): string {
  if (reference.plugin?.kind === "mark") return "plugin";
  if (reference.plugin?.kind === "fold") return "fold";
  if (reference.kind === "session") return "session";
  if (reference.kind === "agent" || reference.kind === "skill") return reference.kind;
  if (reference.kind === "directory") return "dir";
  if (reference.lineRange) return "file";
  const mime = reference.mimeType ?? "";
  if (reference.kind === "image" || mime.startsWith("image/")) return "image";
  const name = reference.name;
  if (CODE_FILE_PATTERN.test(name) || /javascript|typescript|json|python/i.test(mime)) {
    return "code";
  }
  if (ARCHIVE_FILE_PATTERN.test(name) || /zip|compressed|tar$/i.test(mime)) return "archive";
  if (SHEET_FILE_PATTERN.test(name) || /csv|spreadsheet/i.test(mime)) return "sheet";
  if (AUDIO_FILE_PATTERN.test(name) || mime.startsWith("audio/")) return "audio";
  if (VIDEO_FILE_PATTERN.test(name) || mime.startsWith("video/")) return "video";
  return "file";
}

function chipSvg(key: string, size = 13): string {
  return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${CHIP_ICON_SVG[key] ?? CHIP_ICON_SVG.file}</svg>`;
}

export function isEditableTextReference(reference: ComposerFileReference): boolean {
  if (reference.localReference || reference.lineRange) return false;
  if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent" || reference.kind === "skill") return false;
  return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}

/** Build the atomic inline chip element for one attachment reference. */
function buildChipElement(
  reference: ComposerFileReference,
  token: string,
  removeLabel: string,
  onRemove: (token: string) => void,
  onExpandText: (token: string) => void,
  onOpenImage: (token: string) => void,
  onOpenSession: (token: string) => void,
): HTMLElement {
  const chip = document.createElement("span");
  chip.className = "composer-chip";
  chip.contentEditable = "false";
  chip.dataset.token = token;
  // A mark names the plugin that put it there where a file names its path.
  const origin = isPluginMark(reference)
    ? (reference.plugin?.pluginId ?? "")
    : composerMentionText(reference) ?? reference.path;
  if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;
  if (reference.kind === "agent") chip.dataset.agent = reference.path;
  if (reference.kind === "skill") chip.dataset.skill = reference.path;
  chip.title = origin;
  // An image keeps the compact chip and opens its preview, a session chip opens
  // that conversation, and only plain text expands into editable draft text.
  const image = !reference.localReference && chipIconKey(reference) === "image";
  if (image) chip.dataset.image = "";
  const session = reference.kind === "session";
  if (session) chip.dataset.sessionId = reference.path;
  const editableText = !image && !session && isEditableTextReference(reference);
  const activate = editableText
    ? () => onExpandText(token)
    : image
      ? () => onOpenImage(token)
      : session
        ? () => onOpenSession(token)
        : undefined;
  chip.setAttribute("role", activate ? "button" : "listitem");
  const label = reference.lineRange ? fileLineLabel(reference.name, reference.lineRange) : reference.name;
  chip.setAttribute("aria-label", `${label} — ${origin}`);
  if (activate) {
    chip.tabIndex = 0;
    // Only a text reference expands into editable text; an image chip opens
    // its preview and a session chip opens that conversation instead.
    chip.dataset.action = editableText
      ? "expand-text-reference"
      : image
        ? "open-image-preview"
        : "open-session-reference";
    chip.addEventListener("click", activate);
    chip.addEventListener("keydown", (event) => {
      if (event.target !== chip) return;
      if (event.key !== "Enter" && event.key !== " ") return;
      event.preventDefault();
      event.stopPropagation();
      activate();
    });
  }

  const icon = document.createElement("span");
  icon.className = "composer-chip-icon";
  icon.innerHTML = chipSvg(chipIconKey(reference), 13);

  const nameSpan = document.createElement("span");
  nameSpan.className = "composer-chip-name";
  nameSpan.textContent = label;
  if (reference.localReference && reference.size !== undefined) {
    const unit = Math.min(3, Math.floor(Math.log2(Math.max(1, reference.size)) / 10));
    const size = reference.size / 1024 ** unit;
    nameSpan.textContent += ` · ${Number(size.toFixed(1))} ${["B", "KiB", "MiB", "GiB"][unit]}`;
    chip.title += ` (${reference.size} B)`;
    chip.setAttribute("aria-label", `${reference.name} — ${chip.title}`);
  }

  const remove = document.createElement("button");
  remove.type = "button";
  remove.className = "composer-chip-remove";
  remove.title = removeLabel;
  remove.setAttribute("aria-label", removeLabel);
  remove.innerHTML = chipSvg("x", 11);
  // Swallow the mousedown so removing a chip never moves the editable caret.
  remove.addEventListener("mousedown", (event) => event.preventDefault());
  remove.addEventListener("keydown", (event) => {
    // Keep native button activation, without bubbling Enter into send.
    if (event.key === "Enter" || event.key === " ") event.stopPropagation();
  });
  remove.addEventListener("click", (event) => {
    event.stopPropagation();
    onRemove(token);
  });

  chip.append(icon, nameSpan, remove);
  return chip;
}

/** Paint the contenteditable from the draft string. */
export function paintEditorValue(
  el: HTMLElement,
  value: string,
  referenceByToken: Map<string, ComposerFileReference>,
  removeLabelFor: (reference: ComposerFileReference) => string,
  onRemove: (token: string) => void,
  onExpandText: (token: string) => void,
  onOpenImage: (token: string) => void,
  onOpenSession: (token: string) => void,
): void {
  el.replaceChildren();
  let textBuffer = "";
  const flush = () => {
    if (textBuffer) {
      el.appendChild(document.createTextNode(textBuffer));
      textBuffer = "";
    }
  };
  for (const char of Array.from(value)) {
    if (isChipTokenChar(char)) {
      const reference = referenceByToken.get(char);
      if (reference) {
        flush();
        el.appendChild(
          buildChipElement(
            reference,
            char,
            removeLabelFor(reference),
            onRemove,
            onExpandText,
            onOpenImage,
            onOpenSession,
          ),
        );
        continue;
      }
      // A private-use code point with no chip behind it is user text (for
      // example a Nerd Font glyph pasted from a terminal); keep it verbatim.
    }
    if (char === "\n") {
      flush();
      el.appendChild(document.createElement("br"));
      continue;
    }
    textBuffer += char;
  }
  flush();
  if (el.childNodes.length === 0) {
    // Chromium needs at least one node for reliable caret placement.
    el.appendChild(document.createTextNode(""));
  }
  paintTailPlaceholder(el, value);
}

export function clipboardFiles(data: DataTransfer): File[] {
  const files = Array.from(data.files);
  if (files.length === 0) {
    for (const item of Array.from(data.items)) {
      if (item.kind !== "file") continue;
      const file = item.getAsFile();
      if (file) files.push(file);
    }
  }
  return files;
}

/** Word may copy text plus a synthesized image of the same selection. Keep
 * that text editable, but preserve explicit native files and image-only paste. */
export function preferClipboardText(
  text: string,
  files: readonly File[],
  resolveNativePath: (file: File) => string | null,
): boolean {
  return (
    text.trim().length > 0 &&
    files.length > 0 &&
    files.every((file) =>
      file.type.toLowerCase().startsWith("image/") && !resolveNativePath(file),
    )
  );
}

/** Clipboard text arrives with CRLF/CR; the draft model stores LF only. */
export function normalizeClipboardLineEndings(text: string): string {
  return text.replace(/\r\n?/g, "\n");
}

/** Keep native undo while inserting multiline text into the editor's Text/BR
 * model. insertText creates block wrappers whose offsets differ from the draft. */
export function insertClipboardText(editor: HTMLElement, text: string): boolean {
  if (!/[\r\n]/.test(text)) return document.execCommand("insertText", false, text);
  const { start } = editorSelectionRange(editor);
  const normalized = normalizeClipboardLineEndings(text);
  const escaped = document.createElement("div");
  escaped.textContent = normalized;
  // Only escaped plain text and our own line breaks enter insertHTML; clipboard
  // HTML, attributes, links, and scripts are never accepted.
  const inserted = document.execCommand(
    "insertHTML",
    false,
    escaped.innerHTML.replace(/\n/g, "<br>"),
  );
  // Chromium can leave the caret before a final BR in an otherwise empty
  // editor. Use the same draft offsets as chip insertion without changing undo.
  if (inserted) setEditorCaret(editor, start + normalized.length);
  return inserted;
}