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.

🐛 fix(device): order device lists by liveness, show last connected (#17296)

LiJian77edd7dba70c
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 0489f232f17..cf4f1bf5fa7 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -6,7 +6,7 @@ import type {
DeviceWorkspaceShare,
WorkingDirEntry,
} from '@lobechat/types';
-import { deriveWorktreePath, workingDirConfigSchema } from '@lobechat/types';
+import { deriveWorktreePath, sortDevicesByActivity, workingDirConfigSchema } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -869,10 +869,15 @@ export const deviceRouter = router({
return [...fromDb, ...ghosts];
};
- return [
+ // Ordered here rather than in SQL: `online` is the primary key and only the
+ // gateway knows it, so no per-pool `ORDER BY` can produce it — the two pools
+ // and their ghosts have to be merged first, then ordered as one list.
+ // Consumers (settings list, picker) filter this down to a single scope, and
+ // filtering preserves order, so one pass serves every surface.
+ return sortDevicesByActivity([
...buildItems(personalRows, personalOnline, 'personal'),
...buildItems(workspaceRows, workspaceOnline, 'workspace', hiddenWorkspaceIds),
- ];
+ ]);
}),
/**
diff --git a/apps/server/src/services/deviceGateway/__tests__/index.test.ts b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
index 72ae9232d9c..aab398654b6 100644
--- a/apps/server/src/services/deviceGateway/__tests__/index.test.ts
+++ b/apps/server/src/services/deviceGateway/__tests__/index.test.ts
@@ -139,6 +139,45 @@ describe('DeviceGateway', () => {
expect(mockClient.queryDeviceList).toHaveBeenCalledWith('user-1', undefined);
});
+ /**
+ * The gateway promises no channel order, but every consumer reads
+ * `channels[0]` as the device's current connection — the settings row's
+ * "Connected {time}", a ghost row's `lastSeen`/hostname/platform — while
+ * `sortDevicesByActivity` ranks by the freshest channel. Leave the pool raw
+ * and a multi-channel device gets ranked by one connection and labelled
+ * with another, which reads as a broken sort.
+ */
+ it('sorts channels newest-first so channels[0] is the current connection', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const older = Date.parse('2025-01-15T10:30:00Z');
+ const newest = Date.parse('2025-03-20T08:00:00Z');
+ const middle = Date.parse('2025-02-01T12:00:00Z');
+ mockClient.queryDeviceList.mockResolvedValue([
+ {
+ // Deliberately unordered, with the newest NOT first.
+ channels: [
+ { channel: 'cli', connectedAt: older, connectionId: 'conn-old' },
+ { channel: 'desktop', connectedAt: newest, connectionId: 'conn-new' },
+ { channel: 'mobile', connectedAt: middle, connectionId: 'conn-mid' },
+ ],
+ connectedAt: older,
+ deviceId: 'dev-1',
+ hostname: 'my-laptop',
+ platform: 'darwin',
+ },
+ ]);
+
+ const proxy = new DeviceGateway();
+ const result = await proxy.queryDeviceList('user-1');
+
+ expect(result[0]?.channels?.map((c) => c.connectionId)).toEqual([
+ 'conn-new',
+ 'conn-mid',
+ 'conn-old',
+ ]);
+ });
+
it('tolerates a legacy gateway response without channels', async () => {
mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index f0102342287..40f91e678dd 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -115,11 +115,23 @@ export class DeviceGateway {
return devices.map((d) => ({
// `channels` may be absent if the gateway worker deploy lags behind the
// server (separate Cloudflare deploy); tolerate the legacy flat shape.
- channels: (d.channels ?? []).map((c) => ({
- channel: c.channel,
- connectedAt: new Date(c.connectedAt).toISOString(),
- connectionId: c.connectionId,
- })),
+ //
+ // Sorted newest-first because every consumer reads `channels[0]` as
+ // "this device's current connection" — the settings row's
+ // "Connected {time}", a ghost row's `lastSeen`, its hostname/platform
+ // fallback — while `sortDevicesByActivity` ranks by the FRESHEST
+ // channel. The gateway promises no order, so leaving it raw lets a
+ // multi-channel device rank by one connection and get labelled with
+ // another. Normalising here (the single entry point both `listDevices`
+ // and `getScopedOnlineDevices` pull channels through) makes
+ // `channels[0]` mean the same thing everywhere.
+ channels: (d.channels ?? [])
+ .map((c) => ({
+ channel: c.channel,
+ connectedAt: new Date(c.connectedAt).toISOString(),
+ connectionId: c.connectionId,
+ }))
+ .sort((a, b) => Date.parse(b.connectedAt) - Date.parse(a.connectedAt)),
deviceId: d.deviceId,
hostname: d.hostname,
lastSeen: new Date(d.connectedAt).toISOString(),
diff --git a/apps/server/src/services/deviceGateway/scopedDevices.ts b/apps/server/src/services/deviceGateway/scopedDevices.ts
index a3539cbbd21..3fffc797347 100644
--- a/apps/server/src/services/deviceGateway/scopedDevices.ts
+++ b/apps/server/src/services/deviceGateway/scopedDevices.ts
@@ -1,5 +1,6 @@
import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
import { type LobeChatDatabase } from '@lobechat/database';
+import { sortDevicesByActivity } from '@lobechat/types';
import debug from 'debug';
import { DeviceModel } from '@/database/models/device';
@@ -91,5 +92,8 @@ export const getScopedOnlineDevices = async (
.filter((d) => !seen.has(d.deviceId) && !hidden.has(d.deviceId))
.map((d): DeviceAttachment => ({ ...d, friendlyName: null, scope }));
- return [...fromDb, ...transient];
+ // Online first, then most recently active — the same order the settings list
+ // and the run-target picker render, so "the first device" means the same
+ // thing to the model as it does to the user reading the picker.
+ return sortDevicesByActivity([...fromDb, ...transient]);
};
diff --git a/locales/ar/setting.json b/locales/ar/setting.json
index ab4962c5398..4dc721d9a4f 100644
--- a/locales/ar/setting.json
+++ b/locales/ar/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "قم بتوصيل جهازك الأول",
"devices.fallbackBadge": "هوية غير مستقرة",
"devices.fallbackTooltip": "لم يتمكن هذا الجهاز من التعرف عليه بواسطة معرف الجهاز، لذا قد يؤدي إعادة تثبيت التطبيق إلى إنشاء إدخال مكرر.",
- "devices.lastSeen": "آخر نشاط {{time}}",
+ "devices.lastSeen": "آخر اتصال {{time}}",
"devices.remove.confirm": "إزالة هذا الجهاز؟",
"devices.remove.confirmDesc": "سيتم فصل الجهاز عن حسابك. لن يتم تسجيل خروج الجهاز، ويمكنه إعادة التسجيل عند الاتصال التالي.",
"devices.remove.currentSessionWarning": "يتضمن ذلك الجهاز الذي تستخدمه الآن — إزالته ستؤدي إلى قطع الاتصال بجلسة العمل الحالية.",
diff --git a/locales/bg-BG/setting.json b/locales/bg-BG/setting.json
index 3086278aa80..d486607b502 100644
--- a/locales/bg-BG/setting.json
+++ b/locales/bg-BG/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Свържете първото си устройство",
"devices.fallbackBadge": "Нестабилна идентичност",
"devices.fallbackTooltip": "Това устройство не може да бъде идентифицирано чрез неговия машинен ID, така че преинсталирането на приложението може да създаде дублиран запис.",
- "devices.lastSeen": "Последно активно {{time}}",
+ "devices.lastSeen": "Последно свързване {{time}}",
"devices.remove.confirm": "Премахване на това устройство?",
"devices.remove.confirmDesc": "Това прекъсва връзката на устройството с вашия акаунт. Това не го изписва и може да се регистрира отново при следващо свързване.",
"devices.remove.currentSessionWarning": "Това включва устройството, което използвате в момента — премахването му ще прекъсне текущата ви сесия.",
diff --git a/locales/de-DE/setting.json b/locales/de-DE/setting.json
index 49c5fa38d02..719338dfe3b 100644
--- a/locales/de-DE/setting.json
+++ b/locales/de-DE/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Verbinden Sie Ihr erstes Gerät",
"devices.fallbackBadge": "Instabile Identität",
"devices.fallbackTooltip": "Dieses Gerät konnte nicht anhand seiner Maschinen-ID identifiziert werden, daher kann eine Neuinstallation der App einen doppelten Eintrag erstellen.",
- "devices.lastSeen": "Zuletzt aktiv {{time}}",
+ "devices.lastSeen": "Zuletzt verbunden {{time}}",
"devices.remove.confirm": "Dieses Gerät entfernen?",
"devices.remove.confirmDesc": "Dies trennt das Gerät von Ihrem Konto. Es wird nicht abgemeldet und kann sich beim nächsten Verbinden erneut registrieren.",
"devices.remove.currentSessionWarning": "Dies schließt das Gerät ein, das Sie gerade verwenden – wenn Sie es entfernen, wird Ihre aktuelle Sitzung getrennt.",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 6c48e257071..8c649185be9 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Connect your first device",
"devices.fallbackBadge": "Unstable identity",
"devices.fallbackTooltip": "This device couldn't be identified by its machine ID, so reinstalling the app may create a duplicate entry.",
- "devices.lastSeen": "Last active {{time}}",
+ "devices.lastSeen": "Last connected {{time}}",
"devices.remove.confirm": "Remove this device?",
"devices.remove.confirmDesc": "This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.",
"devices.remove.currentSessionWarning": "This includes the device you're using right now — removing it disconnects your current session.",
diff --git a/locales/es-ES/setting.json b/locales/es-ES/setting.json
index 517eb95faae..09b7f416886 100644
--- a/locales/es-ES/setting.json
+++ b/locales/es-ES/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Conecta tu primer dispositivo",
"devices.fallbackBadge": "Identidad inestable",
"devices.fallbackTooltip": "Este dispositivo no pudo ser identificado por su ID de máquina, por lo que reinstalar la aplicación puede crear una entrada duplicada.",
- "devices.lastSeen": "Última actividad {{time}}",
+ "devices.lastSeen": "Última conexión {{time}}",
"devices.remove.confirm": "¿Eliminar este dispositivo?",
"devices.remove.confirmDesc": "Esto desconecta el dispositivo de tu cuenta. No cierra la sesión del dispositivo, y puede registrarse nuevamente en la próxima conexión.",
"devices.remove.currentSessionWarning": "Esto incluye el dispositivo que estás utilizando ahora mismo; eliminarlo desconectará tu sesión actual.",
diff --git a/locales/fa-IR/setting.json b/locales/fa-IR/setting.json
index 297e5a65db0..3ad6b105fe5 100644
--- a/locales/fa-IR/setting.json
+++ b/locales/fa-IR/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "اولین دستگاه خود را متصل کنید",
"devices.fallbackBadge": "هویت ناپایدار",
"devices.fallbackTooltip": "این دستگاه با شناسه ماشین خود شناسایی نشد، بنابراین نصب مجدد برنامه ممکن است یک ورودی تکراری ایجاد کند.",
- "devices.lastSeen": "آخرین فعالیت {{time}}",
+ "devices.lastSeen": "آخرین اتصال {{time}}",
"devices.remove.confirm": "این دستگاه حذف شود؟",
"devices.remove.confirmDesc": "این دستگاه را از حساب شما قطع می‌کند. این دستگاه از حساب خارج نمی‌شود و می‌تواند در اتصال بعدی دوباره ثبت شود.",
"devices.remove.currentSessionWarning": "این شامل دستگاهی است که در حال حاضر از آن استفاده می‌کنید — حذف آن باعث قطع اتصال جلسه فعلی شما می‌شود.",
diff --git a/locales/fr-FR/setting.json b/locales/fr-FR/setting.json
index 1c43efb2423..b9a53d41b90 100644
--- a/locales/fr-FR/setting.json
+++ b/locales/fr-FR/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Connectez votre premier appareil",
"devices.fallbackBadge": "Identité instable",
"devices.fallbackTooltip": "Cet appareil n'a pas pu être identifié par son ID machine, donc la réinstallation de l'application peut créer une entrée en double.",
- "devices.lastSeen": "Dernière activité {{time}}",
+ "devices.lastSeen": "Dernière connexion {{time}}",
"devices.remove.confirm": "Supprimer cet appareil ?",
"devices.remove.confirmDesc": "Cela déconnecte l'appareil de votre compte. Cela ne déconnecte pas l'appareil, et il peut se réenregistrer lors de la prochaine connexion.",
"devices.remove.currentSessionWarning": "Cela inclut l'appareil que vous utilisez actuellement — le supprimer déconnectera votre session en cours.",
diff --git a/locales/it-IT/setting.json b/locales/it-IT/setting.json
index 6757bc4ccbc..fdff6755efd 100644
--- a/locales/it-IT/setting.json
+++ b/locales/it-IT/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Connetti il tuo primo dispositivo",
"devices.fallbackBadge": "Identità instabile",
"devices.fallbackTooltip": "Questo dispositivo non è stato identificato tramite il suo ID macchina, quindi reinstallare l'app potrebbe creare una voce duplicata.",
- "devices.lastSeen": "Ultima attività {{time}}",
+ "devices.lastSeen": "Ultima connessione {{time}}",
"devices.remove.confirm": "Rimuovere questo dispositivo?",
"devices.remove.confirmDesc": "Questo disconnette il dispositivo dal tuo account. Non effettua il logout del dispositivo, che può registrarsi nuovamente alla prossima connessione.",
"devices.remove.currentSessionWarning": "Questo include il dispositivo che stai utilizzando in questo momento — rimuoverlo disconnetterà la tua sessione corrente.",
diff --git a/locales/ja-JP/setting.json b/locales/ja-JP/setting.json
index b7d799165dd..4ab1dc7de10 100644
--- a/locales/ja-JP/setting.json
+++ b/locales/ja-JP/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "最初のデバイスを接続",
"devices.fallbackBadge": "不安定なアイデンティティ",
"devices.fallbackTooltip": "このデバイスはマシンIDで識別できなかったため、アプリを再インストールすると重複エントリが作成される可能性があります。",
- "devices.lastSeen": "最終アクティブ {{time}}",
+ "devices.lastSeen": "最終接続 {{time}}",
"devices.remove.confirm": "このデバイスを削除しますか?",
"devices.remove.confirmDesc": "このデバイスをアカウントから切断します。デバイスのサインアウトは行われず、次回接続時に再登録できます。",
"devices.remove.currentSessionWarning": "これには現在使用しているデバイスも含まれます。削除すると現在のセッションが切断されます。",
diff --git a/locales/ko-KR/setting.json b/locales/ko-KR/setting.json
index 426ca7d1520..7ee9d954e10 100644
--- a/locales/ko-KR/setting.json
+++ b/locales/ko-KR/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "첫 번째 장치를 연결하세요",
"devices.fallbackBadge": "불안정한 ID",
"devices.fallbackTooltip": "이 장치는 머신 ID로 식별할 수 없으므로 앱을 재설치하면 중복 항목이 생성될 수 있습니다.",
- "devices.lastSeen": "마지막 활동 {{time}}",
+ "devices.lastSeen": "마지막 연결 {{time}}",
"devices.remove.confirm": "이 장치를 제거하시겠습니까?",
"devices.remove.confirmDesc": "이 장치를 계정에서 연결 해제합니다. 장치에서 로그아웃하지 않으며 다음 연결 시 다시 등록할 수 있습니다.",
"devices.remove.currentSessionWarning": "현재 사용 중인 장치도 포함됩니다. 이를 제거하면 현재 세션이 연결 해제됩니다.",
diff --git a/locales/nl-NL/setting.json b/locales/nl-NL/setting.json
index a6c32e0d619..131052a393f 100644
--- a/locales/nl-NL/setting.json
+++ b/locales/nl-NL/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Verbind uw eerste apparaat",
"devices.fallbackBadge": "Onstabiele identiteit",
"devices.fallbackTooltip": "Dit apparaat kon niet worden geïdentificeerd via zijn machine-ID, dus het opnieuw installeren van de app kan een dubbele vermelding creëren.",
- "devices.lastSeen": "Laatst actief {{time}}",
+ "devices.lastSeen": "Laatst verbonden {{time}}",
"devices.remove.confirm": "Dit apparaat verwijderen?",
"devices.remove.confirmDesc": "Hiermee wordt het apparaat losgekoppeld van je account. Het logt het apparaat niet uit, en het kan zich opnieuw registreren bij de volgende verbinding.",
"devices.remove.currentSessionWarning": "Dit omvat het apparaat dat je momenteel gebruikt — het verwijderen verbreekt je huidige sessie.",
diff --git a/locales/pl-PL/setting.json b/locales/pl-PL/setting.json
index ae08493c05a..d65804a8830 100644
--- a/locales/pl-PL/setting.json
+++ b/locales/pl-PL/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Połącz swoje pierwsze urządzenie",
"devices.fallbackBadge": "Niestabilna tożsamość",
"devices.fallbackTooltip": "To urządzenie nie mogło zostać zidentyfikowane przez jego identyfikator maszyny, więc ponowna instalacja aplikacji może utworzyć duplikat wpisu.",
- "devices.lastSeen": "Ostatnia aktywność {{time}}",
+ "devices.lastSeen": "Ostatnie połączenie {{time}}",
"devices.remove.confirm": "Usunąć to urządzenie?",
"devices.remove.confirmDesc": "To rozłącza urządzenie z Twojego konta. Nie wylogowuje urządzenia, które może się ponownie zarejestrować przy następnym połączeniu.",
"devices.remove.currentSessionWarning": "Dotyczy to urządzenia, którego używasz w tej chwili — usunięcie go spowoduje rozłączenie bieżącej sesji.",
diff --git a/locales/pt-BR/setting.json b/locales/pt-BR/setting.json
index 6f9b21a069d..b85d166273b 100644
--- a/locales/pt-BR/setting.json
+++ b/locales/pt-BR/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Conecte seu primeiro dispositivo",
"devices.fallbackBadge": "Identidade instável",
"devices.fallbackTooltip": "Este dispositivo não pôde ser identificado pelo ID da máquina, então reinstalar o aplicativo pode criar uma entrada duplicada.",
- "devices.lastSeen": "Última atividade {{time}}",
+ "devices.lastSeen": "Última conexão {{time}}",
"devices.remove.confirm": "Remover este dispositivo?",
"devices.remove.confirmDesc": "Isso desconecta o dispositivo da sua conta. Não desconecta o dispositivo, e ele pode se registrar novamente na próxima conexão.",
"devices.remove.currentSessionWarning": "Isso inclui o dispositivo que você está usando agora — removê-lo desconectará sua sessão atual.",
diff --git a/locales/ru-RU/setting.json b/locales/ru-RU/setting.json
index 675dfc96d27..c1de187596c 100644
--- a/locales/ru-RU/setting.json
+++ b/locales/ru-RU/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Подключите ваше первое устройство",
"devices.fallbackBadge": "Нестабильная идентификация",
"devices.fallbackTooltip": "Это устройство не удалось идентифицировать по его ID машины, поэтому переустановка приложения может создать дублирующую запись.",
- "devices.lastSeen": "Последняя активность {{time}}",
+ "devices.lastSeen": "Последнее подключение {{time}}",
"devices.remove.confirm": "Удалить это устройство?",
"devices.remove.confirmDesc": "Это отключит устройство от вашей учетной записи. Оно не будет выходить из системы и сможет зарегистрироваться снова при следующем подключении.",
"devices.remove.currentSessionWarning": "Это включает устройство, которое вы используете прямо сейчас — его удаление завершит текущую сессию.",
diff --git a/locales/tr-TR/setting.json b/locales/tr-TR/setting.json
index cf81ccb1e05..fa3b3490e97 100644
--- a/locales/tr-TR/setting.json
+++ b/locales/tr-TR/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "İlk cihazınızı bağlayın",
"devices.fallbackBadge": "Kararsız kimlik",
"devices.fallbackTooltip": "Bu cihaz makine kimliğiyle tanımlanamadı, bu nedenle uygulamayı yeniden yüklemek bir kopya giriş oluşturabilir.",
- "devices.lastSeen": "Son aktif {{time}}",
+ "devices.lastSeen": "Son bağlantı {{time}}",
"devices.remove.confirm": "Bu cihazı kaldır?",
"devices.remove.confirmDesc": "Bu, cihazı hesabınızdan ayırır. Cihaz oturumu kapatmaz ve bir sonraki bağlantıda yeniden kaydolabilir.",
"devices.remove.currentSessionWarning": "Bu, şu anda kullandığınız cihazı da içeriyor — kaldırmak mevcut oturumunuzu sonlandırır.",
diff --git a/locales/vi-VN/setting.json b/locales/vi-VN/setting.json
index f7f8f01ec18..38f75a8210b 100644
--- a/locales/vi-VN/setting.json
+++ b/locales/vi-VN/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "Kết nối thiết bị đầu tiên của bạn",
"devices.fallbackBadge": "Danh tính không ổn định",
"devices.fallbackTooltip": "Thiết bị này không thể được nhận diện bằng ID máy, vì vậy việc cài đặt lại ứng dụng có thể tạo ra một mục trùng lặp.",
- "devices.lastSeen": "Hoạt động lần cuối {{time}}",
+ "devices.lastSeen": "Kết nối lần cuối {{time}}",
"devices.remove.confirm": "Xóa thiết bị này?",
"devices.remove.confirmDesc": "Điều này sẽ ngắt kết nối thiết bị khỏi tài khoản của bạn. Nó không đăng xuất thiết bị và có thể đăng ký lại khi kết nối lần sau.",
"devices.remove.currentSessionWarning": "Điều này bao gồm thiết bị bạn đang sử dụng ngay bây giờ — việc loại bỏ nó sẽ ngắt kết nối phiên hiện tại của bạn.",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 676edf1cabf..0ed8d96c424 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "连接你的第一台设备",
"devices.fallbackBadge": "身份不稳定",
"devices.fallbackTooltip": "未能通过机器 ID 识别此设备,重装应用可能会产生重复条目。",
- "devices.lastSeen": "最近活跃 {{time}}",
+ "devices.lastSeen": "最后连接于 {{time}}",
"devices.remove.confirm": "移除此设备?",
"devices.remove.confirmDesc": "这会断开设备与你账户的关联,但不会让设备登出,下次连接时它可重新注册。",
"devices.remove.currentSessionWarning": "其中包含你当前正在使用的设备,移除后会断开当前会话。",
diff --git a/locales/zh-TW/setting.json b/locales/zh-TW/setting.json
index d56f1a297f4..cec0909693e 100644
--- a/locales/zh-TW/setting.json
+++ b/locales/zh-TW/setting.json
@@ -349,7 +349,7 @@
"devices.empty.title": "連接您的第一個設備",
"devices.fallbackBadge": "不穩定的身份",
"devices.fallbackTooltip": "此裝置無法通過其機器 ID 識別,因此重新安裝應用程式可能會創建重複的條目。",
- "devices.lastSeen": "最後活躍 {{time}}",
+ "devices.lastSeen": "最後連接於 {{time}}",
"devices.remove.confirm": "移除此裝置?",
"devices.remove.confirmDesc": "這將使裝置與您的帳戶斷開連接。它不會登出該裝置,並且可以在下次連接時重新註冊。",
"devices.remove.currentSessionWarning": "這包括您現在正在使用的裝置——移除它將使您的當前會話斷開連接。",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 60aee22416e..f5500a3e7c3 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -430,7 +430,7 @@ export default {
'devices.fallbackBadge': 'Unstable identity',
'devices.fallbackTooltip':
"This device couldn't be identified by its machine ID, so reinstalling the app may create a duplicate entry.",
- 'devices.lastSeen': 'Last active {{time}}',
+ 'devices.lastSeen': 'Last connected {{time}}',
'devices.remove.confirm': 'Remove this device?',
'devices.remove.confirmDesc':
'This disconnects the device from your account. It does not sign the device out, and it can re-register on next connect.',
diff --git a/packages/types/src/device.test.ts b/packages/types/src/device.test.ts
index c45259385b9..178db401f96 100644
--- a/packages/types/src/device.test.ts
+++ b/packages/types/src/device.test.ts
@@ -1,8 +1,110 @@
import { describe, expect, expectTypeOf, it } from 'vitest';
import type { z } from 'zod';
-import type { WorkingDirConfig } from './device';
-import { workingDirConfigSchema } from './device';
+import type { DeviceActivityOrder, WorkingDirConfig } from './device';
+import { sortDevicesByActivity, workingDirConfigSchema } from './device';
+
+describe('sortDevicesByActivity', () => {
+ const device = (
+ over: Partial<DeviceActivityOrder> & { deviceId: string },
+ ): DeviceActivityOrder => ({
+ lastSeen: '2026-01-01T00:00:00.000Z',
+ online: false,
+ ...over,
+ });
+
+ /**
+ * The regression this ordering exists for: the picker disables offline rows,
+ * so an offline device sorted above an online one pushes the only *pickable*
+ * machine out of a viewport that caps at a few rows. `lastSeenAt` is stamped
+ * on register and never refreshed, so a box that reconnects on every boot
+ * reports a fresher timestamp than one holding a month-long session — recency
+ * must never be able to outrank liveness.
+ */
+ it('ranks an online device above an offline one that registered far more recently', () => {
+ const sorted = sortDevicesByActivity([
+ device({ deviceId: 'rebooted-vm', lastSeen: '2026-03-01T00:00:00.000Z' }),
+ device({
+ channels: [{ connectedAt: '2026-01-05T00:00:00.000Z' }],
+ deviceId: 'long-lived',
+ lastSeen: '2026-01-05T00:00:00.000Z',
+ online: true,
+ }),
+ ]);
+
+ expect(sorted.map((d) => d.deviceId)).toEqual(['long-lived', 'rebooted-vm']);
+ });
+
+ it('orders online devices by their newest live connection', () => {
+ const sorted = sortDevicesByActivity([
+ device({
+ channels: [{ connectedAt: '2026-01-01T00:00:00.000Z' }],
+ deviceId: 'stale',
+ online: true,
+ }),
+ device({
+ // Multiple live channels → the freshest one is the activity signal.
+ channels: [
+ { connectedAt: '2026-01-02T00:00:00.000Z' },
+ { connectedAt: '2026-06-01T00:00:00.000Z' },
+ ],
+ deviceId: 'fresh',
+ online: true,
+ }),
+ ]);
+
+ expect(sorted.map((d) => d.deviceId)).toEqual(['fresh', 'stale']);
+ });
+
+ it('orders offline devices by lastSeen', () => {
+ const sorted = sortDevicesByActivity([
+ device({ deviceId: 'older', lastSeen: '2026-01-01T00:00:00.000Z' }),
+ device({ deviceId: 'newer', lastSeen: '2026-05-01T00:00:00.000Z' }),
+ ]);
+
+ expect(sorted.map((d) => d.deviceId)).toEqual(['newer', 'older']);
+ });
+
+ /**
+ * These lists poll. Without a total order, two rows sharing a timestamp may
+ * swap places between refreshes — under the user's cursor, mid-click.
+ */
+ it('breaks timestamp ties by deviceId so repeated sorts are stable', () => {
+ const tied = [device({ deviceId: 'c' }), device({ deviceId: 'a' }), device({ deviceId: 'b' })];
+
+ expect(sortDevicesByActivity(tied).map((d) => d.deviceId)).toEqual(['a', 'b', 'c']);
+ // Re-sorting an already-sorted list must not reshuffle it.
+ expect(sortDevicesByActivity(sortDevicesByActivity(tied)).map((d) => d.deviceId)).toEqual([
+ 'a',
+ 'b',
+ 'c',
+ ]);
+ });
+
+ /**
+ * `online: true` with no channels is reachable — the runtime derives `online`
+ * as `!!live` and tolerates a gateway that omits `channels`. Such a row must
+ * still sort above every offline device rather than crash or sink.
+ */
+ it('keeps an online device with no channels in the online partition', () => {
+ const sorted = sortDevicesByActivity([
+ device({ deviceId: 'offline-recent', lastSeen: '2026-09-01T00:00:00.000Z' }),
+ device({ deviceId: 'online-legacy', lastSeen: '2026-01-01T00:00:00.000Z', online: true }),
+ ]);
+
+ expect(sorted.map((d) => d.deviceId)).toEqual(['online-legacy', 'offline-recent']);
+ });
+
+ it('does not mutate the input array', () => {
+ const input = [
+ device({ deviceId: 'b', online: true }),
+ device({ deviceId: 'a', online: true }),
+ ];
+ sortDevicesByActivity(input);
+
+ expect(input.map((d) => d.deviceId)).toEqual(['b', 'a']);
+ });
+});
describe('workingDirConfigSchema', () => {
/**
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 18d45221b2c..f7d3f4b5520 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -223,6 +223,70 @@ export interface DeviceChannel {
platform: string | null;
}
+/**
+ * The subset every device-listing shape shares — satisfied structurally by both
+ * `DeviceListItem` (settings list / run-target picker) and the runtime's
+ * `DeviceAttachment`, so one ordering serves every surface.
+ */
+export interface DeviceActivityOrder {
+ /** Absent on offline rows, and on a legacy gateway that omits the field. */
+ channels?: { connectedAt: string }[];
+ deviceId: string;
+ lastSeen: string;
+ online: boolean;
+}
+
+/**
+ * Most recent evidence the device was alive, as a timestamp.
+ *
+ * Online rows carry the gateway's live `connectedAt` — authoritative. Offline
+ * rows can only fall back to `lastSeen`, which today means "last REGISTERED",
+ * not "last alive": `devices.lastSeenAt` is stamped on register/enroll and
+ * never refreshed while a connection is held. A box that reconnects on every
+ * boot therefore reports a fresher `lastSeen` than one holding a month-long
+ * session. That staleness is contained by the `online` partition below, and
+ * fixing it needs a writer that stamps liveness — not a change here.
+ */
+const deviceActivityAt = (d: DeviceActivityOrder): number => {
+ // `online` with no channels is reachable: the runtime derives it as `!!live`
+ // and tolerates a gateway that omits `channels`. Fall through rather than
+ // assume a channel exists.
+ const connected = (d.online ? (d.channels ?? []) : [])
+ .map((c) => Date.parse(c.connectedAt))
+ .filter((t) => !Number.isNaN(t));
+ if (connected.length > 0) return Math.max(...connected);
+
+ const lastSeen = Date.parse(d.lastSeen);
+ return Number.isNaN(lastSeen) ? 0 : lastSeen;
+};
+
+/**
+ * Order for every device-listing surface: online first, then most recently
+ * active, then by id.
+ *
+ * `online` is a HARD partition rather than one signal among several — an
+ * offline device must never outrank an online one, however recently it was
+ * seen. The picker renders offline rows `disabled`, so an offline row sorted
+ * above an online one is pure noise pushing the only *pickable* machine out of
+ * a viewport that caps at a few rows.
+ *
+ * `deviceId` breaks ties last so the order is total and STABLE: these lists
+ * poll, and two rows sharing a timestamp must not swap places under the user's
+ * cursor between refreshes.
+ */
+export const compareDeviceByActivity = (a: DeviceActivityOrder, b: DeviceActivityOrder): number => {
+ if (a.online !== b.online) return a.online ? -1 : 1;
+
+ const diff = deviceActivityAt(b) - deviceActivityAt(a);
+ if (diff !== 0) return diff;
+
+ return a.deviceId.localeCompare(b.deviceId);
+};
+
+/** Non-mutating {@link compareDeviceByActivity} — callers pass server-built arrays. */
+export const sortDevicesByActivity = <T extends DeviceActivityOrder>(devices: T[]): T[] =>
+ [...devices].sort(compareDeviceByActivity);
+
/**
* Where a device sits relative to the caller:
* - `personal` — the caller's own machine (`devices.workspace_id IS NULL`).
diff --git a/src/features/DeviceManager/DeviceItem.tsx b/src/features/DeviceManager/DeviceItem.tsx
index 5133c63c269..546f1d9b76b 100644
--- a/src/features/DeviceManager/DeviceItem.tsx
+++ b/src/features/DeviceManager/DeviceItem.tsx
@@ -28,6 +28,14 @@ import { openShareDeviceModal } from './ShareDeviceModal';
import { useCanEditDevice } from './useCanEditDevice';
const styles = createStaticStyles(({ css }) => ({
+ // Liveness line. `flex: none` + no ellipsis: it is the shortest thing on the
+ // row and the reason the row is readable at a glance — a long cwd next to it
+ // must truncate itself rather than squeeze this out.
+ activity: css`
+ flex: none;
+ font-size: ${cssVar.fontSizeSM};
+ white-space: nowrap;
+ `,
// Code-font cwd line; truncates rather than wrapping so a deep path keeps the
// row at one line.
cwd: css`
@@ -53,6 +61,12 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillTertiary};
`,
+ metaDivider: css`
+ flex: none;
+ width: 1px;
+ height: 10px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
row: css`
cursor: pointer;
@@ -128,7 +142,22 @@ const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selecte
// Online when the device has at least one live connection in `device.channels`.
const channels = device.channels ?? [];
const online = channels.length > 0;
- const statusTooltip = online
+ // Rendered inline (not as a dot tooltip): "when was this machine last
+ // reachable" is the answer needed to pick between rows, and hover can't
+ // answer it for a whole list at once — nor at all on touch.
+ //
+ // 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 this 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". The copy says exactly that; it becomes a
+ // true last-active once a writer stamps liveness.
+ const activityText = online
? t('devices.channel.connected', {
time: dayjs(channels[0]?.connectedAt ?? device.lastSeen).fromNow(),
})
@@ -245,9 +274,7 @@ const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selecte
<Text ellipsis fontSize={15} weight={500}>
{displayName}
</Text>
- <Tooltip title={statusTooltip}>
- <span className={online ? styles.statusOnline : styles.statusOffline} />
- </Tooltip>
+ <span className={online ? styles.statusOnline : styles.statusOffline} />
{isCurrent && <Tag>{t('devices.currentBadge')}</Tag>}
{device.scope === 'workspace' && device.sharedFromPersonal && (
// Member-shared machine (vs directly enrolled infra) — mirrors the
@@ -272,14 +299,20 @@ const DeviceItem = memo<DeviceItemProps>(({ device, isCurrent, onSelect, selecte
</Tooltip>
)}
</Flexbox>
- {device.defaultCwd && (
- <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
- <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
- <Text className={styles.cwd} type={'secondary'}>
- {device.defaultCwd}
- </Text>
- </Flexbox>
- )}
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Text className={styles.activity} type={'secondary'}>
+ {activityText}
+ </Text>
+ {device.defaultCwd && (
+ <>
+ <span className={styles.metaDivider} />
+ <Icon icon={FolderIcon} size={12} style={{ color: cssVar.colorTextQuaternary }} />
+ <Text className={styles.cwd} type={'secondary'}>
+ {device.defaultCwd}
+ </Text>
+ </>
+ )}
+ </Flexbox>
</Flexbox>
<Flexbox horizontal align={'center'} gap={8} style={{ flex: 'none' }}>