Skip to content

Commit

Permalink
feat: add new .env variable "LANGFLOW_FEATURE_MVP_COMPONENTS" to show…
Browse files Browse the repository at this point in the history
…/hide integration sidebar components (#4270)

* ✨ (authContext.tsx): Add functionality to fetch global variables on authentication
🔧 (api.tsx): Replace universal-cookie import with react-cookie for consistency
🔧 (authStore.ts): Replace universal-cookie import with react-cookie for consistency
🔧 (use-get-global-variables.ts): Add check to only fetch global variables if user is authenticated
✨ (use-get-mutation-global-variables.ts): Add mutation function to fetch and update global variables
🔧 (authStore.ts): Replace universal-cookie import with react-cookie for consistency

* 📝 (endpoints.py): add feature_flags field to ConfigResponse schema
📝 (endpoints.py): modify get_config function to include feature_flags in the response
📝 (feature_flags.py): add mvp_components field to FeatureFlags settings
📝 (schemas.py): add feature_flags field to ConfigResponse schema

* ✨ (use-get-config.ts): Add feature_flags field to ConfigResponse interface to support feature flags in the application
🔧 (utilityStore.ts): Add featureFlags field and setFeatureFlags function to utilityStore to manage feature flags in the application
💡 (extraSidebarComponent/index.tsx): Use featureFlags from utilityStore to conditionally render components based on feature flags in ExtraSidebar component

* ♻️ (frontend/package-lock.json): remove extraneous flag from is-unicode-supported package to clean up unnecessary information

* ✨ (integration-side-bar.spec.ts): Add integration tests to ensure correct visibility of integrations in the sidebar based on the value of mvp_components.

* ✨ (integration-side-bar.spec.ts): update integration-side-bar tests to use feature_flags object for mvp_components flag for better readability and maintainability.

* ✨ (integration-side-bar.spec.ts): add a 4-second delay before making the API call to improve test reliability

* [autofix.ci] apply automated fixes

* Update src/backend/base/langflow/api/v1/schemas.py

Co-authored-by: Gabriel Luiz Freitas Almeida <[email protected]>

* Update src/backend/base/langflow/api/v1/endpoints.py

Co-authored-by: Gabriel Luiz Freitas Almeida <[email protected]>

* formata

* [autofix.ci] apply automated fixes

* ✨ (extraSidebarComponent/index.tsx): update featureFlags property access to use optional chaining for better error handling
📝 (stop-building.spec.ts): add ua-parser-js import to get user agent information and update control key based on user's operating system for better user experience. Also, refactor code to improve readability and add comments for better understanding.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Gabriel Luiz Freitas Almeida <[email protected]>
  • Loading branch information
3 people authored Oct 28, 2024
1 parent d53107c commit a88fd9b
Show file tree
Hide file tree
Showing 9 changed files with 180 additions and 5 deletions.
4 changes: 3 additions & 1 deletion src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
get_task_service,
get_telemetry_service,
)
from langflow.services.settings.feature_flags import FEATURE_FLAGS
from langflow.services.telemetry.schema import RunPayload
from langflow.utils.constants import SIDEBAR_CATEGORIES
from langflow.utils.version import get_version_info
Expand Down Expand Up @@ -629,7 +630,8 @@ def get_config():
from langflow.services.deps import get_settings_service

settings_service: SettingsService = get_settings_service()
return settings_service.settings.model_dump()

return {"feature_flags": FEATURE_FLAGS, **settings_service.settings.model_dump()}
except Exception as exc:
raise HTTPException(status_code=500, detail=str(exc)) from exc

Expand Down
2 changes: 2 additions & 0 deletions src/backend/base/langflow/api/v1/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from langflow.services.database.models.base import orjson_dumps
from langflow.services.database.models.flow import FlowCreate, FlowRead
from langflow.services.database.models.user import UserRead
from langflow.services.settings.feature_flags import FeatureFlags
from langflow.services.tracing.schema import Log
from langflow.utils.util_strings import truncate_long_strings

Expand Down Expand Up @@ -350,6 +351,7 @@ class FlowDataRequest(BaseModel):


class ConfigResponse(BaseModel):
feature_flags: FeatureFlags
frontend_timeout: int
auto_saving: bool
auto_saving_interval: int
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

class FeatureFlags(BaseSettings):
add_toolkit_output: bool = False
mvp_components: bool = False

class Config:
env_prefix = "LANGFLOW_FEATURE_"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface ConfigResponse {
auto_saving_interval: number;
health_check_max_retries: number;
max_file_size_upload: number;
feature_flags: Record<string, any>;
}

export const useGetConfig: useQueryFunctionType<undefined, ConfigResponse> = (
Expand All @@ -27,6 +28,7 @@ export const useGetConfig: useQueryFunctionType<undefined, ConfigResponse> = (
const setMaxFileSizeUpload = useUtilityStore(
(state) => state.setMaxFileSizeUpload,
);
const setFeatureFlags = useUtilityStore((state) => state.setFeatureFlags);

const { query } = UseRequestProcessor();

Expand All @@ -43,6 +45,7 @@ export const useGetConfig: useQueryFunctionType<undefined, ConfigResponse> = (
setAutoSavingInterval(data.auto_saving_interval);
setHealthCheckMaxRetries(data.health_check_max_retries);
setMaxFileSizeUpload(data.max_file_size_upload);
setFeatureFlags(data.feature_flags);
}
return data;
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { nodeIconsLucide } from "../../../../utils/styleUtils";
import ParentDisclosureComponent from "../ParentDisclosureComponent";
import { SidebarCategoryComponent } from "./SidebarCategoryComponent";

import { useUtilityStore } from "@/stores/utilityStore";
import { SidebarFilterComponent } from "./sidebarFilterComponent";
import { sortKeys } from "./utils";

Expand All @@ -31,6 +32,8 @@ export default function ExtraSidebar(): JSX.Element {
const hasStore = useStoreStore((state) => state.hasStore);
const filterType = useFlowStore((state) => state.filterType);

const featureFlags = useUtilityStore((state) => state.featureFlags);

const setErrorData = useAlertStore((state) => state.setErrorData);
const [dataFilter, setFilterData] = useState(data);
const [search, setSearch] = useState("");
Expand Down Expand Up @@ -248,7 +251,7 @@ export default function ExtraSidebar(): JSX.Element {
<div key={index}></div>
),
)}
{ENABLE_INTEGRATIONS && (
{(ENABLE_INTEGRATIONS || featureFlags?.mvp_components) && (
<ParentDisclosureComponent
defaultOpen={true}
key={`${search.length !== 0}-${getFilterEdge.length !== 0}-Bundle`}
Expand Down
2 changes: 2 additions & 0 deletions src/frontend/src/stores/utilityStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@ export const useUtilityStore = create<UtilityStoreType>((set, get) => ({
setFlowsPagination: (flowsPagination: Pagination) => set({ flowsPagination }),
tags: [],
setTags: (tags: Tag[]) => set({ tags }),
featureFlags: {},
setFeatureFlags: (featureFlags: Record<string, any>) => set({ featureFlags }),
}));
2 changes: 2 additions & 0 deletions src/frontend/src/types/zustand/utility/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ export type UtilityStoreType = {
setFlowsPagination: (pagination: Pagination) => void;
tags: Tag[];
setTags: (tags: Tag[]) => void;
featureFlags: Record<string, any>;
setFeatureFlags: (featureFlags: Record<string, any>) => void;
};
70 changes: 67 additions & 3 deletions src/frontend/tests/core/features/stop-building.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { expect, test } from "@playwright/test";
import uaParser from "ua-parser-js";

test("user must be able to stop a building", async ({ page }) => {
await page.goto("/");
Expand All @@ -20,6 +21,14 @@ test("user must be able to stop a building", async ({ page }) => {
modalCount = await page.getByTestId("modal-title")?.count();
}

const getUA = await page.evaluate(() => navigator.userAgent);
const userAgentInfo = uaParser(getUA);
let control = "Control";

if (userAgentInfo.os.name.includes("Mac")) {
control = "Meta";
}

await page.getByTestId("blank-flow").click();

//first component
Expand Down Expand Up @@ -203,7 +212,62 @@ test("user must be able to stop a building", async ({ page }) => {
await page.getByTestId("int_int_chunk_size").fill("2");
await page.getByTestId("int_int_chunk_overlap").fill("1");

await page.getByTestId("button_run_chat output").click();
const timerCode = `
# from langflow.field_typing import Data
from langflow.custom import Component
from langflow.io import MessageTextInput, Output
from langflow.schema import Data
import time
class CustomComponent(Component):
display_name = "Custom Component"
description = "Use as a template to create your own component."
documentation: str = "http://docs.langflow.org/components/custom"
icon = "custom_components"
name = "CustomComponent"
inputs = [
MessageTextInput(name="input_value", display_name="Input Value", value="Hello, World!"),
]
outputs = [
Output(display_name="Output", name="output", method="build_output"),
]
def build_output(self) -> Data:
time.sleep(10000)
data = Data(value=self.input_value)
self.status = data
return data
`;

await page.getByTestId("extended-disclosure").click();
await page.getByPlaceholder("Search").click();
await page.getByPlaceholder("Search").fill("custom component");

await page.waitForTimeout(1000);

await page
.locator('//*[@id="helpersCustom Component"]')
.dragTo(page.locator('//*[@id="react-flow-id"]'));
await page.mouse.up();
await page.mouse.down();
await page.getByTitle("fit view").click();
await page.getByTitle("zoom out").click();

await page.getByTestId("title-Custom Component").first().click();

await page.waitForTimeout(500);
await page.getByTestId("code-button-modal").click();
await page.waitForTimeout(500);

await page.locator("textarea").last().press(`${control}+a`);
await page.keyboard.press("Backspace");
await page.locator("textarea").last().fill(timerCode);
await page.locator('//*[@id="checkAndSaveBtn"]').click();
await page.waitForTimeout(500);

await page.getByTestId("button_run_custom component").click();

await page.waitForSelector("text=Building", {
timeout: 100000,
Expand Down Expand Up @@ -233,7 +297,7 @@ test("user must be able to stop a building", async ({ page }) => {
timeout: 100000,
});

await page.getByTestId("button_run_chat output").click();
await page.getByTestId("button_run_custom component").click();

await page.waitForSelector("text=Building", {
timeout: 100000,
Expand Down Expand Up @@ -269,7 +333,7 @@ test("user must be able to stop a building", async ({ page }) => {
timeout: 100000,
});

await page.getByTestId("button_run_chat output").click();
await page.getByTestId("button_run_custom component").click();

await page.waitForSelector('[data-testid="loading_icon"]', {
timeout: 100000,
Expand Down
96 changes: 96 additions & 0 deletions src/frontend/tests/extended/features/integration-side-bar.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { expect, test } from "@playwright/test";

test("user should be able to see integrations in the sidebar if mvp_components is true", async ({
page,
}) => {
await page.route("**/api/v1/config", (route) => {
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
feature_flags: {
mvp_components: true,
},
}),
headers: {
"content-type": "application/json",
...route.request().headers(),
},
});
});

await page.goto("/");
await page.waitForTimeout(1000);

let modalCount = 0;
try {
const modalTitleElement = await page?.getByTestId("modal-title");
if (modalTitleElement) {
modalCount = await modalTitleElement.count();
}
} catch (error) {
modalCount = 0;
}

while (modalCount === 0) {
await page.getByText("New Project", { exact: true }).click();
await page.waitForTimeout(3000);
modalCount = await page.getByTestId("modal-title")?.count();
}

await page.getByTestId("blank-flow").click();
await page.waitForSelector('[data-testid="extended-disclosure"]', {
timeout: 30000,
});

await expect(page.getByText("Integrations")).toBeVisible();
await expect(page.getByText("Notion")).toBeVisible();
});

test("user should NOT be able to see integrations in the sidebar if mvp_components is false", async ({
page,
}) => {
await page.waitForTimeout(4000);
await page.route("**/api/v1/config", (route) => {
route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
feature_flags: {
mvp_components: false,
},
}),
headers: {
"content-type": "application/json",
...route.request().headers(),
},
});
});

await page.goto("/");
await page.waitForTimeout(1000);

let modalCount = 0;
try {
const modalTitleElement = await page?.getByTestId("modal-title");
if (modalTitleElement) {
modalCount = await modalTitleElement.count();
}
} catch (error) {
modalCount = 0;
}

while (modalCount === 0) {
await page.getByText("New Project", { exact: true }).click();
await page.waitForTimeout(3000);
modalCount = await page.getByTestId("modal-title")?.count();
}

await page.getByTestId("blank-flow").click();
await page.waitForSelector('[data-testid="extended-disclosure"]', {
timeout: 30000,
});

await expect(page.getByText("Integrations")).not.toBeVisible();
await expect(page.getByText("Notion")).not.toBeVisible();
});

0 comments on commit a88fd9b

Please sign in to comment.