Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

2.2 KB
Raw Blame
import type { DeviceListItem } from '@lobechat/types';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';

import { getManagedDeviceStatus, managedStatusLabelKey } from './managedDeviceStatus';

/**
 * A device's presence as one line β€” "Online Β· Connected 5 minutes ago" or
 * "Last connected 2 days ago". Shared by the device card footer and the
 * conversation Overview, so both describe the same machine the same way.
 *
 * Online reads the gateway's live `connectedAt` from `channels[0]` β€” the
 * newest connection, since the pool is sorted newest-first in
 * `deviceGateway.queryDeviceList`. That is the same channel
 * `sortDevicesByActivity` ranks a row by, so the label always explains the
 * row's position.
 *
 * Offline can only report `lastSeen`, which is stamped on register β€” and
 * every client registers right before opening its WS (`gatewayConnectionSrv`,
 * CLI `registerDevice`) β€” so it means "last CONNECTED", not "last active".
 *
 * A single connection drops the "1 connection" count β€” it is the common case
 * and would truncate a narrow line.
 *
 * A row restored from the persisted list (`onlineUnknown`) has no channels by
 * construction, so it reads as "checking" rather than as offline.
 *
 * A managed cloud device reports its phase instead when the connection does
 * not explain it: a sleeping one says it wakes on demand rather than showing
 * when it last connected.
 */
export const useDeviceActivityText = (device: DeviceListItem) => {
  const { t } = useTranslation('setting');
  const channels = device.channels ?? [];

  const managedStatus = getManagedDeviceStatus(device);
  if (managedStatus === 'sleeping') return t('devices.managed.status.sleepingHint');
  if (managedStatus) return t(managedStatusLabelKey[managedStatus]);

  if (device.onlineUnknown) return t('devices.status.checking');

  if (channels.length === 0)
    return t('devices.lastSeen', { time: dayjs(device.lastSeen).fromNow() });

  const status =
    channels.length > 1
      ? t('devices.status.onlineConnections', { count: channels.length })
      : t('devices.status.online');

  return `${status} Β· ${t('devices.channel.connected', {
    time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
  })}`;
};