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。

7.4 KB
Raw Blame
import { beforeAll, describe, expect, it } from 'vitest';
import { DeviceLinkError } from '@cindy/device-link';
import {
  connectionRecoverySyncRetryDelayMs,
  connectionIssueHint,
  connectionIssueTitle,
  describeRemoteComposerBlockingError,
  describeRemoteError,
  formatRemoteError,
  humanizeRemoteError,
  isAutoRecoveringRemoteError,
  isSessionRunningRemoteError,
  relayStatusHint,
  relayStatusLabel,
} from '@/device-link/remoteStatus';
import { i18n } from '@/i18n';

beforeAll(async () => {
  await i18n.changeLanguage('zh-CN');
});

describe('remoteStatus', () => {
  // A switch refusal reaches mobile inside the device-link IPC_ERROR envelope.
  // Verify the real alert/toast formatter, which differs from chat rendering.
  it('localizes nested Harness errors without exposing the technical fallback', async () => {
    const previousLanguage = i18n.language;
    try {
      for (const locale of ['zh-CN', 'zh-TW', 'en', 'ja', 'ko']) {
        await i18n.changeLanguage(locale);
        const error = new DeviceLinkError('IPC_ERROR' as never, '[SSH_HARNESS_SWITCH_UNSUPPORTED] SSH diagnostic');
        expect(humanizeRemoteError(error)).toBe(i18n.t('session.remoteError.SSH_HARNESS_SWITCH_UNSUPPORTED'));
        expect(formatRemoteError(error)).toContain('SSH diagnostic');
      }
    } finally {
      await i18n.changeLanguage(previousLanguage);
    }
  });
  it('backs repeated connection recovery syncs off and caps the delay', () => {
    expect([0, 1, 2, 3, 4, 5, 6].map(connectionRecoverySyncRetryDelayMs))
      .toEqual([900, 1_800, 3_600, 7_200, 14_400, 28_800, 30_000]);
    expect(connectionRecoverySyncRetryDelayMs(20)).toBe(30_000);
  });

  it('labels relay status', () => {
    expect(relayStatusLabel('online')).toBe('Relay 已连接');
    expect(relayStatusLabel('connecting')).toBe('正在连接 Relay');
    expect(relayStatusLabel('stopped')).toBe('Relay 未连接');
  });

  it('renders deterministic sync hints', () => {
    expect(relayStatusHint('online', new Date(2026, 0, 1, 3, 4, 5).getTime())).toBe('上次同步 03:04:05');
    expect(relayStatusHint('connecting', null)).toContain('自动重新订阅');
  });

  it('maps common remote errors to actionable copy', () => {
    expect(describeRemoteError('[REMOTE_DISABLED] disabled')).toContain('关闭允许远程控制');
    expect(describeRemoteError("[CHANNEL_NOT_ALLOWED] channel 'x'")).toContain('版本不支持');
    expect(describeRemoteError('[ACCESS_REVOKED] revoked')).toContain('撤销手机访问权限');
    expect(describeRemoteError('[NOT_CONNECTED] offline')).toBe(i18n.t('session.screen.networkReconnecting'));
    expect(describeRemoteError('unknown failure')).toBe(i18n.t('deviceLink.remoteError.unclassified'));
    expect(describeRemoteError('[NOT_FOUND] Session does not exist')).toBe(i18n.t('deviceLink.remoteError.notFound'));
    expect(describeRemoteError('REMOTE_WORKDIR_NOT_FOUND missing folder')).not.toBe(i18n.t('deviceLink.remoteError.notFound'));
  });

  it('preserves structured remote error codes for banner classification', () => {
    const text = formatRemoteError(new DeviceLinkError('ACCESS_REVOKED', 'access revoked by target device'));
    expect(text).toBe('[ACCESS_REVOKED] access revoked by target device');
    expect(describeRemoteError(text)).toContain('撤销手机访问权限');

    expect(formatRemoteError(Object.assign(new Error('remote disabled'), { code: 'REMOTE_DISABLED' }))).toBe(
      '[REMOTE_DISABLED] remote disabled',
    );
    expect(formatRemoteError(new Error('[NOT_CONNECTED] offline'))).toBe('[NOT_CONNECTED] offline');
  });

  it('recognizes a host refusal because the task is still running', () => {
    // 被控端 handler 抛 `[SESSION_RUNNING] ...`,经隧道到手机时外层 code 是 IPC_ERROR。
    expect(isSessionRunningRemoteError(
      new DeviceLinkError('IPC_ERROR' as never, '[SESSION_RUNNING] Session s1 is running a turn'),
    )).toBe(true);
    expect(isSessionRunningRemoteError(
      Object.assign(new Error('Session s1 has background activity'), { code: 'SESSION_RUNNING' }),
    )).toBe(true);
    expect(isSessionRunningRemoteError(
      new DeviceLinkError('IPC_ERROR' as never, '[NOT_FOUND] Message 不存在或不可删除'),
    )).toBe(false);
    expect(isSessionRunningRemoteError(new DeviceLinkError('NOT_CONNECTED', 'offline'))).toBe(false);
  });

  it('keeps the composer writable for automatic recovery, but blocks deterministic failures', () => {
    for (const error of [
      '[NOT_CONNECTED] offline',
      '[DEVICE_OFFLINE] target unavailable',
      '[LINK_NOT_OPEN] reopening',
      '[INVOKE_TIMEOUT] timed out',
      '[DEVICE_UNRESPONSIVE] circuit open',
      '[SESSION_REFERENCE_OFFLINE] target unavailable',
      '[REMOTE_OPTIMISTIC_SESSION_STATE_UNAVAILABLE] dedupe state unavailable',
    ]) {
      expect(isAutoRecoveringRemoteError(error), error).toBe(true);
      expect(describeRemoteComposerBlockingError(error), error).toBeNull();
    }

    const deliveryUnknown = new DeviceLinkError('NOT_CONNECTED', 'ack may be lost');
    deliveryUnknown.inFlight = true;
    expect(isAutoRecoveringRemoteError(deliveryUnknown)).toBe(true);

    expect(describeRemoteComposerBlockingError('[ACCESS_REVOKED] revoked'))
      .toContain('撤销手机访问权限');
    expect(describeRemoteComposerBlockingError('[REMOTE_DISABLED] disabled'))
      .toContain('关闭允许远程控制');
    expect(describeRemoteComposerBlockingError("[CHANNEL_NOT_ALLOWED] channel 'x'"))
      .toContain('版本不支持');
    expect(describeRemoteComposerBlockingError(null)).toBeNull();
    expect(describeRemoteComposerBlockingError('unknown failure')).toBeNull();
    expect(describeRemoteComposerBlockingError('OUTBOX_STORAGE_INVALID')).toBeNull();
    expect(describeRemoteComposerBlockingError('[BAD_REQUEST] nope')).toBeNull();
  });

  it('localizes Stop connection recovery errors without dropping their structured classification', async () => {
    const previousLanguage = i18n.language;
    try {
      for (const locale of ['en', 'ja', 'ko', 'zh-TW'] as const) {
        await i18n.changeLanguage(locale);
        expect(describeRemoteError('[DEVICE_OFFLINE]')).toBe(i18n.t('session.menu.aiRenameOffline'));
        expect(describeRemoteError('[NOT_CONNECTED]')).toBe(i18n.t('session.screen.networkReconnecting'));
        expect(humanizeRemoteError(
          Object.assign(new Error('target unavailable'), { code: 'DEVICE_OFFLINE' }),
        )).toBe(i18n.t('session.menu.aiRenameOffline'));
        expect(humanizeRemoteError(
          Object.assign(new Error('relay reconnecting'), { code: 'NOT_CONNECTED' }),
        )).toBe(i18n.t('session.screen.networkReconnecting'));
      }
    } finally {
      await i18n.changeLanguage(previousLanguage);
    }
  });

  it('localizes every connection issue kind', async () => {
    const previousLanguage = i18n.language;
    try {
      await i18n.changeLanguage('en');
      expect(connectionIssueTitle('auth-failed')).toBe('Sign-in expired');
      expect(connectionIssueHint('replaced')).toContain('replaced elsewhere');
      expect(connectionIssueTitle('too-many-connections')).toBe('Too many connections');
      expect(connectionIssueHint('version-mismatch')).toContain('Update to the latest version');
      expect(connectionIssueTitle('unstable')).toBe('Connection keeps dropping');
      expect(connectionIssueTitle('device-removed')).toBe('Device removed');
      expect(connectionIssueHint('device-removed')).toContain('Sign out');
    } finally {
      await i18n.changeLanguage(previousLanguage);
    }
  });
});