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。

2.5 KB
Raw Blame
import { withoutBotHiddenLanes } from './botGroupLane';
import type { BotProfile } from './botStore';
import { deviceDisplayName } from '@/lib/deviceName';

/** Keep unnamed and identically named hosts distinguishable without changing routing IDs. */
export function botDeviceLabel(
  device: { deviceId: string; name: string },
  devices: readonly { deviceId: string; name: string }[],
): string {
  return deviceDisplayName(device.deviceId, device.name, devices);
}

function finiteTimestamp(value: unknown): number {
  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;
}

/** Recency used for roster ordering. A new profile may lead until another Bot speaks. */
export function botRosterActivityAt(bot: BotProfile): number {
  return Math.max(
    finiteTimestamp(bot.createdAt),
    finiteTimestamp(bot.lastMessageAt),
    // 群聊 / IM 群里的发言不把这位伙伴在伙伴列表里顶到前面。
    ...withoutBotHiddenLanes(bot.sessions).map((session) => finiteTimestamp(session.updatedAt)),
  );
}

export function sortBotRoster(bots: readonly BotProfile[]): BotProfile[] {
  return [...bots].sort((left, right) => {
    const leftPinned = finiteTimestamp(left.pinnedAt) > 0 ? 1 : 0;
    const rightPinned = finiteTimestamp(right.pinnedAt) > 0 ? 1 : 0;
    if (leftPinned !== rightPinned) return rightPinned - leftPinned;
    const activity = botRosterActivityAt(right) - botRosterActivityAt(left);
    return activity || left.id.localeCompare(right.id);
  });
}

export function filterBotRoster(
  bots: readonly BotProfile[],
  rawQuery: string,
): BotProfile[] {
  const query = rawQuery.trim().toLocaleLowerCase();
  if (!query) return [...bots];
  return bots.filter((bot) =>
    [bot.name, bot.description, ...bot.skills]
      .filter(Boolean)
      .some((value) => value.toLocaleLowerCase().includes(query)),
  );
}

export function partitionBotRoster(
  bots: readonly BotProfile[],
  input: { query: string; showHidden: boolean },
): {
  visible: BotProfile[];
  hidden: BotProfile[];
  showHiddenSection: boolean;
  showHiddenRows: boolean;
} {
  const sorted = sortBotRoster(bots);
  const visible = filterBotRoster(
    sorted.filter((bot) => !bot.hiddenAt),
    input.query,
  );
  const hidden = filterBotRoster(
    sorted.filter((bot) => !!bot.hiddenAt),
    input.query,
  );
  const searching = input.query.trim().length > 0;
  return {
    visible,
    hidden,
    showHiddenSection: hidden.length > 0,
    showHiddenRows: input.showHidden || searching,
  };
}