Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

14.2 KB
Raw Blame
/**
 * GhostCommandDecoration — 意识指令的输入框「确认胶囊」。
 *
 * 消息以 `$画图 ...` 开头且指令词命中一段**已唤醒**的意识时,把指令词渲染成
 * 带意识头像的胶囊、触发符渲染层隐藏(样式见 globals.css `.ghost-cmd-pill` /
 * `.ghost-cmd-sigil`),给用户一个"意识已确定接单"的即时反馈;没命中(没这个
 * 指令 / 意识沉睡 / 位置不对)保持普通文字、触发符照常显示。纯 ProseMirror decoration——doc 里仍是纯文本 `$指令`,不改
 * 序列化、不建 chip(见 ChatInput insertSlashCommand 的"不建 chip"设计决策),
 * 发送链路零影响(规则 10)。
 *
 * 判定与发送期严格同源(规则 9 确定性):
 * - 匹配器复用 ghostCommand.ts 的 findGhostByCommand(启用态 + 指令词大小写
 *   折叠),胶囊亮 ⇔ 发送时 expandGhostCommand 会追加硬指令,两者永不漂移。
 * - 位置语义对齐 serializeEditorContent + COMMAND_RE:序列化后 `.trim()`,
 *   所以允许前导空白/空段落;`$` 前若有 chip(序列化成 `@...` 非空白前缀)
 *   或首个非空白字符不是触发符(含全角变体)则不亮;指令词后必须是空白 /
 *   hardBreak / 段落边界(序列化为 `\n`),紧贴 chip 视为 run 未断,不亮。
 *
 * 意识清单不在 plugin 里查(listSync 是同步 IPC,不进 keystroke 热路径):
 * ChatInput 读取当前设备的插件清单,变更时用 setGhostCommandRoster 推进来。
 */
import { Extension, type Editor } from '@tiptap/core';
import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';
import { Decoration, DecorationSet, type EditorView } from '@tiptap/pm/view';
import type { Node as PMNode } from '@tiptap/pm/model';

import {
  findGhostByCommand,
  findGhostByCommandIncludingDisabled,
  ghostCommandTokenLength,
  parseGhostCommandToken,
} from '@/cindy-brain/ghostCommand';
import type { GhostCommandSource } from '../../../shared/ghostComposer';
import { listGhostsByCommand } from '../../../shared/pluginIdentity';

const PLUGIN_KEY = new PluginKey<GhostCommandPluginState>('ghostCommandDecoration');
const META_KEY = 'ghostCommandDecoration';
const SOURCE_LABELS_META_KEY = 'ghostCommandSourceLabels';

/** Localized 团队共享 label; supplied by ChatInput so a locale change re-renders. */
export interface GhostSourceLabels {
  team: string;
}

interface GhostCommandPluginState {
  ghosts: GhostCommandSource[];
  sourceLabels: GhostSourceLabels | null;
  decorations: DecorationSet;
}

/** 触发符字符集——与 ChatInput 的 GHOST_SIGIL_CHARS / COMMAND_RE 同一套。 */
const SIGILS = new Set(['$', '$', '¥', '¥']);

/**
 * 头像 data URL 白名单形状:只接受 base64 图片,其它一律回退幽灵图标。
 * 值要进内联 style 的 `url("...")`,这里顺带排除了引号/括号/空白等能破坏
 * CSS 声明的字符(base64 字符集本身就不含它们)。
 */
const SAFE_ICON_DATA_URL_RE = /^data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=]+$/i;

export interface GhostCommandMatch {
  /** 触发符字符的 doc 位置。 */
  from: number;
  /** 指令词(不含 `/限定符`)结束后的 doc 位置。 */
  wordEnd: number;
  /** 整个指令(含限定符)结束后的 doc 位置(decoration 区间 [from, to))。 */
  to: number;
  ghost: GhostCommandSource;
}

/**
 * 在 doc 里找「已确认的意识指令」:定位首个非空白内容,校验触发符 + 指令词 +
 * 词尾边界,再经 findGhostByCommand 对已唤醒意识核身。任何一步不满足返回
 * null(渲染层绝不比发送层更乐观)。
 */
export function findGhostCommandMatch(
  doc: PMNode,
  ghosts: GhostCommandSource[],
  options: {
    includeDisabled?: boolean;
    /**
     * 仅供放置替换使用:裸指令词同时命中多个实例(唯一时插入的裸 `$draw`,之后又装了
     * 同名实例)仍识别为消息头指令,好让新选择替换它而不是叠在前面。胶囊与发送期
     * 判定不传此项,歧义时照旧不亮、不展开。
     */
    ambiguousBareToken?: boolean;
  } = {},
): GhostCommandMatch | null {
  if (ghosts.length === 0) return null;
  let paraPos = 0;
  for (let pi = 0; pi < doc.childCount; pi++) {
    const para = doc.child(pi);
    if (para.type.name !== 'paragraph') {
      // A command after a leading structured list is not a message-start
      // command. Let the placement path insert the selected command before
      // that list instead of replacing the later paragraph.
      return null;
    }
    let childPos = paraPos + 1; // 段落内容起点
    for (let ci = 0; ci < para.childCount; ci++) {
      const child = para.child(ci);
      // chip 序列化成 `@...`(非空白)——出现在指令前意味着序列化文本不再以
      // `$` 开头,COMMAND_RE 必不匹配。
      if (child.type.name === 'mentionChip') return null;
      if (child.isText) {
        const text = child.text ?? '';
        const first = /\S/.exec(text);
        if (first) {
          const i = first.index;
          if (!SIGILS.has(text[i])) return null;
          const token = parseGhostCommandToken(text.slice(i));
          // `$` 后直接空白 / 节点结束(相邻 text 节点会被 ProseMirror 合并,
          // 词不可能续在下个节点里)→ 无指令词。
          if (!token) return null;
          const after = i + 1 + ghostCommandTokenLength(token);
          if (after < text.length) {
            // 命中 32 字符上限但 run 未断 → 超长,发送期同样不匹配。
            if (!/\s/.test(text[after])) return null;
          } else {
            // 词到节点末尾:下一个 sibling 是 chip 时序列化紧贴续上非空白,
            // run 未断;hardBreak / 段落边界序列化为 `\n`,是合法词尾。
            const next = ci + 1 < para.childCount ? para.child(ci + 1) : null;
            if (next && next.type.name !== 'hardBreak') return null;
          }
          const ghost = (options.includeDisabled
            ? findGhostByCommandIncludingDisabled(ghosts, token.word, token.namespace)
            : findGhostByCommand(ghosts, token.word, token.namespace))
            ?? (options.ambiguousBareToken && token.namespace === null
              ? listGhostsByCommand(ghosts, token.word, !options.includeDisabled)[0]
              : undefined);
          if (!ghost) return null;
          return {
            from: childPos + i,
            wordEnd: childPos + i + 1 + token.word.length,
            to: childPos + after,
            ghost,
          };
        }
        // 全空白文本,继续找
      }
      // hardBreak / 其它 inline:序列化为空白,继续找
      childPos += child.nodeSize;
    }
    paraPos += para.nodeSize;
  }
  return null;
}

/**
 * 胶囊 span 的渲染属性(导出供测试锁契约):头像 data URL 过白名单才注入
 * `--ghost-cmd-icon`(globals.css 据此换掉默认幽灵图标),异形值静默回退。
 */
export function ghostPillAttrs(ghost: GhostCommandSource): Record<string, string> {
  const attrs: Record<string, string> = {
    class: 'ghost-cmd-pill',
    'data-ghost-cmd': ghost.manifest.id,
    // hover 报幕意识名(胶囊里只有 $指令,名字不占输入区空间)。
    title: ghost.manifest.name,
  };
  const icon = ghost.iconDataUrl;
  if (icon && SAFE_ICON_DATA_URL_RE.test(icon)) {
    attrs['data-ghost-cmd-icon'] = '';
    attrs.style = `--ghost-cmd-icon:url("${icon}")`;
  }
  return attrs;
}

/** 同名冲突时限定符的展示:收起 `/slug`、`/@root`,企业实例另挂「团队共享」标签。 */
export interface GhostQualifierDisplay {
  /** 企业实例为「团队共享」;root 实例为 null(只收起 `/@root`,不加标签)。 */
  label: string | null;
}

/**
 * 同一插件最多一份 root 加一份企业实例,按 namespace 即可区分:企业实例标
 * 「团队共享」,root 不加标签(默认即个人)。$ 菜单与输入框胶囊共用这一条判定;
 * 未冲突、标签未就绪,或当前项 / 任一同名实例的 namespace 未知(旧端、迁移中的
 * 旧安装)时返回 null,限定符照常显示:root 不带标签,只有在每个同名实例都能被
 * 区分时才可以收起 `/@root`,否则会和未知实例的裸指令一模一样。
 */
export function ghostQualifierDisplay(
  ghost: { namespace?: string | null; manifest: { command?: string } },
  qualified: boolean,
  labels: GhostSourceLabels | null,
  roster: readonly { namespace?: string | null; manifest: { command?: string } }[],
): GhostQualifierDisplay | null {
  if (!qualified || !labels || ghost.namespace === undefined) return null;
  const command = ghost.manifest.command?.toLowerCase();
  const unknownSibling = roster.some((other) =>
    other !== ghost &&
    other.namespace === undefined &&
    other.manifest.command?.toLowerCase() === command);
  if (unknownSibling) return null;
  return { label: ghost.namespace === null ? null : labels.team };
}

/** 由匹配结果构建胶囊 decoration(未命中 → 空集)。 */
function buildDecorations(
  doc: PMNode,
  ghosts: GhostCommandSource[],
  sourceLabels: GhostSourceLabels | null,
): DecorationSet {
  const match = findGhostCommandMatch(doc, ghosts);
  if (!match) return DecorationSet.empty;
  const decorations = [
    // 触发符($ 及全角变体)只做识别不做展示:胶囊头像已点明"这是意识",
    // 字符本身渲染层隐藏(doc 里仍在,编辑/发送/复制都不受影响;改坏词
    // 导致胶囊消失时它自然重新显形)。
    Decoration.inline(match.from, match.from + 1, { class: 'ghost-cmd-sigil' }),
  ];
  // 限定符是给发送期消歧的机器字符,与触发符一样只在渲染层隐藏。
  const display = ghostQualifierDisplay(match.ghost, match.to > match.wordEnd, sourceLabels, ghosts);
  if (display) {
    decorations.push(
      Decoration.inline(match.from + 1, match.wordEnd, {
        ...ghostPillAttrs(match.ghost),
        ...(display.label ? { 'data-ghost-cmd-origin': display.label } : {}),
      }),
      Decoration.inline(match.wordEnd, match.to, { class: 'ghost-cmd-qualifier' }),
    );
  } else {
    decorations.push(Decoration.inline(match.from + 1, match.to, ghostPillAttrs(match.ghost)));
  }
  return DecorationSet.create(doc, decorations);
}

/** 词尾后面紧跟的分隔空白(不含换行——换行在 doc 里是 hardBreak,不是文本)。 */
const TRAILING_SPACE_RE = /^[^\S\r\n]/;

/**
 * Backspace 整体删除:光标停在胶囊**外面**——也就是指令词后那个分隔空格之后
 * ——时,一次删掉 `$指令` 连同那个空格,而不是逐字符啃到胶囊碎掉。
 *
 * **胶囊内不接管,包括贴着词尾的位置**(`$画图| 一只猫`)。那里 caret 视觉上落在
 * 胶囊的右内边距里,是编辑位:用户是想改错字,不是想扔掉整条引用。同理光标落在
 * 词中间(`$画|图`)也不接管——改词的能力是当初不把指令做成 atom chip 的核心
 * 诉求,不能被这条捷径吃掉。没有尾随空格时(`$画图` 后直接是段落尾 / hardBreak)
 * 光标只可能停在胶囊内,因此一律走原生逐字删。
 *
 * 判定与胶囊严格同源——同一个 findGhostCommandMatch、同一份 plugin roster,
 * **胶囊亮才整体删**;没亮(未装/沉睡/拼错/位置不对)返回 false,原生逐字删的
 * 行为一字不变。
 *
 * 纯编辑侧行为:doc 里仍是纯文本,序列化与 expandGhostCommand 发送链路零改动。
 */
export function applyGhostCommandBackspace(view: EditorView): boolean {
  const { state } = view;
  if (!state.selection.empty) return false;
  const ghosts = PLUGIN_KEY.getState(state)?.ghosts;
  if (!ghosts || ghosts.length === 0) return false;
  const match = findGhostCommandMatch(state.doc, ghosts);
  if (!match) return false;

  // 面板选中时 ChatInput.insertSlashCommand 会补一个空格(`$cmd `):它既是
  // 「胶囊外」的唯一落脚点,也随引用一起收走,免得正文前留一个孤立空格。
  const after = state.doc.resolve(match.to).nodeAfter;
  if (!after?.isText || !TRAILING_SPACE_RE.test(after.text ?? '')) return false;
  if (state.selection.from !== match.to + 1) return false;

  view.dispatch(state.tr.delete(match.from, match.to + 1).scrollIntoView());
  return true;
}

/**
 * 推送最新意识清单(装/卸/唤醒/沉睡即时反映)。同引用去重——
 * 清单的 state 引用只在数据更新时变化。
 */
export function setGhostCommandRoster(
  editor: Editor | null,
  ghosts: GhostCommandSource[],
  sourceLabels: GhostSourceLabels | null = null,
): void {
  if (!editor || editor.isDestroyed) return;
  const current = PLUGIN_KEY.getState(editor.state);
  if (current && current.ghosts === ghosts && current.sourceLabels === sourceLabels) return;
  editor.view.dispatch(
    editor.state.tr.setMeta(META_KEY, ghosts).setMeta(SOURCE_LABELS_META_KEY, sourceLabels),
  );
}

/** 导出供测试直接在 ProseMirror state 层实例化(同 VoiceInputDraftDecoration)。 */
export function createGhostCommandPlugin(): Plugin<GhostCommandPluginState> {
  return new Plugin<GhostCommandPluginState>({
    key: PLUGIN_KEY,
    state: {
      init(_config, state: EditorState): GhostCommandPluginState {
        // 清单由 ChatInput 挂载后经 meta 推入,首帧空集(用户尚未输入)。
        return { ghosts: [], sourceLabels: null, decorations: buildDecorations(state.doc, [], null) };
      },
      apply(tr: Transaction, old: GhostCommandPluginState): GhostCommandPluginState {
        const roster = tr.getMeta(META_KEY) as GhostCommandSource[] | undefined;
        if (roster) {
          const labelsMeta = tr.getMeta(SOURCE_LABELS_META_KEY) as GhostSourceLabels | null | undefined;
          const sourceLabels = labelsMeta === undefined ? old.sourceLabels : labelsMeta;
          return { ghosts: roster, sourceLabels, decorations: buildDecorations(tr.doc, roster, sourceLabels) };
        }
        if (!tr.docChanged) return old;
        // 只扫消息头部的指令 run,输入量级下全量重算成本可忽略(同 CjkPunct)。
        return { ...old, decorations: buildDecorations(tr.doc, old.ghosts, old.sourceLabels) };
      },
    },
    props: {
      decorations(state) {
        return this.getState(state)?.decorations ?? DecorationSet.empty;
      },
    },
  });
}

export const GhostCommandDecoration = Extension.create({
  name: 'ghostCommandDecoration',

  addProseMirrorPlugins() {
    return [createGhostCommandPlugin()];
  },
});