Skip to content

Your lightweight open-source personal agent.

feat(remote): rename servers without interrupting host sessions

Xubin Ren719a5c3fcf51
diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py
index bec2d45c0..7c72f56d2 100644
--- a/nanobot/webui/remote_instances.py
+++ b/nanobot/webui/remote_instances.py
@@ -329,6 +329,21 @@ class RemoteInstances:
return {"id": key, **self.snapshot()}
if key not in profiles:
raise RemoteError("profile_not_found")
+ if action == "rename":
+ name = payload.get("name")
+ if (not isinstance(name, str) or not 1 <= len(name.strip()) <= 64
+ or any(ord(char) < 32 or ord(char) == 127 for char in name)):
+ raise RemoteError("invalid_name")
+ # Display metadata only: preserve live tunnels, origins and
+ # credentials. All verified grants for this instance share a name.
+ receipt = self.pairing.saved_receipt(profiles[key].pair_id) if profiles[key].pair_id else None
+ for saved_key, saved in profiles.items():
+ if saved_key == key or (receipt and saved.pair_id
+ and (other := self.pairing.saved_receipt(saved.pair_id))
+ and other.destination() == receipt.destination()):
+ saved.name = name.strip()
+ self._write(profiles)
+ return self.snapshot()
if action == "pair_route":
profile = profiles[key]
if not profile.pair_id:
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index 12e4acbce..14f9b609c 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -173,6 +173,7 @@ _WEBUI_MUTATION_PATHS = {
"remote.inspect": "/api/remote-instances/inspect",
"remote.pick_file": "/api/remote-instances/pick_file",
"remote.save": "/api/remote-instances/save",
+ "remote.rename": "/api/remote-instances/rename",
"remote.connect": "/api/remote-instances/connect",
"remote.disconnect": "/api/remote-instances/disconnect",
"remote.remove": "/api/remote-instances/remove",
diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py
index 4e80314ae..2defbbc2a 100644
--- a/tests/webui/test_remote_instances.py
+++ b/tests/webui/test_remote_instances.py
@@ -83,6 +83,41 @@ async def test_new_local_manager_has_new_view_identity_for_same_remote(manager,
assert "view_id" not in manager.path.read_text()
+async def test_rename_connected_profile_only_changes_display_name(manager, ssh):
+ key = await save(manager)
+ await manager.action("connect", {"id": key})
+ before = json.loads(manager.path.read_text())
+ live = manager.connections[key]
+ result = await manager.action("rename", {"id": key, "name": " 腾讯云 nanobot "})
+ assert result["profiles"][0]["name"] == "腾讯云 nanobot"
+ assert result["profiles"][0]["connected"] is True
+ before[key]["name"] = "腾讯云 nanobot"
+ assert json.loads(manager.path.read_text()) == before
+ assert RemoteInstances(manager.path.parent).snapshot()["profiles"][0]["name"] == "腾讯云 nanobot"
+ assert manager.connections[key] is live
+ ssh.tunnel.pause.assert_not_awaited()
+ ssh.tunnel.close.assert_not_awaited()
+ assert ssh.probe.await_count == 1
+
+
[email protected]("name", [None, 7, {}, "", " ", "a" * 65, "a\nb", "a\x00b", "a\x7fb"])
+async def test_rename_invalid_name_does_not_change_saved_profile(manager, name):
+ key = await save(manager)
+ before = manager.path.read_bytes()
+ with pytest.raises(RemoteError, match="invalid_name"):
+ await manager.action("rename", {"id": key, "name": name})
+ assert manager.path.read_bytes() == before
+
+
+async def test_rename_validates_id_and_does_not_merge_matching_names(manager):
+ first = await save(manager)
+ second = await save(manager, host="other-host")
+ await manager.action("rename", {"id": first, "name": "x" * 64})
+ assert manager._read()[second].name == "Team"
+ with pytest.raises(RemoteError, match="profile_not_found"):
+ await manager.action("rename", {"id": "missing", "name": "Team"})
+
+
async def test_unchanged_save_allows_retry_after_browser_load_failure(manager, ssh):
key = await save(manager)
await manager.action("connect", {"id": key})
diff --git a/tests/webui/test_remote_pairing.py b/tests/webui/test_remote_pairing.py
index 5b2f34279..fcc6a1c95 100644
--- a/tests/webui/test_remote_pairing.py
+++ b/tests/webui/test_remote_pairing.py
@@ -279,6 +279,30 @@ async def test_same_name_or_ip_never_groups_different_pairing_destinations(tmp_p
assert len({item["instance_id"] for item in result["profiles"]}) == 2
+async def test_rename_paired_instance_updates_only_verified_sibling_grants(tmp_path):
+ manager = RemoteInstances(tmp_path)
+ first = read_request((await manager.action("pair_start", {}))["command"].split()[-1])
+ original = receipt(first)
+ await manager.action("pair_finish", {"id": first.id, "code": seal(first, original)})
+ requests = [first]
+ for path in [original.config_path, "/srv/different/config.json"]:
+ request = read_request((await manager.action("pair_start", {}))["command"].split()[-1])
+ value = original.model_copy(update={"id": request.id, "ssh_key": request.ssh_key, "config_path": path})
+ await manager.action("pair_finish", {"id": request.id, "code": seal(request, value)})
+ requests.append(request)
+ before = manager._read()
+ receipts = {item.id: manager.pairing.path(item.id).joinpath("receipt").read_bytes() for item in requests}
+ live = SimpleNamespace(tunnel=SimpleNamespace(active=True), error="", gateway_id="live-session",
+ proxy=SimpleNamespace(pause=AsyncMock()))
+ manager.connections[first.id] = live
+ result = await manager.action("rename", {"id": requests[1].id, "name": "My cloud"})
+ assert [p["name"] for p in result["profiles"]] == ["My cloud", "My cloud", original.hostname]
+ for item in requests:
+ assert manager.pairing.path(item.id).joinpath("receipt").read_bytes() == receipts[item.id]
+ assert manager._read()[item.id].model_dump(exclude={"name"}) == before[item.id].model_dump(exclude={"name"})
+ live.proxy.pause.assert_not_awaited()
+
+
@pytest.mark.parametrize("healthy", [True, False])
async def test_repair_retains_route_and_reuses_only_a_healthy_existing_connection(tmp_path, monkeypatch, healthy):
manager = RemoteInstances(tmp_path)
diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsx
index a53d7b526..46308932f 100644
--- a/webui/src/components/remote/RemoteConnectionsPage.tsx
+++ b/webui/src/components/remote/RemoteConnectionsPage.tsx
@@ -39,6 +39,9 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
const [quickOpen, setQuickOpen] = useState(!!returnedPair);
const [pairRoute, setPairRoute] = useState("");
const [details, setDetails] = useState("");
+ const [renaming, setRenaming] = useState<RemoteProfile | null>(null);
+ const [name, setName] = useState("");
+ const [renameError, setRenameError] = useState("");
const [editing, setEditing] = useState(false);
const [savedId, setSavedId] = useState("");
const [busy, setBusy] = useState("");
@@ -60,6 +63,8 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
const operation = useRef(0);
const optionsId = useId();
const statusId = useId();
+ const nameId = useId();
+ const nameInput = useRef<HTMLInputElement>(null);
const refresh = connections?.refresh;
const page = useRef<HTMLDivElement>(null);
useEffect(() => { if (connections?.managing) page.current?.focus({ preventScroll: true }); }, [connections?.managing]);
@@ -228,6 +233,16 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
} catch (reason) { if (mounted.current) showError(reason); }
finally { if (mounted.current) setBusy(""); }
};
+ const rename = async () => {
+ if (!renaming || busy || !name.trim() || name.trim() === renaming.name) return;
+ setBusy("rename"); setRenameError("");
+ try {
+ await connections.rename(renaming.id, name.trim());
+ if (mounted.current) setRenaming(null);
+ } catch (reason) {
+ if (mounted.current) setRenameError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));
+ } finally { if (mounted.current) setBusy(""); }
+ };
const disconnect = async (id: string) => {
setBusy(id); setError("");
try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }
@@ -308,6 +323,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
onKeyDown={(event) => { editorTrigger.current = event.currentTarget; }}
aria-label={t("remote.manage", { name: profile.name })}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ <DropdownMenuItem onSelect={() => { setRenaming(profile); setName(profile.name); setRenameError(""); }}>{t("remote.rename.action")}</DropdownMenuItem>
{entries.length > 1 ? <DropdownMenuItem onSelect={() => setDetails(groupId)}>{t("remote.sameInstance.details")}</DropdownMenuItem> : connectionActions(profile)}
</DropdownMenuContent>
</DropdownMenu>
@@ -333,6 +349,31 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
</div>
</div>
+ <Dialog open={!!renaming} onOpenChange={(open) => { if (!open && !busy) setRenaming(null); }}>
+ <DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto" onOpenAutoFocus={(event) => {
+ event.preventDefault(); nameInput.current?.focus(); nameInput.current?.select();
+ }} onCloseAutoFocus={(event) => { event.preventDefault(); editorTrigger.current?.focus({ preventScroll: true }); }}>
+ <DialogHeader className="pr-5 text-left">
+ <DialogTitle>{t("remote.rename.title")}</DialogTitle>
+ <DialogDescription>{t("remote.rename.hint")}</DialogDescription>
+ </DialogHeader>
+ <form className="space-y-4" onSubmit={(event) => { event.preventDefault(); void rename(); }}>
+ <div className="space-y-2">
+ <label htmlFor={nameId} className="text-[13px] font-medium">{t("remote.rename.name")}</label>
+ <Input ref={nameInput} id={nameId} value={name} maxLength={64} required disabled={!!busy}
+ aria-invalid={!!renameError} aria-describedby={renameError ? `${nameId}-error` : undefined}
+ onChange={(event) => { setName(event.target.value); setRenameError(""); }} />
+ </div>
+ {renameError && <p id={`${nameId}-error`} role="alert" className="text-[13px] leading-5 text-foreground">{renameError}</p>}
+ <div className="flex justify-end gap-2">
+ <Button type="button" variant="ghost" disabled={!!busy} onClick={() => setRenaming(null)}>{t("common.cancel")}</Button>
+ <Button type="submit" disabled={!!busy || !name.trim() || name.trim() === renaming?.name} aria-busy={!!busy}>
+ {busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
+ </Button>
+ </div>
+ </form>
+ </DialogContent>
+ </Dialog>
<Dialog open={!!detailGroup} onOpenChange={(open) => { if (!open) setDetails(""); }}>
<DialogContent className="flex max-h-[85dvh] max-w-md flex-col overflow-hidden">
<DialogHeader className="pr-5 text-left"><DialogTitle>{t("remote.sameInstance.details")}</DialogTitle><DialogDescription>{t("remote.sameInstance.detailsHint")}</DialogDescription></DialogHeader>
diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx
index 914029c30..a161073ae 100644
--- a/webui/src/components/remote/RemoteInstances.tsx
+++ b/webui/src/components/remote/RemoteInstances.tsx
@@ -21,6 +21,7 @@ const RemoteContext = createContext<{
directory: RemoteDirectory | null;
directoryError: boolean;
refresh: () => Promise<RemoteDirectory>;
+ rename: (id: string, name: string) => Promise<void>;
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
disconnect: (id: string) => Promise<void>;
cancel: () => void;
@@ -138,7 +139,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
return <RemoteContext.Provider value={{ available, localActive: !selected, directory,
activeHostId: selected?.id || null, hostStates, managing, closeManagement: () => changeManagement(false), selectLocal,
openHostIds: frames.map((frame) => frame.connection.id),
- directoryError: hosts.directoryError, refresh: hosts.refresh, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
+ directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
<div className="flex h-full min-h-0 flex-col bg-background">
<div className="relative min-h-0 flex-1 overflow-hidden">
diff --git a/webui/src/components/remote/useHostSessions.ts b/webui/src/components/remote/useHostSessions.ts
index ef388f12c..192b10881 100644
--- a/webui/src/components/remote/useHostSessions.ts
+++ b/webui/src/components/remote/useHostSessions.ts
@@ -58,17 +58,44 @@ export function useHostSessions() {
publish();
}, [publish]);
const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
+ const applyDirectory = useCallback((next: RemoteDirectory) => {
+ setDirectory(next); setDirectoryError(false);
+ // Names are metadata, not a new host session. Keep iframe URLs, drafts,
+ // selection and connection state intact when this or another tab renames.
+ let changed = false;
+ for (const profile of next.profiles) {
+ const frame = cache.current.get(profile.id);
+ if (frame && frame.connection.name !== profile.name) {
+ frame.connection = { ...frame.connection, name: profile.name };
+ changed = true;
+ }
+ if (selectedRef.current?.id === profile.id && selectedRef.current.name !== profile.name) {
+ const value = { ...selectedRef.current, name: profile.name };
+ selectedRef.current = value; setSelected(value); rememberSelectedRemote(value);
+ }
+ if (pendingRef.current?.id === profile.id && pendingRef.current.name !== profile.name) {
+ setPendingSwitch({ id: profile.id, name: profile.name });
+ }
+ }
+ if (changed) publish();
+ }, [publish, setPendingSwitch]);
+ const rename = useCallback(async (id: string, name: string) => {
+ const next = await remoteAction<RemoteDirectory>(client, "rename", { id, name });
+ // Discard health reads begun before the save completed.
+ directoryGeneration.current += 1;
+ if (mounted.current) applyDirectory(next);
+ }, [applyDirectory, client]);
const refresh = useCallback(async () => {
const generation = ++directoryGeneration.current;
try {
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
- if (mounted.current && generation === directoryGeneration.current) { setDirectory(next); setDirectoryError(false); }
+ if (mounted.current && generation === directoryGeneration.current) applyDirectory(next);
return next;
} catch (reason) {
if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);
throw reason;
}
- }, [getToken]);
+ }, [applyDirectory, getToken]);
const connect = useCallback(async (id: string, stillWanted: () => boolean = () => true) => {
cancel();
@@ -120,7 +147,7 @@ export function useHostSessions() {
});
if (!ready) return;
}
- if (wanted()) select(connection);
+ if (wanted()) select(frame.connection);
} catch (reason) {
if (wanted()) {
setFailure({ id, code: reason instanceof Error ? reason.message : "unknown" });
@@ -193,7 +220,7 @@ export function useHostSessions() {
try {
const next = await readRemoteInstances(getToken());
if (cancelled || generation !== directoryGeneration.current) return;
- setDirectory(next); setDirectoryError(false);
+ applyDirectory(next);
for (const [id, frame] of cache.current) {
if (id === pendingRef.current?.id) continue;
const profile = next.profiles.find((profile) => profile.id === id);
@@ -230,7 +257,7 @@ export function useHostSessions() {
window.removeEventListener("pageshow", wake);
document.removeEventListener("visibilitychange", wake);
};
- }, [client, getToken, publish]);
- return { directory, directoryError, refresh, selected, recentIds, frames, pending,
+ }, [applyDirectory, client, getToken, publish]);
+ return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };
}
diff --git a/webui/src/components/remote/useSidebarHostBridge.ts b/webui/src/components/remote/useSidebarHostBridge.ts
index 81055b8ee..3c1fe44ac 100644
--- a/webui/src/components/remote/useSidebarHostBridge.ts
+++ b/webui/src/components/remote/useSidebarHostBridge.ts
@@ -69,9 +69,10 @@ export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | u
return () => window.removeEventListener("message", receive);
}, [initialize, nodes]);
useEffect(() => { setAnchor(null); }, [selectedId]);
+ const selectedName = frames.find((frame) => frame.connection.id === selectedId)?.connection.name;
useEffect(() => {
if (selectedId && peers.current.has(selectedId)) initialize(selectedId);
- }, [initialize, selectedId, activity.pendingName, activity.error]);
+ }, [initialize, selectedId, selectedName, activity.pendingName, activity.error]);
useEffect(() => {
for (const id of peers.current.keys()) if (!frames.some((frame) => frame.connection.id === id)) peers.current.delete(id);
}, [frames]);
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index 2284d22f9..ac41cf0a1 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Rename",
+ "title": "Rename server",
+ "name": "Name",
+ "hint": "A name for this connection. Your server and SSH settings won’t change."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Enter a name between 1 and 64 characters, without line breaks.",
"local_connection_unavailable": "Couldn't reach local nanobot on this computer. Keep it running and try again.",
"disconnected": "This shared connection was closed. Reconnect when you’re ready.",
"instance_changed": "This server connection changed. Reconnecting will reload its view; unsent drafts may be lost.",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 4fd1bdc70..78eedadd6 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Cambiar nombre",
+ "title": "Cambiar nombre del servidor",
+ "name": "Nombre",
+ "hint": "Un nombre para esta conexión. El servidor y la configuración SSH no cambiarán."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Introduce un nombre de 1 a 64 caracteres, sin saltos de línea.",
"local_connection_unavailable": "No se pudo conectar con nanobot en este equipo. Comprueba que esté en ejecución e inténtalo de nuevo.",
"disconnected": "Esta conexión compartida se cerró. Reconecta cuando quieras.",
"instance_changed": "La conexión a este servidor cambió. Al reconectar se recargará la vista; los borradores sin enviar podrían perderse.",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index 234792e87..b20ba0ba7 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Renommer",
+ "title": "Renommer le serveur",
+ "name": "Nom",
+ "hint": "Un nom pour cette connexion. Le serveur et les paramètres SSH restent inchangés."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Saisissez un nom de 1 à 64 caractères, sans saut de ligne.",
"local_connection_unavailable": "Impossible de joindre nanobot sur cet ordinateur. Vérifiez qu’il est en cours d’exécution, puis réessayez.",
"disconnected": "Cette connexion partagée a été fermée. Reconnectez-vous quand vous le souhaitez.",
"instance_changed": "La connexion à ce serveur a changé. La reconnexion rechargera la vue ; les brouillons non envoyés risquent d’être perdus.",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index ea30ae7f3..c420fc7f3 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Ubah nama",
+ "title": "Ubah nama server",
+ "name": "Nama",
+ "hint": "Nama untuk koneksi ini. Server dan pengaturan SSH tidak berubah."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Masukkan nama sepanjang 1–64 karakter, tanpa baris baru.",
"local_connection_unavailable": "Tidak dapat terhubung ke nanobot di komputer ini. Pastikan nanobot berjalan, lalu coba lagi.",
"disconnected": "Koneksi bersama ini telah ditutup. Sambungkan kembali saat Anda siap.",
"instance_changed": "Koneksi server ini berubah. Menyambungkan kembali akan memuat ulang tampilan; draf yang belum dikirim dapat hilang.",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index ab303e86e..12c06c961 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "名前を変更",
+ "title": "サーバー名を変更",
+ "name": "名前",
+ "hint": "接続の表示名です。サーバーや SSH 設定は変更されません。"
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "改行を含まない1~64文字の名前を入力してください。",
"local_connection_unavailable": "このコンピューターの nanobot に接続できませんでした。起動していることを確認して、もう一度お試しください。",
"disconnected": "この共有接続は閉じられました。必要なときに再接続できます。",
"instance_changed": "このサーバーへの接続が変わりました。再接続すると画面が再読み込みされ、未送信の下書きが失われる場合があります。",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 4eb5e9bb5..3a1e80087 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "이름 변경",
+ "title": "서버 이름 변경",
+ "name": "이름",
+ "hint": "연결의 표시 이름입니다. 서버나 SSH 설정은 변경되지 않습니다."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "줄 바꿈 없이 1~64자의 이름을 입력하세요.",
"local_connection_unavailable": "이 컴퓨터의 nanobot에 연결하지 못했습니다. 실행 중인지 확인한 후 다시 시도하세요.",
"disconnected": "공유 연결이 종료되었습니다. 준비되면 다시 연결하세요.",
"instance_changed": "이 서버 연결이 변경되었습니다. 다시 연결하면 화면이 새로고침되어 보내지 않은 초안이 사라질 수 있습니다.",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 4294ec87e..52a418664 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Renomear",
+ "title": "Renomear servidor",
+ "name": "Nome",
+ "hint": "Um nome para esta conexão. O servidor e as configurações SSH não serão alterados."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Insira um nome de 1 a 64 caracteres, sem quebras de linha.",
"local_connection_unavailable": "Não foi possível acessar o nanobot neste computador. Verifique se ele está em execução e tente novamente.",
"disconnected": "Esta conexão compartilhada foi fechada. Reconecte quando quiser.",
"instance_changed": "A conexão com este servidor mudou. A reconexão recarregará a tela; rascunhos não enviados poderão ser perdidos.",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index a72a557fb..6e3fe5dc9 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "Đổi tên",
+ "title": "Đổi tên máy chủ",
+ "name": "Tên",
+ "hint": "Tên cho kết nối này. Máy chủ và cài đặt SSH không thay đổi."
+ },
"sameInstance": {
"forgetAction": "Forget",
"switchHint": "To use another authorization, disconnect the open connection first.",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "Nhập tên từ 1–64 ký tự, không chứa dấu xuống dòng.",
"local_connection_unavailable": "Không thể kết nối với nanobot trên máy tính này. Hãy đảm bảo nanobot đang chạy rồi thử lại.",
"disconnected": "Kết nối dùng chung này đã đóng. Bạn có thể kết nối lại khi sẵn sàng.",
"instance_changed": "Kết nối đến máy chủ này đã thay đổi. Kết nối lại sẽ tải lại giao diện; bản nháp chưa gửi có thể bị mất.",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index 0e6e11ffd..f346e65f0 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "重命名",
+ "title": "重命名服务器",
+ "name": "名称",
+ "hint": "给连接起个好认的名字,不会更改服务器或 SSH 设置。"
+ },
"sameInstance": {
"forgetAction": "忘记",
"switchHint": "要使用另一份授权,请先断开当前连接。",
@@ -160,6 +166,7 @@
"forgetTitle": "忘记 {{name}}?",
"forgetDescription": "只移除本机保存的连接。服务器上的 nanobot、密钥和会话都不会被删除。",
"errors": {
+ "invalid_name": "请输入 1–64 个字符的名称,不能包含换行。",
"local_connection_unavailable": "暂时无法连接这台电脑上的 nanobot,请确保它正在运行后重试。",
"disconnected": "此共享连接已断开,需要时可重新连接。",
"instance_changed": "此服务器的连接已发生变化。重新连接会重新打开页面,未发送的草稿可能丢失。",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index 9a0bbd132..e9b89ec51 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1,5 +1,11 @@
{
"remote": {
+ "rename": {
+ "action": "重新命名",
+ "title": "重新命名伺服器",
+ "name": "名稱",
+ "hint": "為連線取個好認的名字,不會更改伺服器或 SSH 設定。"
+ },
"sameInstance": {
"forgetAction": "忘記",
"switchHint": "若要使用另一份授權,請先中斷目前連線。",
@@ -160,6 +166,7 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
+ "invalid_name": "請輸入 1–64 個字元的名稱,不能包含換行。",
"local_connection_unavailable": "暫時無法連線到這台電腦上的 nanobot,請確認它正在執行後重試。",
"disconnected": "此共用連線已中斷,需要時可重新連線。",
"instance_changed": "此伺服器的連線已發生變化。重新連線會重新開啟頁面,未傳送的草稿可能遺失。",
diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsx
index 64ae85828..17df5dd3e 100644
--- a/webui/src/tests/remote-instances.test.tsx
+++ b/webui/src/tests/remote-instances.test.tsx
@@ -92,6 +92,77 @@ function chooseExistingSSH() {
}
describe("remote instance UX", () => {
+ it.each([false, true])("renames an open server without reloading its view (paired: %s)", async (paired) => {
+ let saved = { ...profile, paired, connected: true };
+ mocks.read.mockImplementation(async () => ({ available: true, profiles: [saved] }));
+ mocks.request.mockImplementation(async (action, payload) => {
+ if (action === "remote.connect") return connection;
+ if (action === "remote.rename") { saved = { ...saved, name: payload.name }; return { available: true, profiles: [saved] }; }
+ return {};
+ });
+ view();
+ await chooseHost("Team server [email protected]");
+ const frame = await readyRemote();
+ const source = { postMessage: vi.fn() };
+ Object.defineProperty(frame, "contentWindow", { value: source });
+ act(() => window.dispatchEvent(new MessageEvent("message", { source: source as unknown as Window,
+ origin: "http://127.0.0.1:23456", data: { channel: HOST_BRIDGE, type: "hello" } })));
+ await openDirectory();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
+ fireEvent.click(screen.getByRole("menuitem", { name: "Rename", exact: true }));
+ const input = await screen.findByRole("textbox", { name: "Name", exact: true });
+ expect(input).toHaveValue("Team server");
+ expect(input).toHaveFocus();
+ expect(input).toHaveAttribute("maxlength", "64");
+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
+ fireEvent.change(input, { target: { value: " 腾讯云 nanobot " } });
+ fireEvent.submit(input.closest("form")!);
+ await screen.findByRole("button", { name: "Manage 腾讯云 nanobot" });
+ expect(mocks.request).toHaveBeenCalledWith("remote.rename", { id: profile.id, name: "腾讯云 nanobot" }, 65_000);
+ expect(screen.getByTitle("nanobot on 腾讯云 nanobot")).toBe(frame);
+ expect(frame).toHaveAttribute("src", connection.url);
+ expect(readSelectedRemote()).toMatchObject({ id: profile.id, name: "腾讯云 nanobot" });
+ expect(document.title).toBe("腾讯云 nanobot · nanobot");
+ expect(source.postMessage).toHaveBeenLastCalledWith(expect.objectContaining({ type: "init", name: "腾讯云 nanobot" }), "http://127.0.0.1:23456");
+ expect(mocks.request.mock.calls.map(([action]) => action)).toEqual(["remote.connect", "remote.rename"]);
+ await chooseHost("腾讯云 nanobot [email protected]");
+ expect(screen.getByTitle("nanobot on 腾讯云 nanobot")).toBe(frame);
+ expect(mocks.request).toHaveBeenCalledTimes(2);
+ });
+
+ it("rejects a blank name, preserves input on failure and lets the user retry or cancel", async () => {
+ view(); await openDirectory();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
+ fireEvent.click(screen.getByRole("menuitem", { name: "Rename", exact: true }));
+ const input = await screen.findByRole("textbox", { name: "Name", exact: true });
+ fireEvent.change(input, { target: { value: " " } });
+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
+ fireEvent.submit(input.closest("form")!);
+ expect(mocks.request).not.toHaveBeenCalled();
+ mocks.request.mockRejectedValueOnce(new Error("local_io_error"));
+ fireEvent.change(input, { target: { value: "Cloud" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.local_io_error"));
+ expect(input).toHaveValue("Cloud");
+ expect(screen.getByRole("button", { name: "Save changes" })).toBeEnabled();
+ fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true }));
+ expect(screen.getByRole("button", { name: "Manage Team server" })).toBeVisible();
+ expect(mocks.request).toHaveBeenCalledTimes(1);
+ });
+
+ it("offers one instance-level rename for grouped authorizations", async () => {
+ const siblings = [{ ...profile, paired: true, instance_id: profile.id }, { ...profile, id: "other-grant", paired: true, instance_id: profile.id }];
+ mocks.read.mockResolvedValue({ available: true, profiles: siblings });
+ mocks.request.mockResolvedValue({ available: true, profiles: siblings.map((item) => ({ ...item, name: "Cloud" })) });
+ view(); await openDirectory();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
+ fireEvent.click(screen.getByRole("menuitem", { name: "Rename", exact: true }));
+ fireEvent.change(await screen.findByRole("textbox", { name: "Name", exact: true }), { target: { value: "Cloud" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
+ await screen.findByRole("button", { name: "Manage Cloud" });
+ expect(screen.getAllByRole("button", { name: "Cloud [email protected]" })).toHaveLength(1);
+ });
+
it("shows revocation as a shared copyable code block without executing it or forgetting the connection", async () => {
const command = "nanobot remote revoke 0dec816f-55e8-47ab-a8ad-13251e2a4f30 --ssh-user ubuntu";
const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);