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。

12.3 KB
Raw Blame
/**
 * 队列状态横幅(消息流末尾,作为消息列表 footer 随内容滚动)。
 *
 * 待发送的**气泡**不在这里 —— 它们是消息流的一等渲染项(`pending_send`,见
 * `pendingSendItems.ts` / `PendingSendBubble.tsx`)。原先气泡挂在 footer,消息回流时要跨
 * footer↔data 搬家,位置会从「footer 落点」跳到「列表末项」,空会话时还被撑满高度的居中
 * 同步占位顶到屏幕中间,用户看到的是「气泡在中间 → 消失 → 在底部重新出现」。
 *
 * 留在 footer 的只有**整组队列的状态横幅**:队列错误(可重试 / 清除)、凭证切换等待、
 * 停止确认中、队列已暂停(可继续)。它们描述的是队列整体而非某一条消息,没有身份连续性
 * 问题,留在 footer 最自然。
 */
import { AgentErrorDetails } from './AgentErrorDetails';
import { ErrorNotice, ErrorNoticeAction } from '@/components/ErrorNotice';
import { ReadableHistoryRecovery } from './ReadableHistoryRecovery';
import { useTranslation } from 'react-i18next';
import {
  ActivityIndicator,
  Pressable,
  StyleSheet,
  View,
  type StyleProp,
  type ViewStyle,
} from 'react-native';
import type { ReactNode } from 'react';
import { Text } from '@/components/AppText';
import { Pause, Play } from 'lucide-react-native';
import { describeAgentAuthError } from '@/device-link/remoteStatus';
import type { InputProjection } from '@/session/types';
import type { ErrorDiagnosisSource } from '@/session/errorDiagnosisPrompt';
import { inputProjectionErrorI18nKey } from '@/session/inputProjectionError';
import { describeNonRetryableAgentError, localizeAgentError, localizeUnclassifiedAgentError, requiresAgentErrorConfigurationChange } from '@/session/agentErrorI18n';
import {
  fontWeight,
  iconSize,
  iconStroke,
  lineHeight,
  useTheme,
  useThemedStyles,
  type ThemeColors,
} from '@/theme';
import { radius, spacing, typeScale } from '@/theme/tokens';

export interface InlineQueueSectionProps {
  onRecoverHistory?: () => void;
  projection: InputProjection;
  sessionSource?: string | null;
  busy?: boolean;
  readOnlyReason?: string | null;
  onResume(): void;
  onRetryError(): void;
  /** 无重发记录时,沿用隐藏续跑指令;有记录仍优先按原记录重试。 */
  onContinueAfterError?(): void;
  onClearError(): void;
  /** 取消账号限额重置后的自动继续(只在投影带 usageLimitWait 时出现)。 */
  onCancelUsageLimitWait?(): void;
  /** 展开详情后的「诊断」:上层带着错误与出错任务去新任务里排查。 */
  onDiagnose?(error: ErrorDiagnosisSource): void;
}

export function InlineQueueSection({
  onRecoverHistory,
  projection,
  sessionSource,
  busy,
  readOnlyReason,
  onResume,
  onRetryError,
  onContinueAfterError,
  onClearError,
  onCancelUsageLimitWait,
  onDiagnose,
}: InlineQueueSectionProps) {
  const styles = useThemedStyles(makeStyles);
  const { colors } = useTheme();
  const { t, i18n } = useTranslation();

  const hasBanner = !!projection.error
    || !!projection.credentialSwitchWait
    || projection.queueAbortPending
    || projection.queuePaused;
  if (!hasBanner) return null;

  const controlsDisabled = busy || !!readOnlyReason;
  const errorDisabledReason = readOnlyReason
    || (busy ? t('message.queuePresentation.row.busy') : null);
  // Keep token-based retries on their existing path; hidden continuation uses
  // the same exclusions as the persisted-tail continuation action.
  const retryable = !requiresAgentErrorConfigurationChange(projection.error ?? '')
    && (!!projection.errorRetryText || describeNonRetryableAgentError(projection.error ?? '') === null);
  const retryDisabledReason = errorDisabledReason
    || (!projection.errorRetryText && !onContinueAfterError ? t('message.queue.noRetryContent') : null);
  const localizedAgentError = localizeAgentError(
    projection.errorReason,
    projection.toolLoop ?? null,
  );
  const projectionErrorKey = projection.error
    ? inputProjectionErrorI18nKey(projection.error)
    : null;
  const projectionError = projection.error
    ? localizedAgentError
      ?? (projectionErrorKey
        ? t(projectionErrorKey)
        : (describeAgentAuthError(projection.error) ?? localizeUnclassifiedAgentError(projection.error, sessionSource)))
    : null;

  const usageLimitResumeAt = projection.error && projection.usageLimitWait
    ? formatUsageLimitResumeAt(projection.usageLimitWait.resumeAt, i18n.resolvedLanguage || i18n.language)
    : null;

  return (
    <View style={styles.container} testID="queue.inline.section">
      {projection.error ? (
        <ErrorNotice
          message={projectionError ?? ''}
          testID="queue.inline.error"
          description={onRecoverHistory ? t('session.tail.readableHistoryRecoveryDescription') : undefined}
          onDismiss={onClearError}
          dismissLabel={t('session.tail.dismissNotice')}
          dismissTestID="queue.inline.clearErrorButton"
          dismissDisabled={!!errorDisabledReason}
          dismissBusy={busy}
          dismissHint={errorDisabledReason ?? undefined}
        >
          <AgentErrorDetails message={projection.error} onDiagnose={onDiagnose
            ? () => onDiagnose({
              message: projectionError ?? '',
              details: projection.error ?? '',
              reason: projection.errorReason,
            })
            : undefined} actions={<>
            {retryable ? <ErrorNoticeAction
              primary
              disabled={!!retryDisabledReason}
              busy={busy}
              hint={retryDisabledReason ?? undefined}
              label={t('message.queue.retrySend')}
              onPress={projection.errorRetryText ? onRetryError : (onContinueAfterError ?? onRetryError)}
              testID="queue.inline.retryButton"
            /> : null}
            {onRecoverHistory ? <ReadableHistoryRecovery onRecover={onRecoverHistory} busy={busy} disabled={controlsDisabled} /> : null}
          </>} />
          {retryable && retryDisabledReason ? (
            <Text style={styles.disabledHint} testID="queue.inline.errorDisabledReason">
              {retryDisabledReason}
            </Text>
          ) : null}
          {usageLimitResumeAt ? (
            // 额度重置后自动继续(桌面端执行);等待期间重试 / 清除照常可用。
            <View style={styles.errorActions} testID="queue.inline.usageLimitWait">
              <Text style={styles.disabledHint}>
                {t('message.queue.usageLimitAutoContinueAt', { time: usageLimitResumeAt })}
              </Text>
              {onCancelUsageLimitWait ? (
                <ActionPill
                  busy={busy}
                  disabled={!!errorDisabledReason}
                  disabledReason={errorDisabledReason}
                  label={t('message.queue.usageLimitAutoContinueCancel')}
                  onPress={onCancelUsageLimitWait}
                  testID="queue.inline.cancelUsageLimitWaitButton"
                />
              ) : null}
            </View>
          ) : null}
        </ErrorNotice>
      ) : null}

      {projection.credentialSwitchWait ? (
        <View style={styles.banner} testID="queue.inline.credentialSwitchWaitBanner">
          <ActivityIndicator color={colors.textTertiary} size="small" />
          <Text style={styles.bannerText}>{t('message.queue.credentialSwitchWait')}</Text>
        </View>
      ) : null}

      {projection.queueAbortPending ? (
        <View style={styles.banner} testID="queue.inline.abortBanner">
          <ActivityIndicator color={colors.textTertiary} size="small" />
          <Text style={styles.bannerText}>{t('message.queue.aborting')}</Text>
        </View>
      ) : projection.queuePaused ? (
        <View style={styles.banner} testID="queue.inline.pausedBanner">
          <Pause color={colors.textTertiary} size={iconSize.sm} strokeWidth={iconStroke.regular} />
          <Text style={styles.bannerText}>{t('message.queue.paused')}</Text>
          <QueueTouchButton
            accessibilityLabel={t('message.queue.resumeSendQueue')}
            busy={busy}
            disabled={controlsDisabled}
            disabledReason={readOnlyReason}
            onPress={onResume}
            style={styles.resumePill}
            testID="queue.inline.resumeButton"
          >
            <Play color={colors.ctaText} fill={colors.ctaText} size={iconSize.xs} strokeWidth={iconStroke.regular} />
            <Text style={styles.resumePillText}>{t('message.queue.resume')}</Text>
          </QueueTouchButton>
        </View>
      ) : null}
    </View>
  );
}

/** 同一天只显示时刻,跨天带日期(与桌面横幅同口径)。 */
function formatUsageLimitResumeAt(resumeAt: number, language: string): string | null {
  if (!Number.isFinite(resumeAt)) return null;
  const date = new Date(resumeAt);
  const sameDay = date.toDateString() === new Date().toDateString();
  return new Intl.DateTimeFormat(
    language,
    sameDay
      ? { hour: '2-digit', minute: '2-digit' }
      : { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' },
  ).format(date);
}

function ActionPill({
  busy,
  disabled,
  disabledReason,
  label,
  onPress,
  testID,
}: {
  busy?: boolean;
  disabled?: boolean;
  disabledReason?: string | null;
  label: string;
  onPress(): void;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  return (
    <QueueTouchButton
      accessibilityLabel={label}
      busy={busy}
      disabled={disabled}
      disabledReason={disabledReason}
      onPress={onPress}
      style={styles.actionPill}
      testID={testID}
    >
      <Text style={styles.actionPillText}>{label}</Text>
    </QueueTouchButton>
  );
}

function QueueTouchButton({
  accessibilityLabel,
  busy = false,
  children,
  disabled = false,
  disabledReason,
  onPress,
  style,
  testID,
}: {
  accessibilityLabel: string;
  busy?: boolean;
  children: ReactNode;
  disabled?: boolean;
  disabledReason?: string | null;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
  testID?: string;
}) {
  const styles = useThemedStyles(makeStyles);
  const interactionDisabled = disabled || !onPress;
  return (
    <Pressable
      accessibilityHint={disabledReason ?? undefined}
      accessibilityLabel={accessibilityLabel}
      accessibilityRole="button"
      accessibilityState={{ busy: busy || undefined, disabled: interactionDisabled }}
      disabled={interactionDisabled}
      onPress={interactionDisabled ? undefined : onPress}
      style={({ pressed }) => [
        style,
        pressed && styles.pressed,
        interactionDisabled && styles.disabled,
      ]}
      testID={testID}
    >
      {children}
    </Pressable>
  );
}

const makeStyles = (colors: ThemeColors) =>
  StyleSheet.create({
    container: { gap: spacing.sm, paddingTop: spacing.sm, width: '100%' },
    banner: {
      alignItems: 'center',
      backgroundColor: colors.surfaceElevated,
      borderColor: colors.border,
      borderRadius: radius.container,
      borderWidth: StyleSheet.hairlineWidth,
      flexDirection: 'row',
      gap: spacing.sm,
      paddingHorizontal: spacing.md,
      paddingVertical: spacing.sm,
    },
    bannerText: {
      color: colors.textSecondary,
      flex: 1,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
      minWidth: 0,
    },
    resumePill: {
      alignItems: 'center',
      backgroundColor: colors.cta,
      borderRadius: radius.pill,
      flexDirection: 'row',
      gap: 4,
      justifyContent: 'center',
      minHeight: 30,
      paddingHorizontal: spacing.md,
    },
    resumePillText: {
      color: colors.ctaText,
      fontSize: typeScale.caption,
      lineHeight: lineHeight.caption,
      fontWeight: fontWeight.medium,
    },
    disabledHint: {
      color: colors.textSecondary,
      fontSize: typeScale.footnote,
      lineHeight: lineHeight.caption,
    },
    errorActions: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
    actionPill: {
      alignItems: 'center',
      backgroundColor: colors.surfaceElevated,
      borderColor: colors.border,
      borderRadius: radius.pill,
      borderWidth: StyleSheet.hairlineWidth,
      flexDirection: 'row',
      gap: 6,
      justifyContent: 'center',
      minHeight: 36,
      paddingHorizontal: spacing.md,
    },
    actionPillText: {
      color: colors.textPrimary,
      fontSize: typeScale.caption,
      lineHeight: lineHeight.caption,
      fontWeight: fontWeight.medium,
    },
    pressed: { opacity: 0.72 },
    disabled: { opacity: 0.42 },
  });