The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Make localStorage and sessionStorage work in app front components (#23761)
Raphaël Bosi4923292ef100
diff --git a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdxindex d3ad9295e5d..5f5bfbc3206 100644--- a/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx+++ b/packages/twenty-docs/developers/extend/apps/layout/front-components.mdx@@ -520,6 +520,39 @@ export default defineFrontComponent({});```+### Storage++`localStorage` and `sessionStorage` work as they do in a normal page, with the standard synchronous API. Your keys are scoped to your app install and the signed-in user: no other app can read them, and another user signing into the same browser starts from an empty store. Values written to `localStorage` stay on the device across reloads; `sessionStorage` lasts for the browser session.++```tsx src/front-components/note-draft.tsx+import { useState } from 'react';+import { defineFrontComponent } from 'twenty-sdk/define';++const NoteDraft = () => {+ const [draft, setDraft] = useState(() => localStorage.getItem('draft') ?? '');++ const handleChange = (nextDraft: string) => {+ setDraft(nextDraft);+ localStorage.setItem('draft', nextDraft);+ };++ return (+ <textarea value={draft} onChange={(event) => handleChange(event.target.value)} />+ );+};++export default defineFrontComponent({+ universalIdentifier: 'd0e1f2a3-b4c5-6789-def0-890123456789',+ name: 'note-draft',+ description: 'Keeps an unsaved note on this device',+ component: NoteDraft,+});+```++Twenty stores the values on your app's behalf, so a write is applied locally right away and saved in the background. Reads never wait on the host. Nothing is synced: the values do not follow the user to another browser or machine, so use a logic function's [key-value store](/developers/extend/apps/logic/key-value-store) for anything that must survive a device change.++Writes are capped, and every limit counts characters rather than bytes: keys are at most 512 characters, a single value at most 262,144 characters, and each storage at most 1,048,576 characters per app and user. A write that breaks a limit throws a `QuotaExceededError`, like the browser API.+### Working with multiple recordsUse `useSelectedRecordIds()` to handle multiple selected records. This is useful for bulk operations:@@ -792,7 +825,7 @@ Component CSS, whether from `import './styles.css'`, CSS-in-JS or a `<style>` el### Storage and network-`localStorage`, `sessionStorage`, IndexedDB, cookies, the Cache API and `BroadcastChannel` are all unavailable, since the component runs in a worker at an opaque origin. To persist state, call a [logic function](/developers/extend/apps/logic/logic-functions) and use its [key-value store](/developers/extend/apps/logic/key-value-store).+`localStorage` and `sessionStorage` are provided by Twenty rather than the browser: the component runs in a worker at an opaque origin, so the host stores the values on your app's behalf. See [storage](#storage) for their scoping and limits. IndexedDB, cookies, the Cache API and `BroadcastChannel` remain unavailable. To persist state across devices, call a [logic function](/developers/extend/apps/logic/logic-functions) and use its [key-value store](/developers/extend/apps/logic/key-value-store).`fetch` works, with caveats:diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-copy-to-clipboard.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-copy-to-clipboard.front-component.tsxindex db4aea96fab..5af9abd1b8e 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-copy-to-clipboard.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-copy-to-clipboard.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { copyToClipboard } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiCopyToClipboardFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigate.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigate.front-component.tsxindex f902f4a00ec..38961ee0516 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigate.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-navigate.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { AppPath, navigate } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiNavigateFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-progress.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-progress.front-component.tsxindex 9ea69f18795..c7e2668c564 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-progress.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-progress.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { updateProgress } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiProgressFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-close.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-close.front-component.tsxindex ecb18d6a994..42a3626d9c6 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-close.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-close.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { closeSidePanel } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiSidePanelCloseFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-open.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-open.front-component.tsxindex daaae4b3756..304d2afa359 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-open.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-side-panel-open.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { openSidePanelPage, SidePanelPages } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiSidePanelOpenFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-snackbar.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-snackbar.front-component.tsxindex df0fad7aa21..e047dfd1f86 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-snackbar.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-snackbar.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { enqueueSnackbar } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiSnackbarFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-storage.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-storage.front-component.tsxnew file mode 100644index 00000000000..d5613164fb8--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-storage.front-component.tsx@@ -0,0 +1,112 @@+import { useState } from 'react';+import { defineFrontComponent } from 'twenty-sdk/define';++import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';++const OVERSIZED_VALUE = 'x'.repeat(300 * 1024);++const getErrorName = (error: unknown): string =>+ error instanceof Error ? error.name : String(error);++const HostApiStorageFrontComponent = () => {+ const [status, setStatus] = useState('idle');++ const runLocalStorageRoundTrip = () => {+ try {+ window.localStorage.setItem('greeting', 'hello');++ const storedValue = window.localStorage.getItem('greeting');+ const storedKey = window.localStorage.key(0);+ const storedLength = window.localStorage.length;++ window.localStorage.removeItem('greeting');++ setStatus(+ `storage:local:${storedValue}:${storedKey}:${storedLength}:${window.localStorage.length}`,+ );+ } catch (error) {+ setStatus(`storage:error:${getErrorName(error)}`);+ }+ };++ const runLocalStorageWrite = () => {+ try {+ window.localStorage.setItem('theme', 'dark');++ setStatus(`storage:local-write:${window.localStorage.getItem('theme')}`);+ } catch (error) {+ setStatus(`storage:error:${getErrorName(error)}`);+ }+ };++ const runSessionStorageRoundTrip = () => {+ try {+ window.sessionStorage.setItem('visits', '2');++ setStatus(`storage:session:${window.sessionStorage.getItem('visits')}`);+ } catch (error) {+ setStatus(`storage:error:${getErrorName(error)}`);+ }+ };++ const runOversizedWrite = () => {+ try {+ window.localStorage.setItem('oversized', OVERSIZED_VALUE);++ setStatus('storage:local:oversized');+ } catch (error) {+ setStatus(`storage:error:${getErrorName(error)}`);+ }+ };++ return (+ <FrontComponentCard title="host-api:storage">+ <button+ data-testid="subject"+ type="button"+ onClick={runLocalStorageRoundTrip}+ style={BUTTON_STYLE}+ >+ Local storage round trip+ </button>+ <button+ data-testid="local-storage-write"+ type="button"+ onClick={runLocalStorageWrite}+ style={BUTTON_STYLE}+ >+ Local storage write+ </button>+ <button+ data-testid="session-storage"+ type="button"+ onClick={runSessionStorageRoundTrip}+ style={BUTTON_STYLE}+ >+ Session storage round trip+ </button>+ <button+ data-testid="oversized"+ type="button"+ onClick={runOversizedWrite}+ style={BUTTON_STYLE}+ >+ Write oversized value+ </button>+ <span data-testid="api-status" style={STATUS_STYLE}>+ {status}+ </span>+ </FrontComponentCard>+ );+};++export default defineFrontComponent({+ universalIdentifier: 'fc-host-storage-00000000-0000-0000-0000-000000000021',+ name: 'host-api-storage-front-component',+ description: 'Front component covering the window storage shims',+ component: HostApiStorageFrontComponent,+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-unmount.front-component.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-unmount.front-component.tsxindex 88f16b3cc2a..1ead82672dc 100644--- a/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-unmount.front-component.tsx+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/host-api-unmount.front-component.tsx@@ -3,13 +3,10 @@ import { defineFrontComponent } from 'twenty-sdk/define';import { unmountFrontComponent } from 'twenty-sdk/front-component';import { FrontComponentCard } from '@/__stories__/shared/front-components/front-component-card';-import { BUTTON_STYLE } from '@/__stories__/shared/front-components/styles';--const STATUS_STYLE = {- fontSize: 13,- color: '#1f2937',- fontFamily: 'monospace',-};+import {+ BUTTON_STYLE,+ STATUS_STYLE,+} from '@/__stories__/shared/front-components/styles';const HostApiUnmountFrontComponent = () => {const [status, setStatus] = useState('idle');diff --git a/packages/twenty-front-component-renderer/src/__stories__/host-api/storage.stories.tsx b/packages/twenty-front-component-renderer/src/__stories__/host-api/storage.stories.tsxnew file mode 100644index 00000000000..2fe964e676f--- /dev/null+++ b/packages/twenty-front-component-renderer/src/__stories__/host-api/storage.stories.tsx@@ -0,0 +1,138 @@+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';+import { buildFrontComponentStorageNamespace } from '@/host/utils/buildFrontComponentStorageNamespace';+import { clearFrontComponentStorage } from '@/host/utils/clearFrontComponentStorage';+import { deleteFrontComponentStorageItem } from '@/host/utils/deleteFrontComponentStorageItem';+import { setFrontComponentStorageItem } from '@/host/utils/setFrontComponentStorageItem';+import {+ FRONT_COMPONENT_STORY_DEFAULT_ARGS,+ hostApiMocks,+ resetFrontComponentStoryMocks,+} from '@/__stories__/shared/test-utils/createFrontComponentStoryMeta';+import { expectFrontComponentMounted } from '@/__stories__/shared/test-utils/matchers/expectFrontComponentMounted';+import { runFrontComponentStory } from '@/__stories__/shared/test-utils/runFrontComponentStory';+import {+ HOST_API_TIMEOUT,+ INTERACTION_TIMEOUT,+} from '@/__stories__/shared/test-utils/timeouts';++const PERSISTED_STORAGE_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'story-application-id',+ userId: 'story-user-id',+});++const meta: Meta<typeof FrontComponentRenderer> = {+ title: 'FrontComponent/HostApi/Storage',+ component: FrontComponentRenderer,+ parameters: { layout: 'centered' },+ args: FRONT_COMPONENT_STORY_DEFAULT_ARGS,+ beforeEach: resetFrontComponentStoryMocks,+};++export default meta;++type Story = StoryObj<typeof FrontComponentRenderer>;++const roundTripStory = runFrontComponentStory({+ frontComponentBundleName: 'host-api-storage',+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expectFrontComponentMounted(canvas);++ await userEvent.click(await canvas.findByTestId('subject'));++ expect(+ await canvas.findByText(+ 'storage:local:hello:greeting:1:0',+ {},+ { timeout: INTERACTION_TIMEOUT },+ ),+ ).toBeVisible();++ await userEvent.click(await canvas.findByTestId('local-storage-write'));+ await userEvent.click(await canvas.findByTestId('session-storage'));++ await waitFor(+ () => {+ expect(+ window.localStorage.getItem(`${PERSISTED_STORAGE_NAMESPACE}greeting`),+ ).toBeNull();+ expect(+ window.localStorage.getItem(`${PERSISTED_STORAGE_NAMESPACE}theme`),+ ).toBe('dark');+ expect(+ window.sessionStorage.getItem(`${PERSISTED_STORAGE_NAMESPACE}visits`),+ ).toBe('2');+ },+ { timeout: HOST_API_TIMEOUT },+ );+ },+});++const clearPersistedStorageNamespace = () => {+ for (const storageType of ['localStorage', 'sessionStorage'] as const) {+ clearFrontComponentStorage({+ namespace: PERSISTED_STORAGE_NAMESPACE,+ storageType,+ });+ }+};++export const StorageRoundTrip: Story = {+ ...roundTripStory,+ beforeEach: () => {+ clearPersistedStorageNamespace();++ return clearPersistedStorageNamespace;+ },+ args: {+ ...roundTripStory.args,+ storageNamespace: PERSISTED_STORAGE_NAMESPACE,+ frontComponentHostCommunicationApi: {+ ...hostApiMocks,+ storageSet: async ({ storageType, key, serializedValue }) => {+ setFrontComponentStorageItem({+ namespace: PERSISTED_STORAGE_NAMESPACE,+ storageType,+ key,+ serializedValue,+ });+ },+ storageDelete: async ({ storageType, key }) => {+ deleteFrontComponentStorageItem({+ namespace: PERSISTED_STORAGE_NAMESPACE,+ storageType,+ key,+ });+ },+ storageClear: async ({ storageType }) => {+ clearFrontComponentStorage({+ namespace: PERSISTED_STORAGE_NAMESPACE,+ storageType,+ });+ },+ },+ },+};++export const StorageValueTooLarge: Story = runFrontComponentStory({+ frontComponentBundleName: 'host-api-storage',+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await expectFrontComponentMounted(canvas);++ await userEvent.click(await canvas.findByTestId('oversized'));++ expect(+ await canvas.findByText(+ 'storage:error:QuotaExceededError',+ {},+ { timeout: INTERACTION_TIMEOUT },+ ),+ ).toBeVisible();+ },+});diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/front-components/styles.ts b/packages/twenty-front-component-renderer/src/__stories__/shared/front-components/styles.tsindex 04016212ef1..51536a40b8e 100644--- a/packages/twenty-front-component-renderer/src/__stories__/shared/front-components/styles.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/front-components/styles.ts@@ -23,6 +23,12 @@ export const BUTTON_STYLE = {fontSize: 13,};+export const STATUS_STYLE = {+ fontSize: 13,+ color: '#1f2937',+ fontFamily: 'monospace',+};+export const SUBJECT_WRAPPER_STYLE = {display: 'flex',flexDirection: 'column' as const,diff --git a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.tsindex 90db4eab3a6..1d50233b6ed 100644--- a/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts+++ b/packages/twenty-front-component-renderer/src/__stories__/shared/test-utils/createFrontComponentStoryMeta.ts@@ -15,6 +15,9 @@ export const hostApiMocks = {requestAccessTokenRefresh: fn().mockResolvedValue('refreshed-token'),openCommandConfirmationModal: fn().mockResolvedValue(undefined),copyToClipboard: fn().mockResolvedValue(undefined),+ storageSet: fn().mockResolvedValue(undefined),+ storageDelete: fn().mockResolvedValue(undefined),+ storageClear: fn().mockResolvedValue(undefined),};export const FRONT_COMPONENT_STORY_DEFAULT_ARGS: NonNullable<@@ -44,4 +47,7 @@ export const resetFrontComponentStoryMocks = () => {hostApiMocks.requestAccessTokenRefresh.mockClear();hostApiMocks.openCommandConfirmationModal.mockClear();hostApiMocks.copyToClipboard.mockClear();+ hostApiMocks.storageSet.mockClear();+ hostApiMocks.storageDelete.mockClear();+ hostApiMocks.storageClear.mockClear();};diff --git a/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxKeyLength.ts b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxKeyLength.tsnew file mode 100644index 00000000000..af844b0cc33--- /dev/null+++ b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxKeyLength.ts@@ -0,0 +1 @@+export const FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH = 512;diff --git a/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxTotalLength.ts b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxTotalLength.tsnew file mode 100644index 00000000000..b4d97089868--- /dev/null+++ b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxTotalLength.ts@@ -0,0 +1 @@+export const FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH = 1024 * 1024;diff --git a/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxValueLength.ts b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxValueLength.tsnew file mode 100644index 00000000000..51d46ed8361--- /dev/null+++ b/packages/twenty-front-component-renderer/src/constants/FrontComponentStorageMaxValueLength.ts@@ -0,0 +1 @@+export const FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH = 256 * 1024;diff --git a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsxindex b7fbef0008c..90cf115b658 100644--- a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx+++ b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx@@ -36,6 +36,7 @@ type FrontComponentRendererProps = {sdkClientUrls?: SdkClientUrls;sharedDependenciesUrl?: string;applicationVariables?: Record<string, string>;+ storageNamespace?: string;executionContext: FrontComponentExecutionContext;frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi;onError: (error?: Error) => void;@@ -51,6 +52,7 @@ export const FrontComponentRenderer = ({sdkClientUrls,sharedDependenciesUrl,applicationVariables,+ storageNamespace,executionContext,frontComponentHostCommunicationApi,onError,@@ -77,6 +79,7 @@ export const FrontComponentRenderer = ({sdkClientUrls={sdkClientUrls}sharedDependenciesUrl={sharedDependenciesUrl}applicationVariables={applicationVariables}+ storageNamespace={storageNamespace}geometryTracker={geometryTracker}setReceiver={setReceiver}setThread={setThread}diff --git a/packages/twenty-front-component-renderer/src/host/constants/FrontComponentHostCommunicationApiNoop.ts b/packages/twenty-front-component-renderer/src/host/constants/FrontComponentHostCommunicationApiNoop.tsindex d8395e425a1..41fb3793cca 100644--- a/packages/twenty-front-component-renderer/src/host/constants/FrontComponentHostCommunicationApiNoop.ts+++ b/packages/twenty-front-component-renderer/src/host/constants/FrontComponentHostCommunicationApiNoop.ts@@ -13,4 +13,7 @@ export const FRONT_COMPONENT_HOST_COMMUNICATION_API_NOOP: FrontComponentHostCommcloseSidePanel: noopAsync,updateProgress: noopAsync,copyToClipboard: noopAsync,+ storageSet: noopAsync,+ storageDelete: noopAsync,+ storageClear: noopAsync,};diff --git a/packages/twenty-front-component-renderer/src/host/utils/__tests__/clearFrontComponentStorage.test.ts b/packages/twenty-front-component-renderer/src/host/utils/__tests__/clearFrontComponentStorage.test.tsnew file mode 100644index 00000000000..20d9b6e30cf--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/__tests__/clearFrontComponentStorage.test.ts@@ -0,0 +1,83 @@+import { buildFrontComponentStorageNamespace } from '../buildFrontComponentStorageNamespace';+import { clearFrontComponentStorage } from '../clearFrontComponentStorage';+import { setFrontComponentStorageItem } from '../setFrontComponentStorageItem';+import { snapshotFrontComponentStorage } from '../snapshotFrontComponentStorage';++const NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'user-id',+});++const OTHER_APPLICATION_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'other-application-id',+ userId: 'user-id',+});++const OTHER_USER_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'other-user-id',+});++describe('clearFrontComponentStorage', () => {+ beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ });++ it('should clear only within the namespace', () => {+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });++ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'locale',+ serializedValue: '"en"',+ });++ setFrontComponentStorageItem({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"light"',+ });++ setFrontComponentStorageItem({+ namespace: OTHER_USER_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"system"',+ });++ window.localStorage.setItem('unrelatedTwentyKey', 'value');++ clearFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ });++ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({});+ expect(+ snapshotFrontComponentStorage({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"light"' });+ expect(+ snapshotFrontComponentStorage({+ namespace: OTHER_USER_NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"system"' });+ expect(window.localStorage.getItem('unrelatedTwentyKey')).toBe('value');+ });+});diff --git a/packages/twenty-front-component-renderer/src/host/utils/__tests__/deleteFrontComponentStorageItem.test.ts b/packages/twenty-front-component-renderer/src/host/utils/__tests__/deleteFrontComponentStorageItem.test.tsnew file mode 100644index 00000000000..179542a64ef--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/__tests__/deleteFrontComponentStorageItem.test.ts@@ -0,0 +1,63 @@+import { buildFrontComponentStorageNamespace } from '../buildFrontComponentStorageNamespace';+import { deleteFrontComponentStorageItem } from '../deleteFrontComponentStorageItem';+import { setFrontComponentStorageItem } from '../setFrontComponentStorageItem';+import { snapshotFrontComponentStorage } from '../snapshotFrontComponentStorage';++const NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'user-id',+});++const OTHER_APPLICATION_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'other-application-id',+ userId: 'user-id',+});++describe('deleteFrontComponentStorageItem', () => {+ beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ });++ it('should delete only the namespaced entry', () => {+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });++ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'locale',+ serializedValue: '"en"',+ });++ setFrontComponentStorageItem({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"light"',+ });++ deleteFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ });++ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ locale: '"en"' });+ expect(+ snapshotFrontComponentStorage({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"light"' });+ });+});diff --git a/packages/twenty-front-component-renderer/src/host/utils/__tests__/setFrontComponentStorageItem.test.ts b/packages/twenty-front-component-renderer/src/host/utils/__tests__/setFrontComponentStorageItem.test.tsnew file mode 100644index 00000000000..f83bbcf4a90--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/__tests__/setFrontComponentStorageItem.test.ts@@ -0,0 +1,67 @@+import { FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH } from '@/constants/FrontComponentStorageMaxValueLength';+import { buildFrontComponentStorageNamespace } from '../buildFrontComponentStorageNamespace';+import { setFrontComponentStorageItem } from '../setFrontComponentStorageItem';+import { snapshotFrontComponentStorage } from '../snapshotFrontComponentStorage';++const NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'user-id',+});++describe('setFrontComponentStorageItem', () => {+ beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ });++ it('should refuse a write whose key or value is not a string', () => {+ expect(() =>+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'draft',+ serializedValue: ['value'] as unknown as string,+ }),+ ).toThrow('Storage keys and values must be strings');++ expect(() =>+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: ['draft'] as unknown as string,+ serializedValue: 'value',+ }),+ ).toThrow('Storage keys and values must be strings');++ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({});+ });++ it('should refuse a write that breaks the limits', () => {+ expect(() =>+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'draft',+ serializedValue: 'v'.repeat(+ FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH + 1,+ ),+ }),+ ).toThrow(+ expect.objectContaining({+ code: 'FRONT_COMPONENT_STORAGE_LIMIT_EXCEEDED',+ }),+ );++ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({});+ });+});diff --git a/packages/twenty-front-component-renderer/src/host/utils/__tests__/snapshotFrontComponentStorage.test.ts b/packages/twenty-front-component-renderer/src/host/utils/__tests__/snapshotFrontComponentStorage.test.tsnew file mode 100644index 00000000000..d29cf45c4cb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/__tests__/snapshotFrontComponentStorage.test.ts@@ -0,0 +1,85 @@+import { buildFrontComponentStorageNamespace } from '../buildFrontComponentStorageNamespace';+import { setFrontComponentStorageItem } from '../setFrontComponentStorageItem';+import { snapshotFrontComponentStorage } from '../snapshotFrontComponentStorage';++const NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'user-id',+});++const OTHER_APPLICATION_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'other-application-id',+ userId: 'user-id',+});++const OTHER_USER_NAMESPACE = buildFrontComponentStorageNamespace({+ applicationId: 'application-id',+ userId: 'other-user-id',+});++describe('snapshotFrontComponentStorage', () => {+ beforeEach(() => {+ window.localStorage.clear();+ window.sessionStorage.clear();+ });++ it('should snapshot only the entries of the namespace and storage type', () => {+ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });++ setFrontComponentStorageItem({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"light"',+ });++ setFrontComponentStorageItem({+ namespace: OTHER_USER_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"system"',+ });++ setFrontComponentStorageItem({+ namespace: NAMESPACE,+ storageType: 'sessionStorage',+ key: 'visits',+ serializedValue: '2',+ });++ window.localStorage.setItem('unrelatedTwentyKey', 'value');++ expect(window.localStorage.getItem(`${NAMESPACE}theme`)).toBe('"dark"');+ expect(window.sessionStorage.getItem(`${NAMESPACE}visits`)).toBe('2');++ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"dark"' });+ expect(+ snapshotFrontComponentStorage({+ namespace: NAMESPACE,+ storageType: 'sessionStorage',+ }),+ ).toEqual({ visits: '2' });+ expect(+ snapshotFrontComponentStorage({+ namespace: OTHER_APPLICATION_NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"light"' });+ expect(+ snapshotFrontComponentStorage({+ namespace: OTHER_USER_NAMESPACE,+ storageType: 'localStorage',+ }),+ ).toEqual({ theme: '"system"' });+ });+});diff --git a/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageNamespace.ts b/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageNamespace.tsnew file mode 100644index 00000000000..95a3783b58e--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageNamespace.ts@@ -0,0 +1,7 @@+export const buildFrontComponentStorageNamespace = ({+ applicationId,+ userId,+}: {+ applicationId: string;+ userId: string;+}): string => `frontComponentStorage:${applicationId}:${userId}:`;diff --git a/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageSnapshots.ts b/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageSnapshots.tsnew file mode 100644index 00000000000..04fcaaf6339--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/buildFrontComponentStorageSnapshots.ts@@ -0,0 +1,34 @@+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++import { snapshotFrontComponentStorage } from '@/host/utils/snapshotFrontComponentStorage';+import { type FrontComponentStorageSnapshots } from '@/types/FrontComponentStorageSnapshots';++const STORAGE_SNAPSHOT_FAILURE_WARNING =+ 'The front component storage could not be read from this device';++const STORAGE_TYPES: FrontComponentStorageType[] = [+ 'localStorage',+ 'sessionStorage',+];++export const buildFrontComponentStorageSnapshots = (+ namespace: string,+): FrontComponentStorageSnapshots => {+ const snapshots: FrontComponentStorageSnapshots = {+ localStorage: {},+ sessionStorage: {},+ };++ for (const storageType of STORAGE_TYPES) {+ try {+ snapshots[storageType] = snapshotFrontComponentStorage({+ namespace,+ storageType,+ });+ } catch {+ console.warn(STORAGE_SNAPSHOT_FAILURE_WARNING);+ }+ }++ return snapshots;+};diff --git a/packages/twenty-front-component-renderer/src/host/utils/clearFrontComponentStorage.ts b/packages/twenty-front-component-renderer/src/host/utils/clearFrontComponentStorage.tsnew file mode 100644index 00000000000..f189249c9bb--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/clearFrontComponentStorage.ts@@ -0,0 +1,16 @@+import { getNamespacedStorageKeys } from '@/host/utils/getNamespacedStorageKeys';+import { type FrontComponentStorageScope } from '@/types/FrontComponentStorageScope';++export const clearFrontComponentStorage = ({+ namespace,+ storageType,+}: FrontComponentStorageScope): void => {+ const storage = window[storageType];++ for (const namespacedKey of getNamespacedStorageKeys({+ storage,+ namespace,+ })) {+ storage.removeItem(namespacedKey);+ }+};diff --git a/packages/twenty-front-component-renderer/src/host/utils/deleteFrontComponentStorageItem.ts b/packages/twenty-front-component-renderer/src/host/utils/deleteFrontComponentStorageItem.tsnew file mode 100644index 00000000000..5cef4436012--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/deleteFrontComponentStorageItem.ts@@ -0,0 +1,9 @@+import { type FrontComponentStorageScope } from '@/types/FrontComponentStorageScope';++export const deleteFrontComponentStorageItem = ({+ namespace,+ storageType,+ key,+}: FrontComponentStorageScope & { key: string }): void => {+ window[storageType].removeItem(`${namespace}${key}`);+};diff --git a/packages/twenty-front-component-renderer/src/host/utils/getNamespacedStorageKeys.ts b/packages/twenty-front-component-renderer/src/host/utils/getNamespacedStorageKeys.tsnew file mode 100644index 00000000000..6b58c2c38f0--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/getNamespacedStorageKeys.ts@@ -0,0 +1,21 @@+import { isDefined } from 'twenty-shared/utils';++export const getNamespacedStorageKeys = ({+ storage,+ namespace,+}: {+ storage: Storage;+ namespace: string;+}): string[] => {+ const namespacedKeys: string[] = [];++ for (let index = 0; index < storage.length; index++) {+ const storageKey = storage.key(index);++ if (isDefined(storageKey) && storageKey.startsWith(namespace)) {+ namespacedKeys.push(storageKey);+ }+ }++ return namespacedKeys;+};diff --git a/packages/twenty-front-component-renderer/src/host/utils/setFrontComponentStorageItem.ts b/packages/twenty-front-component-renderer/src/host/utils/setFrontComponentStorageItem.tsnew file mode 100644index 00000000000..7d955c83276--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/setFrontComponentStorageItem.ts@@ -0,0 +1,56 @@+import { isString } from '@sniptt/guards';+import { CustomError, isDefined } from 'twenty-shared/utils';++import { getNamespacedStorageKeys } from '@/host/utils/getNamespacedStorageKeys';+import { type FrontComponentStorageScope } from '@/types/FrontComponentStorageScope';+import { getFrontComponentStorageViolationMessage } from '@/utils/getFrontComponentStorageViolationMessage';++export const setFrontComponentStorageItem = ({+ namespace,+ storageType,+ key,+ serializedValue,+}: FrontComponentStorageScope & {+ key: string;+ serializedValue: string;+}): void => {+ if (!isString(key) || !isString(serializedValue)) {+ throw new CustomError(+ 'Storage keys and values must be strings',+ 'FRONT_COMPONENT_STORAGE_INVALID_INPUT',+ );+ }++ const storage = window[storageType];+ const namespacedKey = `${namespace}${key}`;++ let otherEntriesTotalLength = 0;++ for (const existingNamespacedKey of getNamespacedStorageKeys({+ storage,+ namespace,+ })) {+ if (existingNamespacedKey !== namespacedKey) {+ const existingKeyLength = existingNamespacedKey.length - namespace.length;+ const existingValueLength =+ storage.getItem(existingNamespacedKey)?.length ?? 0;++ otherEntriesTotalLength += existingKeyLength + existingValueLength;+ }+ }++ const violationMessage = getFrontComponentStorageViolationMessage({+ key,+ serializedValue,+ otherEntriesTotalLength,+ });++ if (isDefined(violationMessage)) {+ throw new CustomError(+ violationMessage,+ 'FRONT_COMPONENT_STORAGE_LIMIT_EXCEEDED',+ );+ }++ storage.setItem(namespacedKey, serializedValue);+};diff --git a/packages/twenty-front-component-renderer/src/host/utils/snapshotFrontComponentStorage.ts b/packages/twenty-front-component-renderer/src/host/utils/snapshotFrontComponentStorage.tsnew file mode 100644index 00000000000..99456d0d213--- /dev/null+++ b/packages/twenty-front-component-renderer/src/host/utils/snapshotFrontComponentStorage.ts@@ -0,0 +1,16 @@+import { getNamespacedStorageKeys } from '@/host/utils/getNamespacedStorageKeys';+import { type FrontComponentStorageScope } from '@/types/FrontComponentStorageScope';++export const snapshotFrontComponentStorage = ({+ namespace,+ storageType,+}: FrontComponentStorageScope): Record<string, string> => {+ const storage = window[storageType];++ return Object.fromEntries(+ getNamespacedStorageKeys({ storage, namespace }).map((namespacedKey) => [+ namespacedKey.slice(namespace.length),+ storage.getItem(namespacedKey) ?? '',+ ]),+ );+};diff --git a/packages/twenty-front-component-renderer/src/index.ts b/packages/twenty-front-component-renderer/src/index.tsindex 43f31bd35f7..5a674e8d02e 100644--- a/packages/twenty-front-component-renderer/src/index.ts+++ b/packages/twenty-front-component-renderer/src/index.ts@@ -134,6 +134,10 @@ export { installStyleBridge } from './polyfills/installStyleBridge';export { exposeGlobals } from './remote/utils/exposeGlobals';export type { FrontComponentExecutionContext } from 'twenty-sdk/front-component';export type { FrontComponentHostCommunicationApi } from './types/FrontComponentHostCommunicationApi';+export { setFrontComponentStorageItem } from './host/utils/setFrontComponentStorageItem';+export { deleteFrontComponentStorageItem } from './host/utils/deleteFrontComponentStorageItem';+export { clearFrontComponentStorage } from './host/utils/clearFrontComponentStorage';+export { buildFrontComponentStorageNamespace } from './host/utils/buildFrontComponentStorageNamespace';export type { ElementGeometrySnapshot } from './types/ElementGeometrySnapshot';export type { ViewportGeometrySnapshot } from './types/ViewportGeometrySnapshot';export type { GeometryUpdateBatch } from './types/GeometryUpdateBatch';diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/constants/StoragePersistenceFailureWarning.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/constants/StoragePersistenceFailureWarning.tsnew file mode 100644index 00000000000..803ba3507a6--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/constants/StoragePersistenceFailureWarning.ts@@ -0,0 +1,2 @@+export const STORAGE_PERSISTENCE_FAILURE_WARNING =+ 'A front component storage write could not be persisted';diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/frontComponentStorageBridges.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/frontComponentStorageBridges.tsnew file mode 100644index 00000000000..b6babe1b302--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/frontComponentStorageBridges.ts@@ -0,0 +1,16 @@+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++import { createFrontComponentStorageBridge } from '@/polyfills/storage/utils/createFrontComponentStorageBridge';+import { type FrontComponentStorageBridge } from '@/polyfills/storage/types/FrontComponentStorageBridge';++export const frontComponentStorageBridges: Record<+ FrontComponentStorageType,+ FrontComponentStorageBridge+> = {+ localStorage: createFrontComponentStorageBridge({+ storageType: 'localStorage',+ }),+ sessionStorage: createFrontComponentStorageBridge({+ storageType: 'sessionStorage',+ }),+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/types/FrontComponentStorageBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/types/FrontComponentStorageBridge.tsnew file mode 100644index 00000000000..2919b619588--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/types/FrontComponentStorageBridge.ts@@ -0,0 +1,14 @@+import { type FrontComponentHostCommunicationApiStore } from '@/types/FrontComponentHostCommunicationApiStore';++export type FrontComponentStorageBridge = {+ getItem: (key: string) => string | null;+ getKeyAtIndex: (index: number) => string | null;+ getLength: () => number;+ setItem: (key: string, serializedValue: string) => void;+ removeItem: (key: string) => void;+ clear: () => void;+ seed: (seededEntries: Record<string, string>) => void;+ connectHostCommunicationApi: (+ hostCommunicationApi: FrontComponentHostCommunicationApiStore,+ ) => void;+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/createFrontComponentStorageBridge.test.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/createFrontComponentStorageBridge.test.tsnew file mode 100644index 00000000000..ca615f45728--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/createFrontComponentStorageBridge.test.ts@@ -0,0 +1,149 @@+import { FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH } from '@/constants/FrontComponentStorageMaxKeyLength';+import { createFrontComponentStorageBridge } from '../createFrontComponentStorageBridge';++const createHostCommunicationApiStub = () => ({+ storageSet: jest.fn(async () => {}),+ storageDelete: jest.fn(async () => {}),+ storageClear: jest.fn(async () => {}),+});++const createConnectedBridge = () => {+ const hostCommunicationApi = createHostCommunicationApiStub();++ const bridge = createFrontComponentStorageBridge({+ storageType: 'localStorage',+ });++ bridge.connectHostCommunicationApi(hostCommunicationApi);++ return { hostCommunicationApi, bridge };+};++const flushPendingPromises = () =>+ new Promise((resolve) => setTimeout(resolve, 0));++describe('createFrontComponentStorageBridge', () => {+ it('should enumerate keys in insertion order across mutations', () => {+ const { bridge } = createConnectedBridge();++ bridge.seed({ theme: '"dark"', draft: '"hello"' });++ const enumerateKeys = () =>+ Array.from({ length: bridge.getLength() }, (_unused, index) =>+ bridge.getKeyAtIndex(index),+ );++ expect(enumerateKeys()).toEqual(['theme', 'draft']);+ expect(bridge.getItem('theme')).toBe('"dark"');+ expect(bridge.getItem('missing')).toBeNull();++ bridge.setItem('locale', '"en"');++ expect(enumerateKeys()).toEqual(['theme', 'draft', 'locale']);++ bridge.removeItem('theme');++ expect(enumerateKeys()).toEqual(['draft', 'locale']);++ bridge.setItem('draft', '"updated"');++ expect(enumerateKeys()).toEqual(['draft', 'locale']);++ bridge.clear();++ expect(enumerateKeys()).toEqual([]);+ expect(bridge.getKeyAtIndex(0)).toBeNull();+ });++ it('should apply writes locally and persist them with the storage type', () => {+ const { bridge, hostCommunicationApi } = createConnectedBridge();++ bridge.setItem('theme', '"dark"');++ expect(bridge.getItem('theme')).toBe('"dark"');+ expect(hostCommunicationApi.storageSet).toHaveBeenCalledWith({+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });+ });++ it('should persist deletions and clears with the storage type', () => {+ const { bridge, hostCommunicationApi } = createConnectedBridge();++ bridge.seed({ theme: '"dark"', draft: '"hello"' });++ bridge.removeItem('theme');++ expect(bridge.getItem('theme')).toBeNull();+ expect(hostCommunicationApi.storageDelete).toHaveBeenCalledWith({+ storageType: 'localStorage',+ key: 'theme',+ });++ bridge.clear();++ expect(bridge.getLength()).toBe(0);+ expect(hostCommunicationApi.storageClear).toHaveBeenCalledWith({+ storageType: 'localStorage',+ });+ });++ it('should queue writes until the host communication api is connected', () => {+ const bridge = createFrontComponentStorageBridge({+ storageType: 'localStorage',+ });++ bridge.setItem('theme', '"dark"');++ expect(bridge.getItem('theme')).toBe('"dark"');++ const hostCommunicationApi = createHostCommunicationApiStub();++ bridge.connectHostCommunicationApi(hostCommunicationApi);++ expect(hostCommunicationApi.storageSet).toHaveBeenCalledWith({+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });+ });++ it('should reject an oversized key without caching or persisting it', () => {+ const { bridge, hostCommunicationApi } = createConnectedBridge();++ const oversizedKey = 'k'.repeat(FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH + 1);++ expect(() => bridge.setItem(oversizedKey, '"a"')).toThrow(+ expect.objectContaining({ name: 'QuotaExceededError' }),+ );+ expect(bridge.getItem(oversizedKey)).toBeNull();+ expect(hostCommunicationApi.storageSet).not.toHaveBeenCalled();+ });++ it('should keep the local write when the host refuses it', async () => {+ const consoleWarnSpy = jest+ .spyOn(console, 'warn')+ .mockImplementation(() => {});++ const hostCommunicationApi = createHostCommunicationApiStub();+ hostCommunicationApi.storageSet.mockRejectedValue(+ new Error('Device storage is unavailable'),+ );++ const bridge = createFrontComponentStorageBridge({+ storageType: 'localStorage',+ });++ bridge.connectHostCommunicationApi(hostCommunicationApi);++ bridge.setItem('theme', '"dark"');++ await flushPendingPromises();++ expect(bridge.getItem('theme')).toBe('"dark"');+ expect(consoleWarnSpy).toHaveBeenCalled();++ consoleWarnSpy.mockRestore();+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/installStorageBridge.test.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/installStorageBridge.test.tsnew file mode 100644index 00000000000..b82be2c8885--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/__tests__/installStorageBridge.test.ts@@ -0,0 +1,48 @@+import { createFrontComponentStorageBridge } from '../createFrontComponentStorageBridge';+import { installStorageBridge } from '../installStorageBridge';++const createStorageBridges = () => ({+ localStorage: createFrontComponentStorageBridge({+ storageType: 'localStorage',+ }),+ sessionStorage: createFrontComponentStorageBridge({+ storageType: 'sessionStorage',+ }),+});++describe('installStorageBridge', () => {+ it('should install both storages on the global scope and a distinct window', () => {+ const polyfillWindow: Record<string, unknown> = {};+ const globalScope: Record<string, unknown> = { window: polyfillWindow };++ installStorageBridge({+ globalScope,+ storageBridges: createStorageBridges(),+ });++ expect(globalScope.localStorage).toBe(polyfillWindow.localStorage);+ expect(globalScope.sessionStorage).toBe(polyfillWindow.sessionStorage);+ expect(globalScope.localStorage).not.toBe(globalScope.sessionStorage);+ });++ it('should back each installed storage by its own bridge', () => {+ const globalScope: Record<string, unknown> = {};+ const storageBridges = createStorageBridges();++ storageBridges.localStorage.seed({ theme: '"dark"' });++ installStorageBridge({ globalScope, storageBridges });++ const localStorage = globalScope.localStorage as Storage;+ const sessionStorage = globalScope.sessionStorage as Storage;++ expect(localStorage.getItem('theme')).toBe('"dark"');+ expect(sessionStorage.getItem('theme')).toBeNull();++ sessionStorage.setItem('visits', '2');++ expect(storageBridges.sessionStorage.getItem('visits')).toBe('2');+ expect(storageBridges.localStorage.getItem('visits')).toBeNull();+ expect(localStorage.length).toBe(1);+ });+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createFrontComponentStorageBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createFrontComponentStorageBridge.tsnew file mode 100644index 00000000000..4275422185f--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createFrontComponentStorageBridge.ts@@ -0,0 +1,130 @@+import { isDefined } from 'twenty-shared/utils';+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++import { STORAGE_PERSISTENCE_FAILURE_WARNING } from '@/polyfills/storage/constants/StoragePersistenceFailureWarning';+import { type FrontComponentStorageBridge } from '@/polyfills/storage/types/FrontComponentStorageBridge';+import { type FrontComponentHostCommunicationApiStore } from '@/types/FrontComponentHostCommunicationApiStore';+import { getFrontComponentStorageViolationMessage } from '@/utils/getFrontComponentStorageViolationMessage';++export const createFrontComponentStorageBridge = ({+ storageType,+}: {+ storageType: FrontComponentStorageType;+}): FrontComponentStorageBridge => {+ const entries = new Map<string, string>();+ const pendingPersistOperations: (() => void)[] = [];++ let hostCommunicationApi: FrontComponentHostCommunicationApiStore | null =+ null;+ let cachedKeys: string[] | null = null;++ const getKeys = (): string[] => {+ cachedKeys ??= Array.from(entries.keys());++ return cachedKeys;+ };++ const runPersist = (+ persistOperation: (+ connectedHostCommunicationApi: FrontComponentHostCommunicationApiStore,+ ) => Promise<void> | undefined,+ ): void => {+ if (!isDefined(hostCommunicationApi)) {+ return;+ }++ persistOperation(hostCommunicationApi)?.catch(() => {+ console.warn(STORAGE_PERSISTENCE_FAILURE_WARNING);+ });+ };++ const persist = (+ persistOperation: (+ connectedHostCommunicationApi: FrontComponentHostCommunicationApiStore,+ ) => Promise<void> | undefined,+ ): void => {+ if (isDefined(hostCommunicationApi)) {+ runPersist(persistOperation);++ return;+ }++ pendingPersistOperations.push(() => runPersist(persistOperation));+ };++ const getOtherEntriesTotalLength = (excludedKey: string): number => {+ let totalLength = 0;++ for (const [key, value] of entries) {+ if (key !== excludedKey) {+ totalLength += key.length + value.length;+ }+ }++ return totalLength;+ };++ return {+ getItem: (key) => entries.get(key) ?? null,+ getKeyAtIndex: (index) => getKeys()[index] ?? null,+ getLength: () => entries.size,++ seed: (seededEntries) => {+ entries.clear();+ cachedKeys = null;++ for (const [key, value] of Object.entries(seededEntries)) {+ entries.set(key, value);+ }+ },++ setItem: (key, serializedValue) => {+ const violationMessage = getFrontComponentStorageViolationMessage({+ key,+ serializedValue,+ otherEntriesTotalLength: getOtherEntriesTotalLength(key),+ });++ if (isDefined(violationMessage)) {+ throw new DOMException(violationMessage, 'QuotaExceededError');+ }++ entries.set(key, serializedValue);+ cachedKeys = null;++ persist((connectedHostCommunicationApi) =>+ connectedHostCommunicationApi.storageSet?.({+ storageType,+ key,+ serializedValue,+ }),+ );+ },++ removeItem: (key) => {+ entries.delete(key);+ cachedKeys = null;++ persist((connectedHostCommunicationApi) =>+ connectedHostCommunicationApi.storageDelete?.({ storageType, key }),+ );+ },++ clear: () => {+ entries.clear();+ cachedKeys = null;++ persist((connectedHostCommunicationApi) =>+ connectedHostCommunicationApi.storageClear?.({ storageType }),+ );+ },++ connectHostCommunicationApi: (nextHostCommunicationApi) => {+ hostCommunicationApi = nextHostCommunicationApi;++ for (const operation of pendingPersistOperations.splice(0)) {+ operation();+ }+ },+ };+};diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createStorageFromFrontComponentStorageBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createStorageFromFrontComponentStorageBridge.tsnew file mode 100644index 00000000000..ccd7f3b7df3--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/createStorageFromFrontComponentStorageBridge.ts@@ -0,0 +1,15 @@+import { type FrontComponentStorageBridge } from '@/polyfills/storage/types/FrontComponentStorageBridge';++export const createStorageFromFrontComponentStorageBridge = (+ bridge: FrontComponentStorageBridge,+): Storage => ({+ get length() {+ return bridge.getLength();+ },+ key: (index: number) => bridge.getKeyAtIndex(index),+ getItem: (key: string) => bridge.getItem(String(key)),+ setItem: (key: string, value: string) =>+ bridge.setItem(String(key), String(value)),+ removeItem: (key: string) => bridge.removeItem(String(key)),+ clear: () => bridge.clear(),+});diff --git a/packages/twenty-front-component-renderer/src/polyfills/storage/utils/installStorageBridge.ts b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/installStorageBridge.tsnew file mode 100644index 00000000000..67a1c805a0b--- /dev/null+++ b/packages/twenty-front-component-renderer/src/polyfills/storage/utils/installStorageBridge.ts@@ -0,0 +1,30 @@+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++import { createStorageFromFrontComponentStorageBridge } from '@/polyfills/storage/utils/createStorageFromFrontComponentStorageBridge';+import { type FrontComponentStorageBridge } from '@/polyfills/storage/types/FrontComponentStorageBridge';+import { resolveGlobalScopeInstallTargets } from '@/polyfills/utils/resolveGlobalScopeInstallTargets';++type InstallStorageBridgeInput = {+ globalScope: Record<string, unknown>;+ storageBridges: Record<+ FrontComponentStorageType,+ FrontComponentStorageBridge+ >;+};++export const installStorageBridge = ({+ globalScope,+ storageBridges,+}: InstallStorageBridgeInput): void => {+ const localStorage = createStorageFromFrontComponentStorageBridge(+ storageBridges.localStorage,+ );+ const sessionStorage = createStorageFromFrontComponentStorageBridge(+ storageBridges.sessionStorage,+ );++ for (const installTarget of resolveGlobalScopeInstallTargets(globalScope)) {+ installTarget.localStorage = localStorage;+ installTarget.sessionStorage = sessionStorage;+ }+};diff --git a/packages/twenty-front-component-renderer/src/remote/components/FrontComponentWorkerEffect.tsx b/packages/twenty-front-component-renderer/src/remote/components/FrontComponentWorkerEffect.tsxindex 840248d19e8..a8b28d9909e 100644--- a/packages/twenty-front-component-renderer/src/remote/components/FrontComponentWorkerEffect.tsx+++ b/packages/twenty-front-component-renderer/src/remote/components/FrontComponentWorkerEffect.tsx@@ -9,6 +9,7 @@ import { createHostFetchEnforcingPolicy } from '@/host/utils/createHostFetchEnfoimport { type GeometryTracker } from '@/host/types/GeometryTracker';import { fetchComponentSource } from '@/host/utils/fetchComponentSource';import { fetchSdkClientSources } from '@/host/utils/fetchSdkClientSources';+import { buildFrontComponentStorageSnapshots } from '@/host/utils/buildFrontComponentStorageSnapshots';import { FRONT_COMPONENT_SANDBOX_DOCUMENT } from '@/remote/sandbox/generated/frontComponentSandboxDocument';import { createFrontComponentSandboxIframe } from '@/remote/sandbox/utils/createFrontComponentSandboxIframe';import { createFrontComponentSandboxMessageHandler } from '@/remote/sandbox/utils/createFrontComponentSandboxMessageHandler';@@ -26,6 +27,7 @@ type FrontComponentWorkerEffectProps = {sdkClientUrls?: SdkClientUrls;sharedDependenciesUrl?: string;applicationVariables?: Record<string, string>;+ storageNamespace?: string;geometryTracker: GeometryTracker;setReceiver: React.Dispatch<React.SetStateAction<RemoteReceiver | null>>;setThread: React.Dispatch<React.SetStateAction<FrontComponentThread | null>>;@@ -40,6 +42,7 @@ export const FrontComponentWorkerEffect = ({sdkClientUrls,sharedDependenciesUrl,applicationVariables,+ storageNamespace,geometryTracker,setReceiver,setThread,@@ -125,6 +128,10 @@ export const FrontComponentWorkerEffect = ({return;}+ const storageSnapshots = isDefined(storageNamespace)+ ? buildFrontComponentStorageSnapshots(storageNamespace)+ : undefined;+await thread.imports.render(newReceiver.connection, {componentUrl,componentSource,@@ -136,6 +143,7 @@ export const FrontComponentWorkerEffect = ({hostFetchOrigins: hostFetchPolicy.allowedOrigins,applicationVariables,initialViewportGeometry: geometryTracker.getViewportGeometry(),+ storageSnapshots,});} catch (error) {if (!isCancelled) {@@ -165,6 +173,7 @@ export const FrontComponentWorkerEffect = ({sdkClientUrls,sharedDependenciesUrl,applicationVariables,+ storageNamespace,geometryTracker,setError,setReceiver,diff --git a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.tsindex c543fb6647d..b2205e164ff 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/remote-worker.ts@@ -17,6 +17,8 @@ import { installMutationObserver } from '@/polyfills/dom/utils/installMutationObimport { workerGeometryStore } from '@/polyfills/geometry/workerGeometryStore';import { installElementGeometryPolyfill } from '@/polyfills/geometry/utils/installElementGeometryPolyfill';import { installWindowGeometryPolyfill } from '@/polyfills/geometry/utils/installWindowGeometryPolyfill';+import { frontComponentStorageBridges } from '@/polyfills/storage/frontComponentStorageBridges';+import { installStorageBridge } from '@/polyfills/storage/utils/installStorageBridge';import { exposeGlobals } from '@/remote/utils/exposeGlobals';import { installStylePropertyOnRemoteElements } from '@/remote/utils/installStylePropertyOnRemoteElements';import { patchRemoteElementAttributes } from '@/remote/utils/patchRemoteElementAttributes';@@ -56,6 +58,11 @@ installWindowGeometryPolyfill({geometryStore: workerGeometryStore,});+installStorageBridge({+ globalScope: globalThis as unknown as Record<string, unknown>,+ storageBridges: frontComponentStorageBridges,+});+exposeGlobals({__HTML_TAG_TO_CUSTOM_ELEMENT_TAG__: HTML_TAG_TO_CUSTOM_ELEMENT_TAG,});@@ -81,6 +88,12 @@ const workerExports: WorkerExports = {hostThread.imports,),);++ for (const storageBridge of Object.values(frontComponentStorageBridges)) {+ storageBridge.connectHostCommunicationApi(+ frontComponentHostCommunicationApi,+ );+ }},updateContext: async (context) => {setFrontComponentExecutionContext(context);diff --git a/packages/twenty-front-component-renderer/src/remote/worker/utils/__tests__/buildFrontComponentHostCommunicationApiFromThreadImports.test.ts b/packages/twenty-front-component-renderer/src/remote/worker/utils/__tests__/buildFrontComponentHostCommunicationApiFromThreadImports.test.tsindex 20e2cfabcab..377968fd580 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/utils/__tests__/buildFrontComponentHostCommunicationApiFromThreadImports.test.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/utils/__tests__/buildFrontComponentHostCommunicationApiFromThreadImports.test.ts@@ -13,6 +13,9 @@ const createHostThreadImportsStub = () =>closeSidePanel: jest.fn(),updateProgress: jest.fn(),copyToClipboard: jest.fn(),+ storageSet: jest.fn(),+ storageDelete: jest.fn(),+ storageClear: jest.fn(),hostFetch: jest.fn(),}) as unknown as FrontComponentHostThreadExports;@@ -37,6 +40,9 @@ describe('buildFrontComponentHostCommunicationApiFromThreadImports', () => {'openCommandConfirmationModal','openSidePanelPage','requestAccessTokenRefresh',+ 'storageClear',+ 'storageDelete',+ 'storageSet','unmountFrontComponent','updateProgress',]);@@ -62,6 +68,13 @@ describe('buildFrontComponentHostCommunicationApiFromThreadImports', () => {expect(hostCommunicationApi.copyToClipboard).toBe(hostThreadImports.copyToClipboard,);+ expect(hostCommunicationApi.storageSet).toBe(hostThreadImports.storageSet);+ expect(hostCommunicationApi.storageDelete).toBe(+ hostThreadImports.storageDelete,+ );+ expect(hostCommunicationApi.storageClear).toBe(+ hostThreadImports.storageClear,+ );});it('should wrap openCommandConfirmationModal with the confirmation modal adapter', async () => {diff --git a/packages/twenty-front-component-renderer/src/remote/worker/utils/buildFrontComponentHostCommunicationApiFromThreadImports.ts b/packages/twenty-front-component-renderer/src/remote/worker/utils/buildFrontComponentHostCommunicationApiFromThreadImports.tsindex 1a9a0e6aeba..1a10bb452f3 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/utils/buildFrontComponentHostCommunicationApiFromThreadImports.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/utils/buildFrontComponentHostCommunicationApiFromThreadImports.ts@@ -15,4 +15,7 @@ export const buildFrontComponentHostCommunicationApiFromThreadImports = (closeSidePanel: hostThreadImports.closeSidePanel,updateProgress: hostThreadImports.updateProgress,copyToClipboard: hostThreadImports.copyToClipboard,+ storageSet: hostThreadImports.storageSet,+ storageDelete: hostThreadImports.storageDelete,+ storageClear: hostThreadImports.storageClear,});diff --git a/packages/twenty-front-component-renderer/src/remote/worker/utils/renderFrontComponent.ts b/packages/twenty-front-component-renderer/src/remote/worker/utils/renderFrontComponent.tsindex 3d60b1122eb..5b7e8b17251 100644--- a/packages/twenty-front-component-renderer/src/remote/worker/utils/renderFrontComponent.ts+++ b/packages/twenty-front-component-renderer/src/remote/worker/utils/renderFrontComponent.ts@@ -2,6 +2,7 @@ import { type RemoteConnection } from '@remote-dom/core/elements';import { CustomError, isDefined } from 'twenty-shared/utils';import { workerGeometryStore } from '@/polyfills/geometry/workerGeometryStore';+import { frontComponentStorageBridges } from '@/polyfills/storage/frontComponentStorageBridges';import { attachRemoteRenderRootToWorkerDocument } from '@/remote/worker/utils/attachRemoteRenderRootToWorkerDocument';import { installHostFetchProxy } from '@/remote/worker/utils/installHostFetchProxy';import { loadFrontComponentModule } from '@/remote/worker/utils/loadFrontComponentModule';@@ -39,6 +40,17 @@ export const renderFrontComponent = async ({});}+ const storageSnapshots = renderContext.storageSnapshots;++ if (isDefined(storageSnapshots)) {+ frontComponentStorageBridges.localStorage.seed(+ storageSnapshots.localStorage,+ );+ frontComponentStorageBridges.sessionStorage.seed(+ storageSnapshots.sessionStorage,+ );+ }+const componentModule = await loadFrontComponentModule({componentSource: renderContext.componentSource,sdkClientSources: renderContext.sdkClientSources,diff --git a/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApi.ts b/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApi.tsindex 960f860a488..2213f1b052c 100644--- a/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApi.ts+++ b/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApi.ts@@ -6,6 +6,9 @@ import {type OpenCommandConfirmationModalHostFunction,type OpenSidePanelPageFunction,type RequestAccessTokenRefreshFunction,+ type StorageClearFunction,+ type StorageDeleteFunction,+ type StorageSetFunction,type UnmountFrontComponentFunction,type UpdateProgressFunction,} from 'twenty-sdk/front-component';@@ -20,4 +23,7 @@ export type FrontComponentHostCommunicationApi = {closeSidePanel: CloseSidePanelFunction;updateProgress: UpdateProgressFunction;copyToClipboard: CopyToClipboardFunction;+ storageSet: StorageSetFunction;+ storageDelete: StorageDeleteFunction;+ storageClear: StorageClearFunction;};diff --git a/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApiStore.ts b/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApiStore.tsindex fef60fd7a88..b35fb3f484e 100644--- a/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApiStore.ts+++ b/packages/twenty-front-component-renderer/src/types/FrontComponentHostCommunicationApiStore.ts@@ -6,6 +6,9 @@ import {type OpenCommandConfirmationModalFunction,type OpenSidePanelPageFunction,type RequestAccessTokenRefreshFunction,+ type StorageClearFunction,+ type StorageDeleteFunction,+ type StorageSetFunction,type UnmountFrontComponentFunction,type UpdateProgressFunction,} from 'twenty-sdk/front-component';@@ -20,4 +23,7 @@ export type FrontComponentHostCommunicationApiStore = {closeSidePanel?: CloseSidePanelFunction;updateProgress?: UpdateProgressFunction;copyToClipboard?: CopyToClipboardFunction;+ storageSet?: StorageSetFunction;+ storageDelete?: StorageDeleteFunction;+ storageClear?: StorageClearFunction;};diff --git a/packages/twenty-front-component-renderer/src/types/FrontComponentStorageScope.ts b/packages/twenty-front-component-renderer/src/types/FrontComponentStorageScope.tsnew file mode 100644index 00000000000..b9eeaea837a--- /dev/null+++ b/packages/twenty-front-component-renderer/src/types/FrontComponentStorageScope.ts@@ -0,0 +1,6 @@+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++export type FrontComponentStorageScope = {+ namespace: string;+ storageType: FrontComponentStorageType;+};diff --git a/packages/twenty-front-component-renderer/src/types/FrontComponentStorageSnapshots.ts b/packages/twenty-front-component-renderer/src/types/FrontComponentStorageSnapshots.tsnew file mode 100644index 00000000000..1656e7ba831--- /dev/null+++ b/packages/twenty-front-component-renderer/src/types/FrontComponentStorageSnapshots.ts@@ -0,0 +1,6 @@+import { type FrontComponentStorageType } from 'twenty-sdk/front-component';++export type FrontComponentStorageSnapshots = Record<+ FrontComponentStorageType,+ Record<string, string>+>;diff --git a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.tsindex d1b828038cd..cd3bf3dad43 100644--- a/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts+++ b/packages/twenty-front-component-renderer/src/types/HostToWorkerRenderContext.ts@@ -1,3 +1,4 @@+import { type FrontComponentStorageSnapshots } from '@/types/FrontComponentStorageSnapshots';import { type SdkClientSources } from '@/types/SdkClientSources';import { type ViewportGeometrySnapshot } from '@/types/ViewportGeometrySnapshot';@@ -12,4 +13,5 @@ export type HostToWorkerRenderContext = {hostFetchOrigins?: string[];applicationVariables?: Record<string, string>;initialViewportGeometry?: ViewportGeometrySnapshot;+ storageSnapshots?: FrontComponentStorageSnapshots;};diff --git a/packages/twenty-front-component-renderer/src/utils/__tests__/getFrontComponentStorageViolationMessage.test.ts b/packages/twenty-front-component-renderer/src/utils/__tests__/getFrontComponentStorageViolationMessage.test.tsnew file mode 100644index 00000000000..ab1d28b3d35--- /dev/null+++ b/packages/twenty-front-component-renderer/src/utils/__tests__/getFrontComponentStorageViolationMessage.test.ts@@ -0,0 +1,56 @@+import { FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH } from '@/constants/FrontComponentStorageMaxKeyLength';+import { FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH } from '@/constants/FrontComponentStorageMaxTotalLength';+import { FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH } from '@/constants/FrontComponentStorageMaxValueLength';+import { getFrontComponentStorageViolationMessage } from '../getFrontComponentStorageViolationMessage';++describe('getFrontComponentStorageViolationMessage', () => {+ it('should return null for an entry that fits', () => {+ expect(+ getFrontComponentStorageViolationMessage({+ key: 'theme',+ serializedValue: '"dark"',+ otherEntriesTotalLength: 0,+ }),+ ).toBeNull();+ });++ it('should reject a key longer than the limit', () => {+ expect(+ getFrontComponentStorageViolationMessage({+ key: 'k'.repeat(FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH + 1),+ serializedValue: '"dark"',+ otherEntriesTotalLength: 0,+ }),+ ).toContain('Storage keys cannot exceed');+ });++ it('should reject a value longer than the limit', () => {+ expect(+ getFrontComponentStorageViolationMessage({+ key: 'draft',+ serializedValue: 'v'.repeat(+ FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH + 1,+ ),+ otherEntriesTotalLength: 0,+ }),+ ).toContain('Storage values cannot exceed');+ });++ it('should count the key length toward the total quota', () => {+ expect(+ getFrontComponentStorageViolationMessage({+ key: 'a',+ serializedValue: 'v',+ otherEntriesTotalLength: FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH - 2,+ }),+ ).toBeNull();++ expect(+ getFrontComponentStorageViolationMessage({+ key: 'a',+ serializedValue: 'v',+ otherEntriesTotalLength: FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH - 1,+ }),+ ).toContain('Storage quota');+ });+});diff --git a/packages/twenty-front-component-renderer/src/utils/getFrontComponentStorageViolationMessage.ts b/packages/twenty-front-component-renderer/src/utils/getFrontComponentStorageViolationMessage.tsnew file mode 100644index 00000000000..4ff14812eec--- /dev/null+++ b/packages/twenty-front-component-renderer/src/utils/getFrontComponentStorageViolationMessage.ts@@ -0,0 +1,30 @@+import { FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH } from '@/constants/FrontComponentStorageMaxKeyLength';+import { FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH } from '@/constants/FrontComponentStorageMaxTotalLength';+import { FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH } from '@/constants/FrontComponentStorageMaxValueLength';++export const getFrontComponentStorageViolationMessage = ({+ key,+ serializedValue,+ otherEntriesTotalLength,+}: {+ key: string;+ serializedValue: string;+ otherEntriesTotalLength: number;+}): string | null => {+ if (key.length > FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH) {+ return `Storage keys cannot exceed ${FRONT_COMPONENT_STORAGE_MAX_KEY_LENGTH} characters`;+ }++ if (serializedValue.length > FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH) {+ return `Storage values cannot exceed ${FRONT_COMPONENT_STORAGE_MAX_VALUE_LENGTH} characters`;+ }++ if (+ otherEntriesTotalLength + key.length + serializedValue.length >+ FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH+ ) {+ return `Storage quota of ${FRONT_COMPONENT_STORAGE_MAX_TOTAL_LENGTH} characters exceeded`;+ }++ return null;+};diff --git a/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx b/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsxindex a2290c0d160..f1638ea8691 100644--- a/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx+++ b/packages/twenty-front/src/modules/front-components/components/FrontComponentRenderer.tsx@@ -88,13 +88,17 @@ const FrontComponentRendererContent = ({frontComponentSharedDependenciesChecksum,} = frontComponent;- const { executionContext, frontComponentHostCommunicationApi } =- useFrontComponentExecutionContext({- frontComponentId,- commandMenuItemId,- selectedRecordIds,- colorScheme,- });+ const {+ executionContext,+ frontComponentHostCommunicationApi,+ storageNamespace,+ } = useFrontComponentExecutionContext({+ frontComponentId,+ applicationId,+ commandMenuItemId,+ selectedRecordIds,+ colorScheme,+ });const handleError = useCallback((error?: Error) => {@@ -171,6 +175,7 @@ const FrontComponentRendererContent = ({frontComponentHostCommunicationApi}applicationVariables={applicationVariables}+ storageNamespace={storageNamespace}onError={handleError}loadingFallback={loadingFallback}/>diff --git a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsxindex 0063a388fb6..3d703a0c3a7 100644--- a/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx+++ b/packages/twenty-front/src/modules/front-components/hooks/__tests__/useFrontComponentExecutionContext.test.tsx@@ -37,6 +37,9 @@ const mockCloseSidePanelMenu = jest.fn();const mockSetCommandMenuItemProgress = jest.fn();const mockCopyToClipboard = jest.fn();const mockSetRecordPageActiveTabId = jest.fn();+const mockStorageSet = jest.fn();+const mockStorageDelete = jest.fn();+const mockStorageClear = jest.fn();let mockCurrentUser: { id: string } | null = { id: 'user-123' };let mockIsMobile = false;@@ -140,6 +143,20 @@ jest.mock('~/hooks/useCopyToClipboard', () => ({}),}));+jest.mock('twenty-front-component-renderer', () => ({+ buildFrontComponentStorageNamespace: ({+ applicationId,+ userId,+ }: {+ applicationId: string;+ userId: string;+ }) => `frontComponentStorage:${applicationId}:${userId}:`,+ setFrontComponentStorageItem: (...args: unknown[]) => mockStorageSet(...args),+ deleteFrontComponentStorageItem: (...args: unknown[]) =>+ mockStorageDelete(...args),+ clearFrontComponentStorage: (...args: unknown[]) => mockStorageClear(...args),+}));+jest.mock('@/page-layout/utils/setRecordPageActiveTabId', () => ({setRecordPageActiveTabId: (params: unknown) =>mockSetRecordPageActiveTabId(params),@@ -148,18 +165,24 @@ jest.mock('@/page-layout/utils/setRecordPageActiveTabId', () => ({const renderUseFrontComponentExecutionContext = (params: Omit<Parameters<typeof useFrontComponentExecutionContext>[0],- 'colorScheme'- > & { colorScheme?: 'light' | 'dark' },+ 'colorScheme' | 'applicationId'+ > & { colorScheme?: 'light' | 'dark'; applicationId?: string },) =>renderHook(() =>- useFrontComponentExecutionContext({ colorScheme: 'light', ...params }),+ useFrontComponentExecutionContext({+ colorScheme: 'light',+ applicationId: APPLICATION_ID,+ ...params,+ }),{wrapper: ({ children }) => I18nProvider({ i18n, children }),},);const FRONT_COMPONENT_ID = 'fc-test-id';+const APPLICATION_ID = 'application-test-id';+const STORAGE_NAMESPACE = `frontComponentStorage:${APPLICATION_ID}:user-123:`;const COMMAND_MENU_ITEM_ID = 'cmd-item-1';const parentViewAtom =@@ -919,4 +942,74 @@ describe('useFrontComponentExecutionContext', () => {dateNowSpy.mockRestore();});});++ describe('storage', () => {+ it('should namespace writes by application, user and storage type', async () => {+ const { result } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ await act(async () => {+ await result.current.frontComponentHostCommunicationApi.storageSet({+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });+ });++ expect(mockStorageSet).toHaveBeenCalledWith({+ namespace: STORAGE_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ });+ expect(result.current.storageNamespace).toBe(STORAGE_NAMESPACE);+ });++ it('should forward delete and clear with the namespace applied', async () => {+ const { result } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ await act(async () => {+ await result.current.frontComponentHostCommunicationApi.storageDelete({+ storageType: 'localStorage',+ key: 'theme',+ });+ await result.current.frontComponentHostCommunicationApi.storageClear({+ storageType: 'sessionStorage',+ });+ });++ expect(mockStorageDelete).toHaveBeenCalledWith({+ namespace: STORAGE_NAMESPACE,+ storageType: 'localStorage',+ key: 'theme',+ });+ expect(mockStorageClear).toHaveBeenCalledWith({+ namespace: STORAGE_NAMESPACE,+ storageType: 'sessionStorage',+ });+ });++ it('should reject writes and expose no namespace when signed out', async () => {+ mockCurrentUser = null;++ const { result } = renderUseFrontComponentExecutionContext({+ frontComponentId: FRONT_COMPONENT_ID,+ });++ expect(result.current.storageNamespace).toBeUndefined();++ await expect(+ result.current.frontComponentHostCommunicationApi.storageSet({+ storageType: 'localStorage',+ key: 'theme',+ serializedValue: '"dark"',+ }),+ ).rejects.toThrow('Device storage requires a signed-in user');++ expect(mockStorageSet).not.toHaveBeenCalled();+ });+ });});diff --git a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.tsindex 98e7dee2d42..62bf63e9d09 100644--- a/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts+++ b/packages/twenty-front/src/modules/front-components/hooks/useFrontComponentExecutionContext.ts@@ -5,8 +5,12 @@ import { isNonEmptyString } from '@sniptt/guards';import { useLingui } from '@lingui/react/macro';import { useRef } from 'react';import {+ buildFrontComponentStorageNamespace,+ clearFrontComponentStorage,+ deleteFrontComponentStorageItem,type FrontComponentExecutionContext,type FrontComponentHostCommunicationApi,+ setFrontComponentStorageItem,} from 'twenty-front-component-renderer';import {AppPath,@@ -37,7 +41,7 @@ import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useSetAtomFamilyState';import { useStore } from 'jotai';-import { assertUnreachable, isDefined } from 'twenty-shared/utils';+import { assertUnreachable, CustomError, isDefined } from 'twenty-shared/utils';import { useIcons } from 'twenty-ui/icon';import { useIsMobile } from 'twenty-ui/utilities';import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';@@ -49,17 +53,20 @@ const FRONT_COMPONENT_CLIPBOARD_PREVIEW_LENGTH = 30;export const useFrontComponentExecutionContext = ({frontComponentId,+ applicationId,commandMenuItemId,selectedRecordIds,colorScheme,}: {frontComponentId: string;+ applicationId: string;commandMenuItemId?: string;selectedRecordIds?: string[];colorScheme: 'light' | 'dark';}): {executionContext: FrontComponentExecutionContext;frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi;+ storageNamespace?: string;} => {const currentUser = useAtomStateValue(currentUserState);const navigateApp = useNavigateApp();@@ -361,6 +368,56 @@ export const useFrontComponentExecutionContext = ({);};+ const currentUserId = currentUser?.id;++ const storageNamespace = isDefined(currentUserId)+ ? buildFrontComponentStorageNamespace({+ applicationId,+ userId: currentUserId,+ })+ : undefined;++ const requireStorageNamespace = (): string => {+ if (!isDefined(storageNamespace)) {+ throw new CustomError(+ 'Device storage requires a signed-in user',+ 'FRONT_COMPONENT_STORAGE_REQUIRES_SIGNED_IN_USER',+ );+ }++ return storageNamespace;+ };++ const storageSet: FrontComponentHostCommunicationApi['storageSet'] = async ({+ storageType,+ key,+ serializedValue,+ }) => {+ setFrontComponentStorageItem({+ namespace: requireStorageNamespace(),+ storageType,+ key,+ serializedValue,+ });+ };++ const storageDelete: FrontComponentHostCommunicationApi['storageDelete'] =+ async ({ storageType, key }) => {+ deleteFrontComponentStorageItem({+ namespace: requireStorageNamespace(),+ storageType,+ key,+ });+ };++ const storageClear: FrontComponentHostCommunicationApi['storageClear'] =+ async ({ storageType }) => {+ clearFrontComponentStorage({+ namespace: requireStorageNamespace(),+ storageType,+ });+ };+const frontComponentHostCommunicationApi: FrontComponentHostCommunicationApi ={navigate,@@ -372,10 +429,14 @@ export const useFrontComponentExecutionContext = ({closeSidePanel,updateProgress,copyToClipboard,+ storageSet,+ storageDelete,+ storageClear,};return {executionContext,frontComponentHostCommunicationApi,+ storageNamespace,};};diff --git a/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts b/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.tsindex 3c9ee49c863..6716aa0fec4 100644--- a/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts+++ b/packages/twenty-sdk/src/sdk/front-component/globals/frontComponentHostCommunicationApi.ts@@ -6,6 +6,8 @@ import {} from 'twenty-shared/types';import { type getAppPath } from 'twenty-shared/utils';+import { type FrontComponentStorageType } from '../types/FrontComponentStorageType';+export type NavigateFunction = <T extends AppPath>(to: T,params?: Parameters<typeof getAppPath<T>>[1],@@ -104,6 +106,21 @@ export type OpenCommandConfirmationModalHostFunction = (params: Parameters<OpenCommandConfirmationModalFunction>[0],) => Promise<void>;+export type StorageSetFunction = (params: {+ storageType: FrontComponentStorageType;+ key: string;+ serializedValue: string;+}) => Promise<void>;++export type StorageDeleteFunction = (params: {+ storageType: FrontComponentStorageType;+ key: string;+}) => Promise<void>;++export type StorageClearFunction = (params: {+ storageType: FrontComponentStorageType;+}) => Promise<void>;+export type FrontComponentHostCommunicationApiStore = {navigate?: NavigateFunction;requestAccessTokenRefresh?: RequestAccessTokenRefreshFunction;@@ -114,6 +131,9 @@ export type FrontComponentHostCommunicationApiStore = {closeSidePanel?: CloseSidePanelFunction;updateProgress?: UpdateProgressFunction;copyToClipboard?: CopyToClipboardFunction;+ storageSet?: StorageSetFunction;+ storageDelete?: StorageDeleteFunction;+ storageClear?: StorageClearFunction;};import { FRONT_COMPONENT_HOST_COMMUNICATION_API_KEY } from '../constants/front-component-host-communication-api-key';diff --git a/packages/twenty-sdk/src/sdk/front-component/index.ts b/packages/twenty-sdk/src/sdk/front-component/index.tsindex 7ba51702a0a..b50371b145b 100644--- a/packages/twenty-sdk/src/sdk/front-component/index.ts+++ b/packages/twenty-sdk/src/sdk/front-component/index.ts@@ -25,6 +25,7 @@ export type {TranslationValues,} from './translations/message';export type { FrontComponentExecutionContext } from './types/FrontComponentExecutionContext';+export type { FrontComponentStorageType } from './types/FrontComponentStorageType';export { getFrontComponentCommandErrorDedupeKey } from './utils/getFrontComponentCommandErrorDedupeKey';export type {CloseSidePanelFunction,@@ -38,6 +39,9 @@ export type {OpenSidePanelPageFunction,OpenSidePanelPageParams,RequestAccessTokenRefreshFunction,+ StorageClearFunction,+ StorageDeleteFunction,+ StorageSetFunction,UnmountFrontComponentFunction,UpdateProgressFunction,} from './globals/frontComponentHostCommunicationApi';diff --git a/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentStorageType.ts b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentStorageType.tsnew file mode 100644index 00000000000..7ad1d53071c--- /dev/null+++ b/packages/twenty-sdk/src/sdk/front-component/types/FrontComponentStorageType.ts@@ -0,0 +1 @@+export type FrontComponentStorageType = 'localStorage' | 'sessionStorage';