Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat(home): store pinned automations in agent-server settings (#18190)

Abhay Mishradd597d713325
diff --git a/__tests__/components/features/home/featured-automations-section.test.tsx b/__tests__/components/features/home/featured-automations-section.test.tsx
index b817276536..9f709099e3 100644
--- a/__tests__/components/features/home/featured-automations-section.test.tsx
+++ b/__tests__/components/features/home/featured-automations-section.test.tsx
@@ -8,6 +8,8 @@ import AutomationService from "#/api/automation-service/automation-service.api";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { DEFAULT_SETTINGS } from "#/services/settings";
import {
__resetActiveStoreForTests,
setActiveSelection,
@@ -18,7 +20,6 @@ import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import { PinnedAutomationsDashboard } from "#/components/features/home/featured-automations/pinned-automations-dashboard";
import { RunningAutomationsList } from "#/components/features/home/featured-automations/running-automations-list";
import { NavigationProvider } from "#/context/navigation-context";
-import { HOME_PINNED_AUTOMATIONS_KEY } from "#/hooks/use-home-pinned-automations";
import { AUTOMATION_STACK_SECTION_BOTTOM_CLASS } from "#/utils/automation-stack-section";
import {
AutomationRunStatus,
@@ -66,6 +67,8 @@ vi.mock("#/api/profiles-service/profiles-service.api", () => ({
},
}));
+vi.mock("#/api/settings-service/settings-service.api");
+
vi.mock("#/utils/custom-toast-handlers", () => ({
displaySuccessToast: vi.fn(),
displayErrorToast: vi.fn(),
@@ -142,14 +145,6 @@ function makeConversation(id: string, title: string | null): AppConversation {
};
}
-/** Pins are stored under a backend/org-scoped key; find it by prefix. */
-function getStoredPinnedIds(): string | null {
- const key = Object.keys(window.localStorage).find((storageKey) =>
- storageKey.startsWith(HOME_PINNED_AUTOMATIONS_KEY),
- );
- return key ? window.localStorage.getItem(key) : null;
-}
-
function renderHomeAutomations(ui: React.ReactElement) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -173,6 +168,15 @@ function renderHomeAutomations(ui: React.ReactElement) {
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
+ let serverPins: string[] | undefined;
+ vi.mocked(SettingsService.getSettings).mockImplementation(async () => ({
+ ...DEFAULT_SETTINGS,
+ home_pinned_automations: serverPins,
+ }));
+ vi.mocked(SettingsService.saveSettings).mockImplementation(async (update) => {
+ serverPins = update.home_pinned_automations;
+ return true;
+ });
vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });
vi.mocked(AutomationService.getAutomations).mockResolvedValue({
automations: [makeAutomation()],
@@ -471,7 +475,9 @@ describe("home automations composer layout", () => {
within(dashboard).getByText("AUTOMATIONS$DETAIL$NO_CONVERSATION"),
).toBeInTheDocument();
- expect(getStoredPinnedIds()).toContain("auto-1");
+ expect(SettingsService.saveSettings).toHaveBeenLastCalledWith({
+ home_pinned_automations: ["auto-1", "auto-2"],
+ });
expect(
screen.queryByTestId("pinned-automation-run-now-auto-1"),
diff --git a/__tests__/hooks/use-home-pinned-automations.test.ts b/__tests__/hooks/use-home-pinned-automations.test.ts
index 79a28e61d2..3805225008 100644
--- a/__tests__/hooks/use-home-pinned-automations.test.ts
+++ b/__tests__/hooks/use-home-pinned-automations.test.ts
@@ -1,11 +1,182 @@
-import { describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import React from "react";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
import {
applyPinnedOrder,
getHomePinnedAutomationsKey,
HOME_PINNED_AUTOMATIONS_KEY,
movePinnedId,
+ useHomePinnedAutomations,
} from "#/hooks/use-home-pinned-automations";
+vi.mock("#/api/settings-service/settings-service.api");
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "cloud-1",
+ name: "Production",
+ host: "https://app.all-hands.dev",
+ apiKey: "bearer-key",
+ kind: "cloud",
+};
+
+function renderPinnedHook<T>(hook: () => T) {
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(ActiveBackendProvider, null, children),
+ );
+ return renderHook(hook, { wrapper });
+}
+
+function activate(backend: Backend) {
+ setRegisteredBackends([backend]);
+ setActiveSelection({ backendId: backend.id });
+}
+
+/** Pins the mocked agent-server holds; saves replace it, like the server. */
+let serverPins: string[] | undefined;
+
+beforeEach(() => {
+ window.localStorage.clear();
+ serverPins = undefined;
+ vi.mocked(SettingsService.getSettings).mockImplementation(async () => ({
+ ...DEFAULT_SETTINGS,
+ home_pinned_automations: serverPins,
+ }));
+ vi.mocked(SettingsService.saveSettings).mockImplementation(async (update) => {
+ serverPins = update.home_pinned_automations;
+ return true;
+ });
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+ vi.clearAllMocks();
+});
+
+describe("useHomePinnedAutomations on a local backend", () => {
+ it("reads pins from server settings and saves each change as the full ordered list", async () => {
+ // Arrange
+ activate(localBackend);
+ serverPins = ["a", "b"];
+ const { result } = renderPinnedHook(() => useHomePinnedAutomations());
+ await waitFor(() => expect(result.current.pinnedIds).toEqual(["a", "b"]));
+
+ // Act + Assert
+ act(() => result.current.pin("c"));
+ await waitFor(() =>
+ expect(result.current.pinnedIds).toEqual(["a", "b", "c"]),
+ );
+ act(() => result.current.reorder("c", "a", "before"));
+ await waitFor(() =>
+ expect(result.current.pinnedIds).toEqual(["c", "a", "b"]),
+ );
+ act(() => result.current.unpin("a"));
+ await waitFor(() => expect(result.current.pinnedIds).toEqual(["c", "b"]));
+
+ await waitFor(() =>
+ expect(
+ vi
+ .mocked(SettingsService.saveSettings)
+ .mock.calls.map(([update]) => update),
+ ).toEqual([
+ { home_pinned_automations: ["a", "b", "c"] },
+ { home_pinned_automations: ["c", "a", "b"] },
+ { home_pinned_automations: ["c", "b"] },
+ ]),
+ );
+ });
+
+ it("moves legacy localStorage pins to the server once, then removes the local copy", async () => {
+ // Arrange: the dashboard and the activity list each mount the hook.
+ activate(localBackend);
+ const legacyKey = getHomePinnedAutomationsKey(localBackend.id, null);
+ window.localStorage.setItem(legacyKey, JSON.stringify(["legacy", "a"]));
+ serverPins = ["a"];
+
+ // Act
+ const { result } = renderPinnedHook(() => [
+ useHomePinnedAutomations(),
+ useHomePinnedAutomations(),
+ ]);
+
+ // Assert
+ await waitFor(() =>
+ expect(window.localStorage.getItem(legacyKey)).toBe(null),
+ );
+ expect(SettingsService.saveSettings).toHaveBeenCalledExactlyOnceWith({
+ home_pinned_automations: ["a", "legacy"],
+ });
+ expect(result.current[0].pinnedIds).toEqual(["a", "legacy"]);
+ });
+
+ it("keeps the legacy localStorage pins when the server save fails", async () => {
+ // Arrange
+ activate(localBackend);
+ const legacyKey = getHomePinnedAutomationsKey(localBackend.id, null);
+ window.localStorage.setItem(legacyKey, JSON.stringify(["legacy"]));
+ vi.mocked(SettingsService.saveSettings).mockRejectedValue(
+ new Error("offline"),
+ );
+
+ // Act
+ renderPinnedHook(() => useHomePinnedAutomations());
+
+ // Assert
+ await waitFor(() =>
+ expect(SettingsService.saveSettings).toHaveBeenCalledOnce(),
+ );
+ expect(window.localStorage.getItem(legacyKey)).toBe(
+ JSON.stringify(["legacy"]),
+ );
+ });
+});
+
+describe("useHomePinnedAutomations on a cloud backend", () => {
+ it("keeps pins in localStorage and never writes them to settings", async () => {
+ // Arrange
+ activate(cloudBackend);
+ const { result } = renderPinnedHook(() => useHomePinnedAutomations());
+
+ // Act
+ act(() => result.current.pin("a"));
+
+ // Assert
+ await waitFor(() => expect(result.current.pinnedIds).toEqual(["a"]));
+ expect(
+ window.localStorage.getItem(
+ getHomePinnedAutomationsKey(cloudBackend.id, null),
+ ),
+ ).toBe(JSON.stringify(["a"]));
+ expect(SettingsService.saveSettings).not.toHaveBeenCalled();
+ });
+});
+
describe("getHomePinnedAutomationsKey", () => {
it("scopes the storage key by backend and org", () => {
expect(getHomePinnedAutomationsKey("backend-a", "org-1")).toBe(
diff --git a/src/api/settings-service/settings-service.api.ts b/src/api/settings-service/settings-service.api.ts
index 6366d60aff..66f79ec7c7 100644
--- a/src/api/settings-service/settings-service.api.ts
+++ b/src/api/settings-service/settings-service.api.ts
@@ -42,6 +42,7 @@ export const APP_PREFERENCE_FIELDS = [
"enabled_skills",
"run_router_at_conversation_start",
"workspace_file_discovery",
+ "home_pinned_automations",
"default_profile_migrated",
] as const;
diff --git a/src/hooks/use-home-pinned-automations.ts b/src/hooks/use-home-pinned-automations.ts
index 8471b7692b..3d3dcaf493 100644
--- a/src/hooks/use-home-pinned-automations.ts
+++ b/src/hooks/use-home-pinned-automations.ts
@@ -1,10 +1,19 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useLocalStorage } from "@uidotdev/usehooks";
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ getActiveBackend,
+ isNoBackend,
+} from "#/api/backend-registry/active-store";
+import SettingsService from "#/api/settings-service/settings-service.api";
import { useActiveBackend } from "#/contexts/active-backend-context";
import {
HOME_AUTOMATIONS_DEMO_PINNED_IDS,
isHomeAutomationsDemoEnabled,
} from "#/fixtures/home-automations-demo";
+import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
+import { useSettings } from "#/hooks/query/use-settings";
+import type { Settings } from "#/types/settings";
export const HOME_PINNED_AUTOMATIONS_KEY = "oh:home-pinned-automations";
@@ -12,6 +21,9 @@ export const HOME_PINNED_AUTOMATIONS_KEY = "oh:home-pinned-automations";
* Pins are stored per backend + org: automation ids only resolve against the
* backend that issued them, and `pruneMissing` compares against the active
* backend's list β€” a shared key would let one backend wipe another's pins.
+ *
+ * Local backends keep pins in server settings and use this key only for the
+ * one-time migration of older browser-stored pins; cloud still stores here.
*/
export function getHomePinnedAutomationsKey(
backendId: string,
@@ -37,6 +49,16 @@ function sanitizePinnedIds(value: unknown): string[] {
return next;
}
+function hasSameIds(a: readonly string[], b: readonly string[]): boolean {
+ return a.length === b.length && a.every((id, index) => id === b[index]);
+}
+
+/**
+ * Legacy keys whose pins are being copied to the server. Several components
+ * mount this hook at once; this keeps them from starting duplicate copies.
+ */
+const migratingLegacyKeys = new Set<string>();
+
/** Reorder `base` to match `preferred` where possible; append leftovers. */
export function applyPinnedOrder(
base: readonly string[],
@@ -77,29 +99,153 @@ export function movePinnedId(
}
/**
- * Pin state for home automation activity rows. Persists pinned ids in
- * localStorage so dashboard modules survive reload. Resolution against live
- * automations happens in the consuming components.
+ * Pin state for home automation activity rows. Local backends persist pinned
+ * ids in `misc_settings.app_preferences` on the agent-server so they follow
+ * the user across browsers; cloud backends keep them in localStorage.
+ * Resolution against live automations happens in the consuming components.
*/
export function useHomePinnedAutomations() {
const demo = isHomeAutomationsDemoEnabled();
const active = useActiveBackend();
- const [rawPinnedIds, setRawPinnedIds] = useLocalStorage<string[]>(
- getHomePinnedAutomationsKey(active.backend.id, active.orgId),
- [],
+ const backendId = active.backend.id;
+ const { orgId } = active;
+ const storageKey = getHomePinnedAutomationsKey(backendId, orgId);
+ const usesServerSettings =
+ !demo && active.backend.kind === "local" && !isNoBackend(active.backend);
+ // No initial value: an initial value would re-create the legacy key right
+ // after the migration below removes it.
+ const [rawPinnedIds, setRawPinnedIds] = useLocalStorage<string[] | undefined>(
+ storageKey,
);
// Demo pins are fixture-backed; keep session order overrides in memory so
// drag reorder still works while testing with mock data.
const [demoOrder, setDemoOrder] = useState<string[] | null>(null);
+ const queryClient = useQueryClient();
+ const settings = useSettings();
+ const settingsQueryKey = useMemo(
+ () => [...SETTINGS_QUERY_KEYS.byScope("personal"), backendId, orgId],
+ [backendId, orgId],
+ );
+ const { mutate: savePinnedIds, mutateAsync: savePinnedIdsAsync } =
+ useMutation({
+ mutationKey: [storageKey],
+ // Run saves one at a time so an older list never lands after a newer one.
+ scope: { id: storageKey },
+ mutationFn: async (ids: string[]) => {
+ // A save queued on one backend must never write into another.
+ const current = getActiveBackend();
+ if (current.backend.id !== backendId || current.orgId !== orgId) {
+ return false;
+ }
+ await SettingsService.saveSettings({ home_pinned_automations: ids });
+ return true;
+ },
+ onSettled: async () => {
+ // Refetch only after the last queued save: an earlier refetch would
+ // replace the newer optimistic list with an older server value.
+ if (queryClient.isMutating({ mutationKey: [storageKey] }) === 1) {
+ await queryClient.invalidateQueries({ queryKey: settingsQueryKey });
+ }
+ },
+ });
+
+ const readServerPinnedIds = useCallback(() => {
+ const cached = queryClient.getQueryData<Settings>(settingsQueryKey);
+ return cached ? sanitizePinnedIds(cached.home_pinned_automations) : null;
+ }, [queryClient, settingsQueryKey]);
+
+ const setServerPinnedIds = useCallback(
+ (ids: string[]) => {
+ void queryClient.cancelQueries({ queryKey: settingsQueryKey });
+ queryClient.setQueryData<Settings>(settingsQueryKey, (cached) =>
+ cached ? { ...cached, home_pinned_automations: ids } : cached,
+ );
+ },
+ [queryClient, settingsQueryKey],
+ );
+
+ const updatePinnedIds = useCallback(
+ (update: (current: string[]) => string[]) => {
+ if (!usesServerSettings) {
+ setRawPinnedIds((current) => update(sanitizePinnedIds(current)));
+ return;
+ }
+ // Until settings load there is no base list, and saving a partial list
+ // would overwrite the user's server pins.
+ const current = readServerPinnedIds();
+ if (!current) return;
+ const next = update(current);
+ if (hasSameIds(current, next)) return;
+ setServerPinnedIds(next);
+ savePinnedIds(next);
+ },
+ [
+ usesServerSettings,
+ setRawPinnedIds,
+ readServerPinnedIds,
+ setServerPinnedIds,
+ savePinnedIds,
+ ],
+ );
+
+ // `useLocalStorage` parses a new array every render; the string stays
+ // stable, so the effect below runs only when the stored pins change.
+ const legacyPinsJson =
+ rawPinnedIds == null ? null : JSON.stringify(rawPinnedIds);
+ useEffect(() => {
+ if (!usesServerSettings || !settings.isSuccess || legacyPinsJson === null) {
+ return;
+ }
+ if (migratingLegacyKeys.has(storageKey)) return;
+ const current = readServerPinnedIds();
+ if (!current) return;
+ migratingLegacyKeys.add(storageKey);
+ const next = sanitizePinnedIds([
+ ...current,
+ ...sanitizePinnedIds(JSON.parse(legacyPinsJson)),
+ ]);
+ let saved: Promise<boolean> = Promise.resolve(true);
+ if (!hasSameIds(current, next)) {
+ setServerPinnedIds(next);
+ saved = savePinnedIdsAsync(next);
+ }
+ saved
+ .then((didSave) => {
+ if (didSave) setRawPinnedIds(undefined);
+ })
+ // Keep the legacy pins on failure; the next mount retries the copy.
+ .catch(() => undefined)
+ .finally(() => migratingLegacyKeys.delete(storageKey));
+ }, [
+ usesServerSettings,
+ settings.isSuccess,
+ legacyPinsJson,
+ storageKey,
+ readServerPinnedIds,
+ setServerPinnedIds,
+ savePinnedIdsAsync,
+ setRawPinnedIds,
+ ]);
+
const pinnedIds = useMemo(() => {
if (demo) {
return demoOrder
? applyPinnedOrder(HOME_AUTOMATIONS_DEMO_PINNED_IDS, demoOrder)
: [...HOME_AUTOMATIONS_DEMO_PINNED_IDS];
}
- return sanitizePinnedIds(rawPinnedIds);
- }, [demo, demoOrder, rawPinnedIds]);
+ return sanitizePinnedIds(
+ usesServerSettings
+ ? settings.data?.home_pinned_automations
+ : rawPinnedIds,
+ );
+ }, [
+ demo,
+ demoOrder,
+ usesServerSettings,
+ settings.data?.home_pinned_automations,
+ rawPinnedIds,
+ ]);
const isPinned = useCallback(
(id: string) => pinnedIds.includes(id),
@@ -118,13 +264,11 @@ export function useHomePinnedAutomations() {
});
return;
}
- setRawPinnedIds((current) => {
- const next = sanitizePinnedIds(current);
- if (next.includes(id)) return next;
- return [...next, id];
- });
+ updatePinnedIds((current) =>
+ current.includes(id) ? current : [...current, id],
+ );
},
- [demo, setRawPinnedIds],
+ [demo, updatePinnedIds],
);
const unpin = useCallback(
@@ -138,11 +282,11 @@ export function useHomePinnedAutomations() {
});
return;
}
- setRawPinnedIds((current) =>
- sanitizePinnedIds(current).filter((pinnedId) => pinnedId !== id),
+ updatePinnedIds((current) =>
+ current.filter((pinnedId) => pinnedId !== id),
);
},
- [demo, setRawPinnedIds],
+ [demo, updatePinnedIds],
);
const togglePin = useCallback(
@@ -171,30 +315,20 @@ export function useHomePinnedAutomations() {
});
return;
}
- setRawPinnedIds((current) =>
- movePinnedId(sanitizePinnedIds(current), activeId, targetId, position),
+ updatePinnedIds((current) =>
+ movePinnedId(current, activeId, targetId, position),
);
},
- [demo, setRawPinnedIds],
+ [demo, updatePinnedIds],
);
/** Drop pin ids that no longer exist on the backend (deleted automations). */
const pruneMissing = useCallback(
(knownIds: ReadonlySet<string>) => {
if (demo) return;
- setRawPinnedIds((current) => {
- const sanitized = sanitizePinnedIds(current);
- const next = sanitized.filter((id) => knownIds.has(id));
- if (
- next.length === sanitized.length &&
- next.every((id, index) => id === sanitized[index])
- ) {
- return sanitized;
- }
- return next;
- });
+ updatePinnedIds((current) => current.filter((id) => knownIds.has(id)));
},
- [demo, setRawPinnedIds],
+ [demo, updatePinnedIds],
);
return {
diff --git a/src/types/settings.ts b/src/types/settings.ts
index 8f7e75c3dd..9a5d52d371 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -111,6 +111,8 @@ export type AgentKind = "openhands" | "acp";
export type Settings = {
workspace_file_discovery?: Record<string, WorkspaceFileDiscovery | null>;
+ /** Ordered ids of automations pinned to the home dashboard (local only). */
+ home_pinned_automations?: string[];
llm_model: string;
llm_base_url: string;
agent: string;