App Framework

Functions

Functions

CommandProvider

Provider component for command service

Signature:

CommandProvider({
  initialContext = {},
  children,
}: CommandProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
initialContext = {},
children,
}`CommandProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useCommandService

Hook to get the command service

Signature:

useCommandService(): CommandService

Returns:

CommandService -

useCommandExecutor

Hook to get command execution capabilities

Signature:

useCommandExecutor(): { execute: <T = void>(commandId: string, args?: unknown) => Promise<CommandResult<T>>; exists: (commandId: string) => boolean; isEnabled: (commandId: string) => boolean; }

Returns:

{ execute: <T = void>(commandId: string, args?: unknown) => Promise<CommandResult<T>>; exists: (commandId: string) => boolean; isEnabled: (commandId: string) => boolean; } -

useCommand

Hook for a specific command

Signature:

useCommand(commandId: string): { execute: (args?: unknown) => Promise<CommandResult<unknown>>; exists: boolean; enabled: boolean; hasHandler: boolean; command?: ExecutableCommand; }

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes

Returns:

{ execute: (args?: unknown) => Promise<CommandResult<unknown>>; exists: boolean; enabled: boolean; hasHandler: boolean; command?: ExecutableCommand; } -

useExecutableCommands

Hook to get all executable commands

Signature:

useExecutableCommands(): ExecutableCommand[]

Returns:

ExecutableCommand[] -

useCommandsByCategory

Hook to get commands grouped by category

Signature:

useCommandsByCategory(): Map<string, ExecutableCommand[]>

Returns:

Map<string, ExecutableCommand[]> -

useCommandContext

Hook to update command context

Signature:

useCommandContext(): [CmdContext, (updates: Partial<CmdContext>) => void]

Returns:

[CmdContext, (updates: Partial<CmdContext>) => void] -

getCommandService

Get the singleton instance

Signature:

getCommandService(): CommandService

Returns:

CommandService -

Link component that automatically prefixes paths with basePath from config

Signature:

AppLink({ to, ...props }: LinkProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ to, ...props }LinkPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

<AppLink to="/tasks">Tasks</AppLink>
// Renders as <Link to="/agents/tasks"> if basePath is '/agents'

FlowstateAppContainer

Root container for Flowstate Apps Provides configuration context and merges default config

Signature:

FlowstateAppContainer({ config, children, renderBugReportModal }: FlowstateAppContainerProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ config, children, renderBugReportModal }FlowstateAppContainerPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

FlowstateAppLayout

Responsive layout component with configurable navigation Shows/hides sidebar, header, and footer based on config

Signature:

FlowstateAppLayout({
  sidebar,
  header,
  footer,
  children,
}: FlowstateAppLayoutProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
sidebar,
header,
footer,
children,
}`FlowstateAppLayoutPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

FlowstateAppProvider

Wraps children with injected service providers (Auth, DB, Loading) Services are applied in order: DB provider, then Auth provider, then Global Loading

Signature:

FlowstateAppProvider({ config, children }: FlowstateAppProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ config, children }FlowstateAppProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

RootRedirect

Signature:

RootRedirect({
  defaultPath = '/apps/flowstate',
  serversPath = '/apps/servers',
  onboardingPath = '/onboarding',
}: RootRedirectProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
defaultPath = '/apps/flowstate',
serversPath = '/apps/servers',
onboardingPath = '/onboarding',
}`RootRedirectPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ServerConfigNavbar

Reusable navbar widget for server configuration management. Includes connection status indicator, server selector, and configuration dialog. Can be used in any sub-app header/navbar.

Signature:

ServerConfigNavbar({ className = '' }: ServerConfigNavbarProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ className = '' }ServerConfigNavbarPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

createFlowstateContainer

Signature:

createFlowstateContainer(config: FlowstateContainerConfig): ({ children }: { children: React.ReactNode; }) => import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
configFlowstateContainerConfigYes

Returns:

({ children }: { children: React.ReactNode; }) => import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ReplicationProvider

Signature:

ReplicationProvider({
  database,
  serverConfig,
  config,
  authToken = null,
  children,
}: ReplicationProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
database,
serverConfig,
config,
authToken = null,
children,
}`ReplicationProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useReplication

Signature:

useReplication(): ReplicationContextState

Returns:

ReplicationContextState -

ViewStateProvider

ViewStateProvider component

Signature:

ViewStateProvider({ children, initialState }: ViewStateProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ children, initialState }ViewStateProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useViewState

Hook to access view state

Signature:

useViewState(): ViewStateContextValue

Returns:

ViewStateContextValue -

useViewStateSafe

Hook to access view state safely (returns undefined if not in provider)

Signature:

useViewStateSafe(): ViewStateContextValue

Returns:

ViewStateContextValue -

evaluateCondition

Evaluate a "when" expression against a context

Signature:

evaluateCondition(expression: string, context: ConditionContext): boolean

Parameters:

ParameterTypeRequiredDescription
expressionstringYes- The when expression to evaluate
contextConditionContextYes- The context variables

Returns:

boolean - Whether the condition is true

isValidCondition

Check if an expression is valid

Signature:

isValidCondition(expression: string): boolean

Parameters:

ParameterTypeRequiredDescription
expressionstringYes

Returns:

boolean -

getConditionVariables

Get all variable names referenced in an expression

Signature:

getConditionVariables(expression: string): string[]

Parameters:

ParameterTypeRequiredDescription
expressionstringYes

Returns:

string[] -

ContributionProvider

Provider component for contribution registry

Signature:

ContributionProvider({
  initialContext = {},
  children,
}: ContributionProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
initialContext = {},
children,
}`ContributionProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useContributionRegistry

Hook to get the contribution registry

Signature:

useContributionRegistry(): ContributionRegistry

Returns:

ContributionRegistry -

useConditionContext

Hook to get the current condition context

Signature:

useConditionContext(): [ConditionContext, (updates: Partial<ConditionContext>) => void]

Returns:

[ConditionContext, (updates: Partial<ConditionContext>) => void] -

useCommands

Hook to get all commands with resolved state

Signature:

useCommands(): ResolvedCommand[]

Returns:

ResolvedCommand[] -

useCommand

Hook to get a specific command

Signature:

useCommand(commandId: string): ResolvedCommand

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes

Returns:

ResolvedCommand -

useMenuItems

Hook to get menu items for a specific location

Signature:

useMenuItems(location: MenuLocation): ResolvedMenuItem[]

Parameters:

ParameterTypeRequiredDescription
locationMenuLocationYes

Returns:

ResolvedMenuItem[] -

useGroupedMenuItems

Hook to get grouped menu items for a location

Signature:

useGroupedMenuItems(location: MenuLocation): MenuGroup[]

Parameters:

ParameterTypeRequiredDescription
locationMenuLocationYes

Returns:

MenuGroup[] -

useKeybindings

Hook to get all keybindings

Signature:

useKeybindings(): ResolvedKeybinding[]

Returns:

ResolvedKeybinding[] -

useKeybinding

Hook to get keybinding for a specific command

Signature:

useKeybinding(commandId: string): ResolvedKeybinding

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes

Returns:

ResolvedKeybinding -

useStatusBarItems

Hook to get all status bar items with resolved visibility

Signature:

useStatusBarItems(): ResolvedStatusBarItem[]

Returns:

ResolvedStatusBarItem[] -

useStatusBarItemsByAlignment

Hook to get status bar items filtered by alignment

Signature:

useStatusBarItemsByAlignment(alignment: "right" | "left" | "center"): ResolvedStatusBarItem[]

Parameters:

ParameterTypeRequiredDescription
alignment"right" | "left" | "center"Yes

Returns:

ResolvedStatusBarItem[] -

useHeaderActions

Hook to get all header actions with resolved visibility

Signature:

useHeaderActions(): ResolvedHeaderAction[]

Returns:

ResolvedHeaderAction[] -

useSettingsTabs

Hook to get all settings tabs

Signature:

useSettingsTabs(): ResolvedSettingsTab[]

Returns:

ResolvedSettingsTab[] -

useSettingsTabsByGroup

Hook to get settings tabs grouped by group

Signature:

useSettingsTabsByGroup(): Map<string, ResolvedSettingsTab[]>

Returns:

Map<string, ResolvedSettingsTab[]> -

useBottomPanelTabs

Hook to get all bottom panel tabs with resolved visibility

Signature:

useBottomPanelTabs(): ResolvedBottomPanelTab[]

Returns:

ResolvedBottomPanelTab[] -

useBottomPanelToolbarItems

Hook to get all bottom panel toolbar items with resolved visibility

Signature:

useBottomPanelToolbarItems(): ResolvedBottomPanelToolbarItem[]

Returns:

ResolvedBottomPanelToolbarItem[] -

useBottomPanelToolbarItemsForTab

Hook to get toolbar items for a specific bottom panel tab

Signature:

useBottomPanelToolbarItemsForTab(tabId: string): ResolvedBottomPanelToolbarItem[]

Parameters:

ParameterTypeRequiredDescription
tabIdstringYes

Returns:

ResolvedBottomPanelToolbarItem[] -

getContributionRegistry

Get the singleton instance

Signature:

getContributionRegistry(): ContributionRegistry

Returns:

ContributionRegistry -

registerCoreCommands

Register all core command handlers

Signature:

registerCoreCommands(options: CoreCommandOptions): () => void

Parameters:

ParameterTypeRequiredDescription
optionsCoreCommandOptionsYes- Options including services and callbacks

Returns:

() => void - Cleanup function to unregister all handlers

unregisterCoreCommands

Unregister all core commands

Signature:

unregisterCoreCommands(commandService: CommandService): void

Parameters:

ParameterTypeRequiredDescription
commandServiceCommandServiceYes

useAppNavigate

Hook that wraps useNavigate with automatic basePath prefixing and org/workspace context switching

Signature:

useAppNavigate(): AppNavigateFunction

Returns:

AppNavigateFunction -

Examples:

const navigate = useAppNavigate();
// Basic navigation (unchanged behavior)
navigate('/tasks/123');

// Navigation with org/workspace context switching
navigate('/tasks/123', { orgId: 'org_xxx', workspaceId: 'work_yyy' });

prefixPath

Helper function to prefix a path with basePath Useful for constructing paths without navigating

Signature:

prefixPath(basePath: string, path: string): string

Parameters:

ParameterTypeRequiredDescription
basePathstringYes- The base path from config
pathstringYes- The relative path to prefix

Returns:

string - The full path with basePath prefix

useAttributes

useAttributes - Unified hook for attribute management Provides access to categories, tags, and meta attributes with real-time updates

Supports scope inheritance where sub-scopes (project > workspace > org) can override parent scope attributes by name.

Signature:

useAttributes(entityType?: string, attributeType?: "tag" | "category" | "meta", filters?: Partial<AttributeFilters>, scopeOptions?: AttributeScopeOptions): UseAttributesReturn & { createAttribute: (data: AttributeFormData) => Promise<AttributeModel | null>; updateAttribute: (id: string, data: Partial<AttributeFormData>) => Promise<AttributeModel | null>; deleteAttribute: (id: string) => Promise<boolean>; archiveAttribute: (id: string) => Promise<boolean>; }

Parameters:

ParameterTypeRequiredDescription
entityTypestringNo
attributeType"tag" | "category" | "meta"No
filtersPartial<AttributeFilters>No
scopeOptionsAttributeScopeOptionsNo

Returns:

UseAttributesReturn & { createAttribute: (data: AttributeFormData) => Promise<AttributeModel \| null>; updateAttribute: (id: string, data: Partial<AttributeFormData>) => Promise<AttributeModel \| null>; deleteAttribute: (id: string) => Promise<boolean>; archiveAttribute: (id: string) => Promise<boolean>; } -

useCategories

Signature:

useCategories(entityType?: string): { categories: AttributeModel[]; isLoading: boolean; error: string | null; refetch: () => void; }

Parameters:

ParameterTypeRequiredDescription
entityTypestringNo

Returns:

{ categories: AttributeModel[]; isLoading: boolean; error: string \| null; refetch: () => void; } -

useTags

Signature:

useTags(entityType?: string): { tags: AttributeModel[]; isLoading: boolean; error: string | null; refetch: () => void; search: (query: string) => AttributeModel[]; }

Parameters:

ParameterTypeRequiredDescription
entityTypestringNo

Returns:

{ tags: AttributeModel[]; isLoading: boolean; error: string \| null; refetch: () => void; search: (query: string) => AttributeModel[]; } -

useAuthenticatedReplication

Hook that combines FlowstateAuth with ReplicationContext for authenticated replication functionality.

Signature:

useAuthenticatedReplication(): UseAuthenticatedReplicationResult

Returns:

UseAuthenticatedReplicationResult -

useAuthTokenRefresh

Hook for automatic JWT token refresh

Signature:

useAuthTokenRefresh(config?: TokenRefreshConfig): { isRefreshing: boolean; lastRefreshError: Error; refreshNow: () => Promise<void>; }

Parameters:

ParameterTypeRequiredDescription
configTokenRefreshConfigNo- Configuration options

Returns:

{ isRefreshing: boolean; lastRefreshError: Error; refreshNow: () => Promise<void>; } - Object with refresh state and manual refresh function

Examples:

function App() {
  const { isRefreshing, lastRefreshError } = useAuthTokenRefresh({ debug: true });

  if (lastRefreshError) {
    console.error('Token refresh failed:', lastRefreshError);
  }

  return <YourApp />;
}

useCurrentEntityContext

Hook to extract the current entity context from the URL

Parses routes like:

  • /apps/projects/projects/:projectId
  • /apps/projects/projects/:projectId/milestones/:milestoneId
  • /apps/projects/projects/:projectId/milestones/:milestoneId/tasks/:taskId

Signature:

useCurrentEntityContext(): EntityContext

Returns:

EntityContext - The current entity context with entityType, entityId, and parentChain

Examples:

function ChatPanel() {
  const { entityType, entityId, parentChain } = useCurrentEntityContext();

  if (entityType === 'task') {
    // Chat is in context of a specific task
    console.log(`Task ID: ${entityId}`);
    // parentChain contains the project and milestone
  }

  return <Chat context={{ entityType, entityId, parentChain }} />;
}

useFlowstateAppConfig

Hook to access Flowstate App configuration Must be used within FlowstateAppContainer

Signature:

useFlowstateAppConfig(): FlowstateAppConfig

Returns:

FlowstateAppConfig -

useInjectedAuth

Hook to access injected authentication service Returns the result of the injected useAuth hook if provided Otherwise returns null (Flowstate App should provide fallback)

Signature:

useInjectedAuth(): any

Returns:

any -

useInjectedDB

Hook to access injected database service Returns the result of the injected useDB hook if provided Otherwise returns null (Flowstate App should provide fallback)

Signature:

useInjectedDB(): any

Returns:

any -

useLoader

Hook to subscribe to loader state

Signature:

useLoader(): { itemsArray: LoadingItem[]; shouldHide: boolean; items: Map<string, LoadingItem>; isLoading: boolean; allComplete: boolean; }

Returns:

{ itemsArray: LoadingItem[]; shouldHide: boolean; items: Map<string, LoadingItem>; isLoading: boolean; allComplete: boolean; } -

useLongTermMemory

Hook for long-term memory operations

Provides search, create, and forget functionality for long-term memories stored in the Agent Memory Server.

Signature:

useLongTermMemory(client: AgentMemoryClient, namespace: string, options?: UseLongTermMemoryOptions): UseLongTermMemoryResult

Parameters:

ParameterTypeRequiredDescription
clientAgentMemoryClientYes- AMS client instance (from useMemoryClient)
namespacestringYes- Default namespace for operations
optionsUseLongTermMemoryOptionsNo- Configuration options

Returns:

UseLongTermMemoryResult - UseLongTermMemoryResult with memories and operations

Examples:

import { useMemoryClient, useLongTermMemory } from '@epicdm/flowstate-app-framework';

function MemoryManager({ namespace }: { namespace: string }) {
  const { client } = useMemoryClient();
  const {
    memories,
    totalCount,
    isLoading,
    error,
    search,
    create,
    forget,
  } = useLongTermMemory(client, namespace);

  const handleSearch = async () => {
    await search('user preferences');
  };

  const handleCreate = async () => {
    await create({
      text: 'User prefers dark mode',
      memory_type: 'preference',
      topics: ['ui', 'preferences'],
    });
  };

  return (
    <div>
      <button onClick={handleSearch}>Search</button>
      <button onClick={handleCreate}>Add Memory</button>
      {isLoading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      <p>Found {totalCount} memories</p>
      <ul>
        {memories.map((m) => (
          <li key={m.id}>{m.text}</li>
        ))}
      </ul>
    </div>
  );
}

useMemoryClient

Hook to get a configured Agent Memory Service (AMS) client

Provides a memoized client instance that performs an initial health check. The client is considered "ready" when it has been created and the server health check passes.

Signature:

useMemoryClient(options?: UseMemoryClientOptions): UseMemoryClientResult

Parameters:

ParameterTypeRequiredDescription
optionsUseMemoryClientOptionsNo- Configuration options for the AMS client

Returns:

UseMemoryClientResult - UseMemoryClientResult with client, status, and error information

Examples:

import { useMemoryClient } from '@epicdm/flowstate-app-framework';

function MyComponent() {
  const { client, isReady, error } = useMemoryClient({
    baseUrl: 'http://localhost:8000',
  });

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  if (!isReady) {
    return <div>Connecting to AMS...</div>;
  }

  // Use client for memory operations
  const handleAddMessage = async () => {
    const memory = await client.addMessage(
      'session-123',
      'default',
      'user',
      'Hello!'
    );
  };
}

useMemorySession

Hook to manage a specific memory session

Provides access to session memory data with automatic fetching, manual refresh capability, and session clearing functionality.

Signature:

useMemorySession(client: AgentMemoryClient, sessionId: string, namespace: string, options?: UseMemorySessionOptions): UseMemorySessionResult

Parameters:

ParameterTypeRequiredDescription
clientAgentMemoryClientYes- AMS client instance (from useMemoryClient)
sessionIdstringYes- Session ID to manage
namespacestringYes- Namespace for the session
optionsUseMemorySessionOptionsNo- Configuration options

Returns:

UseMemorySessionResult - UseMemorySessionResult with memory data and operations

Examples:

import { useMemoryClient, useMemorySession } from '@epicdm/flowstate-app-framework';

function SessionView({ sessionId }: { sessionId: string }) {
  const { client, isReady } = useMemoryClient();
  const {
    messages,
    messageCount,
    tokenCount,
    isLoading,
    refresh,
    clear,
  } = useMemorySession(client, sessionId, 'my-app', {
    refreshInterval: 5000, // Auto-refresh every 5 seconds
  });

  if (isLoading) {
    return <div>Loading session...</div>;
  }

  return (
    <div>
      <p>Messages: {messageCount}, Tokens: {tokenCount}</p>
      <button onClick={refresh}>Refresh</button>
      <button onClick={clear}>Clear Session</button>
      <ul>
        {messages.map((msg, i) => (
          <li key={i}>{msg.role}: {msg.content}</li>
        ))}
      </ul>
    </div>
  );
}

useMemorySessions

Hook to list and manage memory sessions (admin view)

Provides access to all sessions in a namespace with pagination and the ability to delete sessions.

Signature:

useMemorySessions(client: AgentMemoryClient, namespace: string, options?: UseMemorySessionsOptions): UseMemorySessionsResult

Parameters:

ParameterTypeRequiredDescription
clientAgentMemoryClientYes- AMS client instance (from useMemoryClient)
namespacestringYes- Namespace to list sessions for
optionsUseMemorySessionsOptionsNo- Filtering and pagination options

Returns:

UseMemorySessionsResult - UseMemorySessionsResult with sessions list and operations

Examples:

import { useMemoryClient, useMemorySessions } from '@epicdm/flowstate-app-framework';

function SessionsAdmin() {
  const { client, isReady } = useMemoryClient();
  const {
    sessions,
    total,
    isLoading,
    refresh,
    deleteSession,
  } = useMemorySessions(client, 'my-app', {
    limit: 20,
    offset: 0,
  });

  const handleDelete = async (sessionId: string) => {
    const success = await deleteSession(sessionId);
    if (success) {
      console.log('Session deleted');
    }
  };

  if (isLoading) {
    return <div>Loading sessions...</div>;
  }

  return (
    <div>
      <p>Total sessions: {total}</p>
      <button onClick={refresh}>Refresh</button>
      <ul>
        {sessions.map((session) => (
          <li key={session.sessionId}>
            {session.sessionId} - {session.messageCount ?? 0} messages
            <button onClick={() => handleDelete(session.sessionId)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

useOnboardingDetection

Hook to detect if onboarding is needed

Onboarding is required when ALL three conditions are true:

  1. No local database data (RxDB is empty)
  2. No server configuration exists
  3. No onboarding completion flag in localStorage

Signature:

useOnboardingDetection({
  hasLocalDatabaseData,
}: UseOnboardingDetectionOptions): UseOnboardingDetectionResult

Parameters:

ParameterTypeRequiredDescription
`{
hasLocalDatabaseData,
}`UseOnboardingDetectionOptionsYes

Returns:

UseOnboardingDetectionResult -

useOrgWorkspace

Hook for managing org and workspace context with reactive RxDB integration

Convenience hook that wraps OrgWorkspaceContext with helper methods for filtering RxDB queries. Context uses

Signature:

useOrgWorkspace({
  db,
  autoLoad = true,
}?: UseOrgWorkspaceOptions): UseOrgWorkspaceReturn

Parameters:

ParameterTypeRequiredDescription
`{
db,
autoLoad = true,
}`UseOrgWorkspaceOptionsNo

Returns:

UseOrgWorkspaceReturn - Object containing current selections, loading state, and helper methods

Examples:

import { useOrgWorkspace } from '@epicdm/flowstate-app-framework';

function MyComponent() {
const {
selectedOrg,
selectedWorkspace,
isLoading,
getOrgSelector,
getWorkspaceSelector,
} = useOrgWorkspace({ db });

// Filter RxDB queries by current org
const selector = getOrgSelector();

if (isLoading) {
return <Skeleton />;
}

return (
<div>
<h1>Current Org: {selectedOrg?.name}</h1>
<h2>Current Workspace: {selectedWorkspace?.title}</h2>
</div>
);
}

useSearchAllMemory

Hook for unified memory search operations

Provides search functionality across both working memory and long-term memory stored in the Agent Memory Server.

Signature:

useSearchAllMemory(client: AgentMemoryClient, namespace: string, options?: UseSearchAllMemoryOptions): UseSearchAllMemoryResult

Parameters:

ParameterTypeRequiredDescription
clientAgentMemoryClientYes- AMS client instance (from useMemoryClient)
namespacestringYes- Namespace for operations (typically orgId)
optionsUseSearchAllMemoryOptionsNo- Configuration options

Returns:

UseSearchAllMemoryResult - UseSearchAllMemoryResult with results and search function

Examples:

import { useMemoryClient, useSearchAllMemory } from '@epicdm/flowstate-app-framework';

function MemorySearchPanel({ namespace }: { namespace: string }) {
  const { client } = useMemoryClient();
  const {
    results,
    totalCount,
    isLoading,
    error,
    search,
    clearResults,
  } = useSearchAllMemory(client, namespace);

  const handleSearch = async (query: string) => {
    await search(query, {
      includeWorkingMemory: true,
      includeLongTermMemory: true,
    });
  };

  return (
    <div>
      <input onChange={(e) => handleSearch(e.target.value)} />
      {isLoading && <p>Searching...</p>}
      {error && <p>Error: {error.message}</p>}
      <p>Found {totalCount} results</p>
      <ul>
        {results.map((r) => (
          <li key={r.id}>
            [{r.source}] {r.text} (score: {r.score.toFixed(2)})
          </li>
        ))}
      </ul>
    </div>
  );
}

useServerConfig

Custom hook for server configuration management

Manages server configurations with CRUD operations, connection testing, and import/export capabilities. Supports dependency injection for testing and multi-app isolation.

Signature:

useServerConfig(service?: ServerConfigService): UseServerConfig

Parameters:

ParameterTypeRequiredDescription
serviceServerConfigServiceNo- Optional ServerConfigService instance (defaults to singleton)

Returns:

UseServerConfig - UseServerConfig - Server config state and operations

Examples:

// Use default singleton service
const {
  servers,
  activeServer,
  addServer,
  updateServer,
  deleteServer,
  setActiveServer,
  testConnection,
  exportConfigs,
  importConfigs,
  isLoading,
  error
} = useServerConfig();

// Use custom service for testing or isolation
const testService = new ServerConfigService('test-namespace');
const testHook = useServerConfig(testService);

PluginSystemProvider

Unified provider for the plugin system

Includes:

  • ContributionRegistry for commands, menus, keybindings
  • CommandService for executing commands
  • KeybindingService for global keyboard shortcuts
  • PaletteProvider with optional CommandPalette UI
  • Core commands auto-registered on startup

Signature:

PluginSystemProvider({
  initialContext,
  paletteConfig,
  showPalette = true,
  quicknavConfig,
  showQuickNav = true,
  showSettings = true,
  initialViewState,
  settingsPaneRenderers,
  navigationFallback,
  children,
}: PluginSystemProviderProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
initialContext,
paletteConfig,
showPalette = true,
quicknavConfig,
showQuickNav = true,
showSettings = true,
initialViewState,
settingsPaneRenderers,
navigationFallback,
children,
}`PluginSystemProviderPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

<PluginSystemProvider
  initialContext={{ activeApp: 'projects' }}
  showPalette={true}
>
  <App />
</PluginSystemProvider>

KeybindingProvider

Provider component for keybinding system

Signature:

KeybindingProvider({ children }: KeybindingProviderProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
{ children }KeybindingProviderPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

useKeybindingService

Hook to access the keybinding service

Signature:

useKeybindingService(): KeybindingService

Returns:

KeybindingService -

useKeybindings

Hook to get all keybindings

Signature:

useKeybindings(): ParsedKeybinding[]

Returns:

ParsedKeybinding[] -

useKeybinding

Hook to get keybinding for a specific command

Signature:

useKeybinding(commandId: string): UseKeybindingReturn

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes- The command ID to get keybinding for

Returns:

UseKeybindingReturn - The display key string and whether a keybinding exists

useResolvedKeybinding

Hook to get resolved keybinding with metadata

Signature:

useResolvedKeybinding(commandId: string): ResolvedKeybinding

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes- The command ID

Returns:

ResolvedKeybinding - Resolved keybinding or null

useLocalKeybinding

Hook to register a local keybinding within a component

This is useful for component-specific shortcuts that don't need to be in the global registry.

Signature:

useLocalKeybinding(keyString: string, callback: () => void, options?: { enabled?: boolean; preventDefault?: boolean; }): UseLocalKeybindingReturn

Parameters:

ParameterTypeRequiredDescription
keyStringstringYes- The key combination (e.g., "ctrl+s")
callback() => voidYes- The function to call when the key is pressed
options{ enabled?: boolean; preventDefault?: boolean; }No- Additional options

Returns:

UseLocalKeybindingReturn - Whether the keybinding is active

useRegisterKeybinding

Hook to programmatically register a keybinding

Signature:

useRegisterKeybinding(commandId: string, keyString: string, options?: { when?: string; mac?: string; }): void

Parameters:

ParameterTypeRequiredDescription
commandIdstringYes- The command to execute
keyStringstringYes- The key combination
options{ when?: string; mac?: string; }No- Additional options

getKeybindingService

Get the singleton instance

Signature:

getKeybindingService(): KeybindingService

Returns:

KeybindingService -

isMac

Detect if running on macOS

Signature:

isMac(): boolean

Returns:

boolean -

isWindows

Detect if running on Windows

Signature:

isWindows(): boolean

Returns:

boolean -

parseKey

Parse a key string into a KeyCombo

Signature:

parseKey(keyString: string): KeyCombo

Parameters:

ParameterTypeRequiredDescription
keyStringstringYes- Key string like "ctrl+shift+p" or "cmd+k"

Returns:

KeyCombo - Parsed key combination

formatKey

Format a KeyCombo to a display string

Signature:

formatKey(keyCombo: KeyCombo, platform?: "mac" | "windows" | "linux"): string

Parameters:

ParameterTypeRequiredDescription
keyComboKeyComboYes- The key combination
platform"mac" | "windows" | "linux"No- Override platform detection ('mac' | 'windows' | 'linux')

Returns:

string - Formatted display string

keyComboFromEvent

Convert a keyboard event to a KeyCombo

Signature:

keyComboFromEvent(event: KeyboardEvent): KeyCombo

Parameters:

ParameterTypeRequiredDescription
eventKeyboardEventYes- The keyboard event

Returns:

KeyCombo - KeyCombo representing the pressed keys

keyComboEquals

Check if two key combos match

Signature:

keyComboEquals(a: KeyCombo, b: KeyCombo): boolean

Parameters:

ParameterTypeRequiredDescription
aKeyComboYes- First key combo
bKeyComboYes- Second key combo

Returns:

boolean - True if they match

keyComboToString

Convert a key combo to a normalized string for use as a Map key

Signature:

keyComboToString(keyCombo: KeyCombo): string

Parameters:

ParameterTypeRequiredDescription
keyComboKeyComboYes- The key combination

Returns:

string - Normalized string representation

getPlatformKey

Get the platform-appropriate key string from a keybinding

Signature:

getPlatformKey(keyString: string, macKeyString?: string): string

Parameters:

ParameterTypeRequiredDescription
keyStringstringYes- The default key string
macKeyStringstringNo- Optional Mac-specific key string

Returns:

string - The appropriate key string for the current platform

cn

Signature:

cn(inputs?: ClassValue[]): string

Parameters:

ParameterTypeRequiredDescription
inputsClassValue[]No

Returns:

string -

getGlobalLoadingService

Get the global loading service instance

Signature:

getGlobalLoadingService(config?: Partial<GlobalLoadingConfig>): GlobalLoadingService

Parameters:

ParameterTypeRequiredDescription
configPartial<GlobalLoadingConfig>No

Returns:

GlobalLoadingService -

useGlobalLoading

useGlobalLoading Hook

Provides access to the global loading system.

Signature:

useGlobalLoading(): UseGlobalLoadingReturn

Returns:

UseGlobalLoadingReturn -

Examples:

function SaveButton() {
  const { start, complete, fail } = useGlobalLoading();

  const handleSave = async () => {
    start('save', { type: 'topnav', message: 'Saving...' });
    try {
      await api.save(data);
      complete('save');
    } catch (error) {
      fail('save', error.message);
    }
  };

  return <button onClick={handleSave}>Save</button>;
}

manifestToPlugin

Convert a loaded manifest to an AppPlugin

Signature:

manifestToPlugin(loadedManifest: LoadedManifest, options?: ManifestAdapterOptions): AppPlugin

Parameters:

ParameterTypeRequiredDescription
loadedManifestLoadedManifestYes- The loaded manifest with path information
optionsManifestAdapterOptionsNo- Adapter options for customizing the conversion

Returns:

AppPlugin - AppPlugin compatible with PluginRegistry

manifestsToPlugins

Convert multiple loaded manifests to AppPlugins

Signature:

manifestsToPlugins(manifests: LoadedManifest[], options?: ManifestAdapterOptions): AppPlugin[]

Parameters:

ParameterTypeRequiredDescription
manifestsLoadedManifest[]Yes- Array of loaded manifests
optionsManifestAdapterOptionsNo- Adapter options for customizing the conversion

Returns:

AppPlugin[] - Array of AppPlugins

createManifestAdapter

Create an adapter with preset options for reuse

Signature:

createManifestAdapter(options?: ManifestAdapterOptions): { toPlugin: (manifest: LoadedManifest) => AppPlugin; toPlugins: (manifests: LoadedManifest[]) => AppPlugin[]; }

Parameters:

ParameterTypeRequiredDescription
optionsManifestAdapterOptionsNo- Default adapter options

Returns:

{ toPlugin: (manifest: LoadedManifest) => AppPlugin; toPlugins: (manifests: LoadedManifest[]) => AppPlugin[]; } - Adapter functions with bound options

manifestToPluginWithRef

Convert manifest to plugin with manifest reference preserved Useful for contribution processing

Signature:

manifestToPluginWithRef(loadedManifest: LoadedManifest, options?: ManifestAdapterOptions): ManifestBackedPlugin

Parameters:

ParameterTypeRequiredDescription
loadedManifestLoadedManifestYes
optionsManifestAdapterOptionsNo

Returns:

ManifestBackedPlugin -

getManifestDiscovery

Get the singleton instance

Signature:

getManifestDiscovery(): ManifestDiscovery

Returns:

ManifestDiscovery -

loadManifest

Load a single plugin manifest from a directory

Signature:

loadManifest(pluginPath: string): Promise<LoadedManifest>

Parameters:

ParameterTypeRequiredDescription
pluginPathstringYes- Path to the plugin directory containing flowstate.json

Returns:

Promise<LoadedManifest> - Promise resolving to the loaded manifest with metadata

loadAllManifests

Load all plugin manifests from a plugins directory

Signature:

loadAllManifests(pluginsDir: string): Promise<LoadedManifest[]>

Parameters:

ParameterTypeRequiredDescription
pluginsDirstringYes- Path to the directory containing plugin subdirectories

Returns:

Promise<LoadedManifest[]> - Promise resolving to array of loaded manifests

loadManifestsFromRegistry

Load manifests from a browser-compatible registry Used when manifest paths are known at build time

Signature:

loadManifestsFromRegistry(manifestPaths: string[]): Promise<LoadedManifest[]>

Parameters:

ParameterTypeRequiredDescription
manifestPathsstring[]Yes- Array of paths to manifest files

Returns:

Promise<LoadedManifest[]> - Promise resolving to array of loaded manifests

ManifestLoaderProvider

ManifestLoaderProvider - Registers plugin manifests with the system

Usage:

import projectsManifest from './apps/projects/flowstate.json';
import chatManifest from './apps/chat/flowstate.json';

const manifests = [projectsManifest, chatManifest];

<ManifestLoaderProvider manifests={manifests}>
  <App />
</ManifestLoaderProvider>

Signature:

ManifestLoaderProvider({
  manifests,
  children,
}: ManifestLoaderProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
manifests,
children,
}`ManifestLoaderProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

getManifestRegistry

Get the singleton ManifestRegistry instance

Signature:

getManifestRegistry(): ManifestRegistry

Returns:

ManifestRegistry -

validateManifest

Validate a plugin manifest

Signature:

validateManifest(manifest: unknown): ManifestValidationResult

Parameters:

ParameterTypeRequiredDescription
manifestunknownYes- The manifest object to validate

Returns:

ManifestValidationResult - Validation result with errors and warnings

parseAndValidateManifest

Validate and parse a manifest, throwing on validation errors

Signature:

parseAndValidateManifest(manifest: unknown): PluginManifest

Parameters:

ParameterTypeRequiredDescription
manifestunknownYes- The manifest object to validate

Returns:

PluginManifest - The validated manifest with proper typing

useManifestDiscovery

React hook for manifest discovery

Signature:

useManifestDiscovery(options: UseManifestDiscoveryOptions): UseManifestDiscoveryReturn

Parameters:

ParameterTypeRequiredDescription
optionsUseManifestDiscoveryOptionsYes

Returns:

UseManifestDiscoveryReturn -

Examples:

function App() {
  const { manifests, loading, errors } = useManifestDiscovery({
    paths: ['/plugins', '/apps'],
    watch: true,
  });

  if (loading) return <div>Loading plugins...</div>;

  return (
    <div>
      <h1>Discovered {manifests.length} plugins</h1>
      {errors.length > 0 && (
        <div>Errors: {errors.map(e => e.error.message).join(', ')}</div>
      )}
    </div>
  );
}

useDiscoveredManifests

Hook to get all currently discovered manifests Useful when you don't need to trigger discovery yourself

Signature:

useDiscoveredManifests(): LoadedManifest[]

Returns:

LoadedManifest[] -

useManifest

Hook to get a specific manifest by plugin ID

Signature:

useManifest(pluginId: string): LoadedManifest

Parameters:

ParameterTypeRequiredDescription
pluginIdstringYes

Returns:

LoadedManifest -

useRegisteredApps

Hook to get all registered apps from loaded manifests

Signature:

useRegisteredApps(): RegisteredApp[]

Returns:

RegisteredApp[] - Array of registered apps derived from manifests

useLoadedManifests

Hook to get all loaded manifests

Signature:

useLoadedManifests(): LoadedManifest[]

Returns:

LoadedManifest[] - Array of loaded manifests

useManifest

Hook to get a specific manifest by plugin ID

Signature:

useManifest(pluginId: string): PluginManifest

Parameters:

ParameterTypeRequiredDescription
pluginIdstringYes- Plugin ID to look up

Returns:

PluginManifest - The manifest or undefined if not found

getMenuService

Get the singleton instance

Signature:

getMenuService(): MenuService

Returns:

MenuService -

useContextMenu

Hook for managing a context menu

Signature:

useContextMenu(): UseContextMenuReturn

Returns:

UseContextMenuReturn - Context menu state and handlers

createContextMenuHook

Create a context menu for a specific context type

Signature:

createContextMenuHook(contextType: string): () => { onContextMenu: (e: React.MouseEvent, contextData?: Record<string, unknown>) => void; state: ContextMenuState; open: (anchor: MenuAnchor, contextType?: string, contextData?: Record<string, unknown>) => void; close: () => void; }

Parameters:

ParameterTypeRequiredDescription
contextTypestringYes

Returns:

() => { onContextMenu: (e: React.MouseEvent, contextData?: Record<string, unknown>) => void; state: ContextMenuState; open: (anchor: MenuAnchor, contextType?: string, contextData?: Record<string, unknown>) => void; close: () => void; } -

useMenuItems

Hook to get menu items for a location

Signature:

useMenuItems(location: MenuLocation, context?: ConditionContext): ResolvedMenuItem[]

Parameters:

ParameterTypeRequiredDescription
locationMenuLocationYes- Menu location
contextConditionContextNo- Condition context

Returns:

ResolvedMenuItem[] - Array of resolved menu items

useGroupedMenuItems

Hook to get grouped menu items for a location

Signature:

useGroupedMenuItems(location: MenuLocation, context?: ConditionContext): MenuGroup[]

Parameters:

ParameterTypeRequiredDescription
locationMenuLocationYes- Menu location
contextConditionContextNo- Condition context

Returns:

MenuGroup[] - Array of menu groups

useMenuItemExecutor

Hook to execute a menu item's command

Signature:

useMenuItemExecutor(): { execute: (commandId: string) => Promise<import("/Users/sthornock/code/epic/epic-flowstate/packages/flowstate-app-framework/src/index").CommandResult<void>>; }

Returns:

{ execute: (commandId: string) => Promise<import("/Users/sthornock/code/epic/epic-flowstate/packages/flowstate-app-framework/src/index").CommandResult<void>>; } -

getEntityRouteRegistry

Get the global EntityRouteRegistry instance

Signature:

getEntityRouteRegistry(): EntityRouteRegistry

Returns:

EntityRouteRegistry -

getNavigationService

Get the global NavigationService instance

Signature:

getNavigationService(): NavigationService

Returns:

NavigationService -

detectEntityType

Detect entity type from ID prefix

Signature:

detectEntityType(id: string): NavigableEntityType

Parameters:

ParameterTypeRequiredDescription
idstringYes

Returns:

NavigableEntityType -

useNavigation

useNavigation Hook

Provides navigation methods with cross-org/workspace support. Automatically initializes the NavigationService with the current context.

Signature:

useNavigation(): UseNavigationReturn

Returns:

UseNavigationReturn -

BugReportProvider

Provider for bug report functionality across the app. Allows error boundaries to trigger bug reports that can be handled by any component that registers a handler.

Signature:

BugReportProvider({ children }: BugReportProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ children }BugReportProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useBugReport

Hook to access bug report context. Returns null if used outside of BugReportProvider.

Signature:

useBugReport(): BugReportContextValue

Returns:

BugReportContextValue -

useBugReportHandler

Hook to get the onReportBug handler for error boundaries. Returns undefined if no bug report context is available.

Signature:

useBugReportHandler(): (data: BugReportData) => void

Returns:

(data: BugReportData) => void -

DefaultErrorFallback

Default error fallback UI component Displays user-friendly error message with reset capability

Signature:

DefaultErrorFallback({
  error,
  errorInfo,
  reset,
  onReportBug,
  boundaryName,
  containerClassName = "flex min-h-full items-center justify-center bg-gray-50 px-4"
}: ErrorFallbackProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
error,
errorInfo,
reset,
onReportBug,
boundaryName,
containerClassName = "flex min-h-full items-center justify-center bg-gray-50 px-4"
}`ErrorFallbackPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

PaletteProvider

Provider component for command palette

Signature:

PaletteProvider({
  config: configOverrides,
  children,
}: PaletteProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
config: configOverrides,
children,
}`PaletteProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useCommandPalette

Hook to use command palette

Signature:

useCommandPalette(): UsePaletteReturn

Returns:

UsePaletteReturn -

usePaletteState

Hook for just the open/close state

Signature:

usePaletteState(): { isOpen: boolean; open: () => void; close: () => void; toggle: () => void; }

Returns:

{ isOpen: boolean; open: () => void; close: () => void; toggle: () => void; } -

getRecentCommandsManager

Get the singleton manager

Signature:

getRecentCommandsManager(maxCommands?: number): RecentCommandsManager

Parameters:

ParameterTypeRequiredDescription
maxCommandsnumberNo

Returns:

RecentCommandsManager -

useRecentCommands

React hook for recent commands

Signature:

useRecentCommands(maxCommands?: number): { recentIds: string[]; addRecent: (commandId: string) => void; removeRecent: (commandId: string) => void; clearRecent: () => void; }

Parameters:

ParameterTypeRequiredDescription
maxCommandsnumberNo

Returns:

{ recentIds: string[]; addRecent: (commandId: string) => void; removeRecent: (commandId: string) => void; clearRecent: () => void; } -

Search commands and return sorted results with category headers

Signature:

usePaletteSearch(commands: ExecutableCommand[], recentIds: string[], query: string, options?: { showCategories?: boolean; showRecentWhenEmpty?: boolean; }): PaletteItem[]

Parameters:

ParameterTypeRequiredDescription
commandsExecutableCommand[]Yes
recentIdsstring[]Yes
querystringYes
options{ showCategories?: boolean; showRecentWhenEmpty?: boolean; }No

Returns:

PaletteItem[] -

getNextSelectableIndex

Get the next selectable index

Signature:

getNextSelectableIndex(items: PaletteItem[], currentIndex: number, direction: 1 | -1): number

Parameters:

ParameterTypeRequiredDescription
itemsPaletteItem[]Yes
currentIndexnumberYes
direction1 | -1Yes

Returns:

number -

getFirstSelectableIndex

Find first selectable index

Signature:

getFirstSelectableIndex(items: PaletteItem[]): number

Parameters:

ParameterTypeRequiredDescription
itemsPaletteItem[]Yes

Returns:

number -

useAuth

Signature:

useAuth(): AuthContextValue

Returns:

AuthContextValue -

AuthProvider

Signature:

AuthProvider({ children }: AuthProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ children }AuthProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useComponent

Signature:

useComponent(name: string): React.ComponentType<any>

Parameters:

ParameterTypeRequiredDescription
namestringYes

Returns:

React.ComponentType<any> -

ComponentProvider

Signature:

ComponentProvider({
  children,
  components,
  overrides = {},
}: ComponentProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
components,
overrides = {},
}`ComponentProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useDatabase

Signature:

useDatabase(): DatabaseContextValue

Returns:

DatabaseContextValue -

DatabaseProvider

Signature:

DatabaseProvider({
  children,
  adapter,
  databaseName,
  serverInfo = null,
}: DatabaseProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
adapter,
databaseName,
serverInfo = null,
}`DatabaseProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

getDbName

Get the database name based on server configuration. Each server gets its own IndexedDB instance for data isolation.

Signature:

getDbName(serverConfig: ServerProfile): string

Parameters:

ParameterTypeRequiredDescription
serverConfigServerProfileYes- The current server profile, or null for offline mode

Returns:

string - The database name to use for IndexedDB

Examples:

// Offline mode
getDbName(null) // returns 'flowstate_offline'

// Server mode with explicit dbName
getDbName({ id: 'server_abc', dbName: 'custom_db', ... }) // returns 'custom_db'

// Server mode without dbName (generates from id)
getDbName({ id: 'server_abc', ... }) // returns 'flowstate_server_abc'

useFlowstateAuth

Hook to access server authentication context

Signature:

useFlowstateAuth(): FlowstateAuthContextValue

Returns:

FlowstateAuthContextValue -

useFlowstateAuthOptional

Hook to optionally access server authentication context. Returns null if used outside FlowstateAuthProvider instead of throwing. Useful for components that work with or without authentication.

Signature:

useFlowstateAuthOptional(): FlowstateAuthContextValue

Returns:

FlowstateAuthContextValue -

FlowstateAuthProvider

Provider component for server authentication

Signature:

FlowstateAuthProvider({ children, config, onTokenRefresh }: FlowstateAuthProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ children, config, onTokenRefresh }FlowstateAuthProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useOrgWorkspace

Signature:

useOrgWorkspace(): OrgWorkspaceContextValue

Returns:

OrgWorkspaceContextValue -

OrgWorkspaceProvider

Signature:

OrgWorkspaceProvider({
  children,
}: OrgWorkspaceProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
}`OrgWorkspaceProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useServerConfig

Signature:

useServerConfig(): ServerConfigContextValue

Returns:

ServerConfigContextValue -

ServerConfigProvider

Signature:

ServerConfigProvider({
  children,
  initialMode,
  initialServers,
  initialServer = null,
}: ServerConfigProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
initialMode,
initialServers,
initialServer = null,
}`ServerConfigProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

seedStandaloneData

Signature:

seedStandaloneData(db: RxDatabase): Promise<void>

Parameters:

ParameterTypeRequiredDescription
dbRxDatabaseYes

Returns:

Promise<void> -

QuickNavProvider

Provider component for quick navigation

Signature:

QuickNavProvider({
  config: configOverrides,
  children,
}: QuickNavProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
config: configOverrides,
children,
}`QuickNavProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useQuickNav

Hook to use quick navigation

Signature:

useQuickNav(): QuickNavContextValue

Returns:

QuickNavContextValue -

useQuickNavState

Hook for just the open/close state

Signature:

useQuickNavState(): { isOpen: boolean; open: () => void; close: () => void; toggle: () => void; }

Returns:

{ isOpen: boolean; open: () => void; close: () => void; toggle: () => void; } -

getQuickNavService

Get the QuickNavService singleton

Signature:

getQuickNavService(): QuickNavService

Returns:

QuickNavService -

resetQuickNavService

Reset the QuickNavService singleton (for testing)

Signature:

resetQuickNavService(): void

Hook for programmatic access to QuickNav search

Signature:

useQuickNavSearch(options?: UseQuickNavSearchOptions): UseQuickNavSearchReturn

Parameters:

ParameterTypeRequiredDescription
optionsUseQuickNavSearchOptionsNo

Returns:

UseQuickNavSearchReturn -

Examples:

function MyComponent() {
  const { results, isLoading, search, clear } = useQuickNavSearch();

  return (
    <div>
      <input onChange={(e) => search(e.target.value)} />
      {isLoading && <span>Loading...</span>}
      {results.map(item => <div key={item.id}>{item.title}</div>)}
    </div>
  );
}

createAuthTokenRefresher

Create a token refresh function that can be used with ReplicationPlugin. This is a factory function that returns a refresh function compatible with the ReplicationPluginConfig.refreshToken signature.

Signature:

createAuthTokenRefresher(options?: AuthTokenRefresherOptions): () => Promise<string>

Parameters:

ParameterTypeRequiredDescription
optionsAuthTokenRefresherOptionsNo- Configuration options

Returns:

() => Promise<string> - A function that refreshes the auth token and returns the new token

Examples:

import { createAuthTokenRefresher } from '@epicdm/flowstate-app-framework';

const refreshToken = createAuthTokenRefresher({ debug: true });

new ReplicationPlugin({
  collections: ['tasks', 'projects'],
  refreshToken, // Automatic token refresh on 401
  onTokenRefreshed: (newToken) => {
    console.log('Token refreshed successfully');
  },
  onTokenRefreshFailed: (error) => {
    console.error('Token refresh failed:', error);
    // Redirect to login
  },
});

validateSyncConfig

Validate a sync provider configuration

Signature:

validateSyncConfig(config: unknown): ValidationResult<SyncProviderConfig>

Parameters:

ParameterTypeRequiredDescription
configunknownYes- The configuration to validate (unknown type for runtime safety)

Returns:

ValidationResult<SyncProviderConfig> - ValidationResult with validated config or error details

Examples:

const result = validateSyncConfig(userInput);
if (result.success) {
  // result.data is typed as SyncProviderConfig
  setupSync(result.data);
} else {
  // result.errors contains validation failures
  console.error('Invalid config:', result.errors);
}

validateFieldMapping

Validate a sync field mapping

Signature:

validateFieldMapping(mapping: unknown): ValidationResult<SyncFieldMapping>

Parameters:

ParameterTypeRequiredDescription
mappingunknownYes- The field mapping to validate (unknown type for runtime safety)

Returns:

ValidationResult<SyncFieldMapping> - ValidationResult with validated mapping or error details

Examples:

const result = validateFieldMapping(userInput);
if (result.success) {
  // result.data is typed as SyncFieldMapping
  addMapping(result.data);
} else {
  // result.errors contains validation failures
  console.error('Invalid mapping:', result.errors);
}

getSyncProviderRegistry

Get the singleton SyncProviderRegistry instance.

Convenience function for accessing the registry.

Signature:

getSyncProviderRegistry(): SyncProviderRegistry

Returns:

SyncProviderRegistry - The singleton registry instance

createTheme

Create a custom theme with partial overrides from the default theme

Signature:

createTheme(overrides?: DeepPartial<Theme>): Theme

Parameters:

ParameterTypeRequiredDescription
overridesDeepPartial<Theme>No- Partial theme configuration to override defaults

Returns:

Theme - A complete Theme object with overrides applied

Examples:

const customTheme = createTheme({
  name: 'My Custom Theme',
  branding: { appName: 'My App' },
  colors: {
    light: { primary: 'oklch(0.6 0.18 120)' },
  },
});

getOrgThemeLoader

Get a new OrgThemeLoader instance

Factory function for creating OrgThemeLoader instances. Each call returns a new instance with its own storage.

Signature:

getOrgThemeLoader(config?: OrgThemeLoaderConfig): OrgThemeLoader

Parameters:

ParameterTypeRequiredDescription
configOrgThemeLoaderConfigNo- Optional configuration for storage mode

Returns:

OrgThemeLoader - New OrgThemeLoader instance

Examples:

// Mock mode (default)
const loader = getOrgThemeLoader();

// Database mode
const loader = getOrgThemeLoader({
  useMock: false,
  database: myRxDatabase,
});

const theme = await loader.loadOrgTheme('org-123');

useThemeContext

Hook to access theme context state directly

Signature:

useThemeContext(): ThemeState

Returns:

ThemeState - Current theme state

Examples:

function ThemeDisplay() {
  const { currentTheme, mode, resolvedMode } = useThemeContext();
  return <div>Current mode: {mode}</div>;
}

getThemeService

Get the theme service instance

Signature:

getThemeService(config?: Partial<ThemeConfig>): ThemeService

Parameters:

ParameterTypeRequiredDescription
configPartial<ThemeConfig>No

Returns:

ThemeService -

useTheme

useTheme Hook

Provides access to the theme system with reactive state updates. Automatically subscribes to ThemeService state changes.

Signature:

useTheme(): UseThemeReturn

Returns:

UseThemeReturn - Theme state and control functions

Examples:

function ThemeToggle() {
  const { mode, resolvedMode, setMode, toggleMode } = useTheme();

  return (
    <div>
      <p>Current mode: {mode}</p>
      <p>Resolved: {resolvedMode}</p>
      <button onClick={toggleMode}>Toggle</button>
      <button onClick={() => setMode('system')}>Use System</button>
    </div>
  );
}

isFileProtocol

Check if running in an environment where relative URLs won't work (e.g., Electron's file:// protocol).

Signature:

isFileProtocol(): boolean

Returns:

boolean -

getKongGatewayUrl

Get the Kong gateway base URL.

Uses VITE_KONG_GATEWAY_URL env var if available, otherwise defaults to http://localhost:7080.

Signature:

getKongGatewayUrl(): string

Returns:

string -

resolveApiUrl

Resolve an API URL that works in both Next.js and Electron contexts.

In Next.js (http/https): returns the relative path as-is (proxied by API routes). In Electron (file://): prepends the Kong gateway URL.

Signature:

resolveApiUrl(relativePath: string): string

Parameters:

ParameterTypeRequiredDescription
relativePathstringYes- The relative API path (e.g., '/api/rag-sync/admin/status')

Returns:

string - The resolved URL

getAmsBaseUrl

Get the AMS (Agent Memory Server) base URL.

In Next.js: returns '/api/memory' (proxied through Next.js API routes). In Electron: returns Kong gateway AMS route (e.g., 'http://localhost:7080/ams').

Signature:

getAmsBaseUrl(): string

Returns:

string -

getUsableOrigin

Get the current origin suitable for constructing callback URLs.

In Next.js: returns window.location.origin (e.g., 'http://localhost:3000'). In Electron: returns the Kong gateway URL since file:// origin is not usable.

Signature:

getUsableOrigin(): string

Returns:

string -

generateCalendarRecurrenceInstances

Generate calendar event instances for a recurring task

Signature:

generateCalendarRecurrenceInstances(recurringTask: TaskModel & { recurrencePattern: RecurrencePattern; }, options: RecurrenceDisplayOptions, existingInstances?: RecurrenceInstance[]): CalendarRecurrenceInstance[]

Parameters:

ParameterTypeRequiredDescription
recurringTaskTaskModel & { recurrencePattern: RecurrencePattern; }Yes
optionsRecurrenceDisplayOptionsYes
existingInstancesRecurrenceInstance[]No

Returns:

CalendarRecurrenceInstance[] -

handleRecurrenceEdit

Handle editing of recurring task instances

Signature:

handleRecurrenceEdit(originalTask: TaskModel, editOptions: EditRecurrenceOptions, existingInstances: RecurrenceInstance[]): { instancesToCreate: Partial<RecurrenceInstance>[]; instancesToUpdate: Partial<RecurrenceInstance>[]; patternToUpdate?: Partial<RecurrencePattern>; success: boolean; message: string; }

Parameters:

ParameterTypeRequiredDescription
originalTaskTaskModelYes
editOptionsEditRecurrenceOptionsYes
existingInstancesRecurrenceInstance[]Yes

Returns:

{ instancesToCreate: Partial<RecurrenceInstance>[]; instancesToUpdate: Partial<RecurrenceInstance>[]; patternToUpdate?: Partial<RecurrencePattern>; success: boolean; message: string; } -

calculateRecurrenceCalendarStats

Calculate recurrence statistics for calendar display

Signature:

calculateRecurrenceCalendarStats(instances: CalendarRecurrenceInstance[], currentDate?: Date): { totalInstances: number; completedInstances: number; upcomingInstances: number; overdueInstances: number; }

Parameters:

ParameterTypeRequiredDescription
instancesCalendarRecurrenceInstance[]Yes
currentDateDateNo

Returns:

{ totalInstances: number; completedInstances: number; upcomingInstances: number; overdueInstances: number; } -

getNextRecurrenceOccurrence

Get next occurrence information for a recurring task

Signature:

getNextRecurrenceOccurrence(recurrencePattern: RecurrencePattern, currentDate?: Date): { date: string; daysUntil: number; }

Parameters:

ParameterTypeRequiredDescription
recurrencePatternRecurrencePatternYes
currentDateDateNo

Returns:

{ date: string; daysUntil: number; } -

generateRecurrenceCalendarData

Generate complete recurrence calendar data

Signature:

generateRecurrenceCalendarData(recurringTask: TaskModel & { recurrencePattern: RecurrencePattern; }, options: RecurrenceDisplayOptions, existingInstances?: RecurrenceInstance[]): RecurrenceCalendarData

Parameters:

ParameterTypeRequiredDescription
recurringTaskTaskModel & { recurrencePattern: RecurrencePattern; }Yes
optionsRecurrenceDisplayOptionsYes
existingInstancesRecurrenceInstance[]No

Returns:

RecurrenceCalendarData -

isDateInRecurrencePattern

Check if a date matches a recurrence pattern (convenience wrapper)

Signature:

isDateInRecurrencePattern(date: string | Date, pattern: RecurrencePattern): boolean

Parameters:

ParameterTypeRequiredDescription
datestring | DateYes
patternRecurrencePatternYes

Returns:

boolean -

formatRecurrenceDescription

Format recurrence description for calendar display

Signature:

formatRecurrenceDescription(pattern: RecurrencePattern): string

Parameters:

ParameterTypeRequiredDescription
patternRecurrencePatternYes

Returns:

string -

lastUpdated

Signature:

lastUpdated(dateString: string): string

Parameters:

ParameterTypeRequiredDescription
dateStringstringYes

Returns:

string -

formattedDateTime

Signature:

formattedDateTime(dateString: any): string

Parameters:

ParameterTypeRequiredDescription
dateStringanyYes

Returns:

string -

formattedDate

Signature:

formattedDate(dateString: any): string

Parameters:

ParameterTypeRequiredDescription
dateStringanyYes

Returns:

string -

formatDateInTimezone

Format a date string in a specific timezone using modern date-fns

Signature:

formatDateInTimezone(dateString: any, timezone: string, includeTime?: boolean): string

Parameters:

ParameterTypeRequiredDescription
dateStringanyYes- UTC ISO string or any date string
timezonestringYes- Target timezone (IANA identifier)
includeTimebooleanNo- Whether to include time in the output

Returns:

string - Formatted date string in the specified timezone

getRelativeTime

Get relative time string with timezone awareness

Signature:

getRelativeTime(dateString: any, includeSeconds?: boolean): string

Parameters:

ParameterTypeRequiredDescription
dateStringanyYes- UTC ISO string or any date string
includeSecondsbooleanNo- Whether to include seconds precision

Returns:

string - Relative time string (e.g., "2 hours ago")

isValidDateString

Check if a date string is valid

Signature:

isValidDateString(dateString: any): boolean

Parameters:

ParameterTypeRequiredDescription
dateStringanyYes- Date string to validate

Returns:

boolean - Boolean indicating validity

htmlToMarkdown

Convert HTML content to Markdown format

Signature:

htmlToMarkdown(html: string): string

Parameters:

ParameterTypeRequiredDescription
htmlstringYes- HTML string to convert

Returns:

string - Markdown string

markdownToHtml

Convert Markdown content to HTML format

Signature:

markdownToHtml(markdown: string): string

Parameters:

ParameterTypeRequiredDescription
markdownstringYes- Markdown string to convert

Returns:

string - HTML string

isMarkdownContent

Detect if content contains Markdown formatting

Signature:

isMarkdownContent(content: string): boolean

Parameters:

ParameterTypeRequiredDescription
contentstringYes- Content string to analyze

Returns:

boolean - True if content appears to contain Markdown

stripMarkdown

Strip Markdown formatting to get plain text

Signature:

stripMarkdown(markdown: string): string

Parameters:

ParameterTypeRequiredDescription
markdownstringYes- Markdown string to process

Returns:

string - Plain text without Markdown formatting

sanitizeHtml

Sanitize HTML content to prevent XSS attacks Basic sanitization - removes script tags and dangerous attributes

Signature:

sanitizeHtml(html: string): string

Parameters:

ParameterTypeRequiredDescription
htmlstringYes- HTML string to sanitize

Returns:

string - Sanitized HTML string

getMarkdownPreview

Get a preview of markdown content as plain text with length limit

Signature:

getMarkdownPreview(markdown: string, maxLength?: number): string

Parameters:

ParameterTypeRequiredDescription
markdownstringYes- Markdown content
maxLengthnumberNo- Maximum length of preview (default: 150)

Returns:

string - Plain text preview with ellipsis if truncated

validateContent

Validate that content is safe for storage and display

Signature:

validateContent(content: string): { isValid: boolean; isSafe: boolean; hasMarkdown: boolean; length: number; errors: string[]; }

Parameters:

ParameterTypeRequiredDescription
contentstringYes- Content to validate

Returns:

{ isValid: boolean; isSafe: boolean; hasMarkdown: boolean; length: number; errors: string[]; } - Object with validation results

parseRRule

Parse an iCal RRULE string into structured data Supports basic RRULE parsing for common recurrence patterns

Signature:

parseRRule(rrule: string): Partial<RecurrencePattern>

Parameters:

ParameterTypeRequiredDescription
rrulestringYes

Returns:

Partial<RecurrencePattern> -

generateRRule

Generate an iCal RRULE string from recurrence pattern data

Signature:

generateRRule(pattern: CreateRecurrencePatternData): string

Parameters:

ParameterTypeRequiredDescription
patternCreateRecurrencePatternDataYes

Returns:

string -

validateRecurrencePattern

Validate a recurrence pattern for correctness and logical consistency

Signature:

validateRecurrencePattern(pattern: CreateRecurrencePatternData): RecurrenceValidationResult

Parameters:

ParameterTypeRequiredDescription
patternCreateRecurrencePatternDataYes

Returns:

RecurrenceValidationResult -

getNextOccurrence

Calculate the next occurrence of a recurring pattern after a given date

Signature:

getNextOccurrence(pattern: RecurrencePattern, afterDate: Date, timezone?: string): Date

Parameters:

ParameterTypeRequiredDescription
patternRecurrencePatternYes
afterDateDateYes
timezonestringNo

Returns:

Date -

generateRecurringInstances

Generate multiple recurring instances within a date range

Signature:

generateRecurringInstances(pattern: RecurrencePattern, options: GenerateInstancesOptions): Date[]

Parameters:

ParameterTypeRequiredDescription
patternRecurrencePatternYes
optionsGenerateInstancesOptionsYes

Returns:

Date[] -

generateRecurrencePreview

Generate a preview of upcoming recurrence instances

Signature:

generateRecurrencePreview(pattern: CreateRecurrencePatternData): RecurrencePreview

Parameters:

ParameterTypeRequiredDescription
patternCreateRecurrencePatternDataYes

Returns:

RecurrencePreview -

dateMatchesPattern

Check if a date matches a recurrence pattern

Signature:

dateMatchesPattern(date: Date, pattern: RecurrencePattern, timezone?: string): boolean

Parameters:

ParameterTypeRequiredDescription
dateDateYes
patternRecurrencePatternYes
timezonestringNo

Returns:

boolean -

getRecurrenceDescription

Get human-readable description of a recurrence pattern

Signature:

getRecurrenceDescription(pattern: RecurrencePattern): string

Parameters:

ParameterTypeRequiredDescription
patternRecurrencePatternYes

Returns:

string -

camelize

Signature:

camelize(str: string): string

Parameters:

ParameterTypeRequiredDescription
strstringYes

Returns:

string -

capitalize

Signature:

capitalize(str: string): string

Parameters:

ParameterTypeRequiredDescription
strstringYes

Returns:

string -

LoginForm

Signature:

LoginForm({
  onSuccess,
  onError,
  className = '',
  showTitle = true,
  title = 'Sign In'
}: LoginFormProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onSuccess,
onError,
className = '',
showTitle = true,
title = 'Sign In'
}`LoginFormPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

DateDisplay

Signature:

DateDisplay({
  date,
  format: displayFormat = 'datetime',
  customFormat,
  timezone,
  fallback = 'Invalid date',
  className = '',
  showTimezone = false,
}: DateDisplayProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
date,
format: displayFormat = 'datetime',
customFormat,
timezone,
fallback = 'Invalid date',
className = '',
showTimezone = false,
}`DateDisplayPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

DateOnly

Signature:

DateOnly({ date, ...props }: Omit<DateDisplayProps, "format">): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ date, ...props }Omit<DateDisplayProps, "format">Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

DateTime

Signature:

DateTime({ date, ...props }: Omit<DateDisplayProps, "format">): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ date, ...props }Omit<DateDisplayProps, "format">Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TimeOnly

Signature:

TimeOnly({ date, ...props }: Omit<DateDisplayProps, "format">): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ date, ...props }Omit<DateDisplayProps, "format">Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

RelativeTime

Signature:

RelativeTime({ date, ...props }: Omit<DateDisplayProps, "format">): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ date, ...props }Omit<DateDisplayProps, "format">Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

RelativeTimeDisplay

Signature:

RelativeTimeDisplay({
  date,
  timezone,
  fallback = 'Invalid date',
  className = '',
  showTooltip = true,
  updateInterval = 60000, // 1 minute
  disableAutoUpdate = false,
  addSuffix = true,
  includeSeconds = false,
}: RelativeTimeDisplayProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
date,
timezone,
fallback = 'Invalid date',
className = '',
showTooltip = true,
updateInterval = 60000, // 1 minute
disableAutoUpdate = false,
addSuffix = true,
includeSeconds = false,
}`RelativeTimeDisplayPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useRelativeTime

Signature:

useRelativeTime(date: string | Date, options?: { timezone?: string; updateInterval?: number; disableAutoUpdate?: boolean; addSuffix?: boolean; includeSeconds?: boolean; }): string

Parameters:

ParameterTypeRequiredDescription
datestring | DateYes
options{ timezone?: string; updateInterval?: number; disableAutoUpdate?: boolean; addSuffix?: boolean; includeSeconds?: boolean; }No

Returns:

string -

InputField

Signature:

InputField(props: { id: string; name?: string; label: string; extra?: string; placeholder: string; variant?: string; state?: string; disabled?: boolean; type?: string; onChange?: any; value?: any; onBlur?: any; helperText?: string; required?: boolean; error?: string; }): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
props{ id: string; name?: string; label: string; extra?: string; placeholder: string; variant?: string; state?: string; disabled?: boolean; type?: string; onChange?: any; value?: any; onBlur?: any; helperText?: string; required?: boolean; error?: string; }Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TagsField

Signature:

TagsField(props: { [x: string]: any; id?: string; label?: string; placeholder?: string; placeholderTags?: { name: string; id: number; }[]; onChange?: any; }): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
props{ [x: string]: any; id?: string; label?: string; placeholder?: string; placeholderTags?: { name: string; id: number; }[]; onChange?: any; }Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

InputField

Signature:

InputField(props: { id: string; label: string; extra?: string; placeholder: string; state?: string; disabled?: boolean; cols: number; rows: number; onChange?: any; }): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
props{ id: string; label: string; extra?: string; placeholder: string; state?: string; disabled?: boolean; cols: number; rows: number; onChange?: any; }Yes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

isRichTextConfig

Type guard to check if a config is a valid RichTextConfig

Signature:

isRichTextConfig(config: any): boolean

Parameters:

ParameterTypeRequiredDescription
configanyYes

Returns:

boolean -

validateRichTextConfig

Validates and sanitizes a RichTextConfig object

Signature:

validateRichTextConfig(config: RichTextConfig): RichTextConfigValidation

Parameters:

ParameterTypeRequiredDescription
configRichTextConfigYes

Returns:

RichTextConfigValidation -

MarkdownEditor

Signature:

MarkdownEditor({
  content,
  onChange,
  onSave
}: MarkdownEditorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
content,
onChange,
onSave
}`MarkdownEditorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

MarkdownViewer

Signature:

MarkdownViewer({ content }: MarkdownViewerProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ content }MarkdownViewerPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

LongTermMemoryList

Table/list of long-term memories

Displays memories with:

  • Content text (truncated preview)
  • Memory type badge
  • Topics/tags
  • User (optional)
  • Created timestamp
  • Edit/Delete actions

Signature:

LongTermMemoryList({
  memories,
  isLoading = false,
  onEdit,
  onDelete,
  onSelect,
  searchQuery,
  emptyMessage = 'No long-term memories found',
  colorMode = 'light',
  showUserColumn = false,
}: LongTermMemoryListProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
memories,
isLoading = false,
onEdit,
onDelete,
onSelect,
searchQuery,
emptyMessage = 'No long-term memories found',
colorMode = 'light',
showUserColumn = false,
}`LongTermMemoryListPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { LongTermMemoryList } from '@epicdm/flowstate-app-framework';

function MemoryAdmin({ memories }) {
  return (
    <LongTermMemoryList
      memories={memories}
      onEdit={(m) => openEditModal(m)}
      onDelete={(m) => handleDelete(m.id)}
    />
  );
}

MemoryAnalytics

Memory usage analytics dashboard

Signature:

MemoryAnalytics({
  data,
  isLoading = false,
  error,
  onRefresh,
  orgName,
}: MemoryAnalyticsProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
data,
isLoading = false,
error,
onRefresh,
orgName,
}`MemoryAnalyticsPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemoryAnalytics } from '@epicdm/flowstate-app-framework';

function AnalyticsDashboard({ data, isLoading, onRefresh }) {
  return (
    <MemoryAnalytics
      data={data}
      isLoading={isLoading}
      onRefresh={onRefresh}
      orgName="My Organization"
    />
  );
}

MemoryControls

Memory controls dropdown for chat header

Includes a status indicator button that opens a dropdown with:

  • Memory status information
  • Clear memory button with confirmation
  • Link to memory manager (optional)

Signature:

MemoryControls({
  isEnabled,
  messageCount,
  lastUpdated,
  isLoading = false,
  hasError = false,
  errorMessage,
  onClear,
  onOpenManager,
  colorMode = 'light',
  className = '',
}: MemoryControlsProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
isEnabled,
messageCount,
lastUpdated,
isLoading = false,
hasError = false,
errorMessage,
onClear,
onOpenManager,
colorMode = 'light',
className = '',
}`MemoryControlsPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemoryControls } from '@epicdm/flowstate-app-framework';

function ChatHeader() {
  const { clear, messageCount, isLoading } = useMemorySession(client, sessionId, namespace);

  return (
    <MemoryControls
      isEnabled={true}
      messageCount={messageCount}
      isLoading={isLoading}
      onClear={clear}
      onOpenManager={() => navigate('/memory')}
    />
  );
}

MemorySearchPanel

Unified search interface for all memory types

Signature:

MemorySearchPanel({
  results,
  isLoading = false,
  error,
  workingMemoryCount = 0,
  longTermMemoryCount = 0,
  currentQuery = '',
  onSearch,
  onClear,
  onResultSelect,
  debounceMs = 300,
  placeholder = 'Search all memories...',
  emptyMessage = 'No results found',
  showFilters = true,
}: MemorySearchPanelProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
results,
isLoading = false,
error,
workingMemoryCount = 0,
longTermMemoryCount = 0,
currentQuery = '',
onSearch,
onClear,
onResultSelect,
debounceMs = 300,
placeholder = 'Search all memories...',
emptyMessage = 'No results found',
showFilters = true,
}`MemorySearchPanelPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemorySearchPanel, useSearchAllMemory, useMemoryClient } from '@epicdm/flowstate-app-framework';

function MemorySearch({ namespace }) {
  const { client } = useMemoryClient();
  const { results, isLoading, error, search, clearResults } = useSearchAllMemory(client, namespace);

  return (
    <MemorySearchPanel
      results={results}
      isLoading={isLoading}
      error={error}
      onSearch={(query, opts) => search(query, opts)}
      onClear={clearResults}
      onResultSelect={(r) => console.log('Selected:', r)}
    />
  );
}

MemorySessionDetail

Detailed view of a memory session's conversation

Displays:

  • Header with session ID, message count, and token count
  • Conversation summary (if available)
  • Full message history with role indicators
  • Actions for refresh and delete

Signature:

MemorySessionDetail({
  sessionId,
  memory,
  isLoading = false,
  onBack,
  onDelete,
  onRefresh,
  showActions = true,
  colorMode = 'light',
}: MemorySessionDetailProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
sessionId,
memory,
isLoading = false,
onBack,
onDelete,
onRefresh,
showActions = true,
colorMode = 'light',
}`MemorySessionDetailPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemorySessionDetail } from '@epicdm/flowstate-app-framework';
import { useMemorySession } from '@epicdm/flowstate-app-framework';

function SessionDetailPage({ sessionId }: { sessionId: string }) {
  const { memory, isLoading, refresh, clear } = useMemorySession(client, sessionId, namespace);

  return (
    <MemorySessionDetail
      sessionId={sessionId}
      memory={memory}
      isLoading={isLoading}
      onBack={() => navigate('/memory')}
      onRefresh={refresh}
      onDelete={clear}
    />
  );
}

MemorySessionList

Table of memory sessions for admin view

Displays sessions with:

  • Session ID (truncated)
  • User information (optional)
  • Agent identifier
  • Message count
  • Token usage
  • Last updated timestamp
  • View/Delete actions

Signature:

MemorySessionList({
  sessions,
  isLoading = false,
  onSelectSession,
  onDeleteSession,
  selectedSessionId,
  showUserColumn = true,
  emptyMessage = 'No memory sessions yet',
  colorMode = 'light',
}: MemorySessionListProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
sessions,
isLoading = false,
onSelectSession,
onDeleteSession,
selectedSessionId,
showUserColumn = true,
emptyMessage = 'No memory sessions yet',
colorMode = 'light',
}`MemorySessionListPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemorySessionList } from '@epicdm/flowstate-app-framework';
import { useMemorySessions } from '@epicdm/flowstate-app-framework';

function SessionsAdmin() {
  const { sessions, isLoading, deleteSession } = useMemorySessions(client, namespace);

  return (
    <MemorySessionList
      sessions={sessions}
      isLoading={isLoading}
      onSelectSession={(s) => navigate(`/memory/${s.sessionId}`)}
      onDeleteSession={deleteSession}
    />
  );
}

MemoryStatusIndicator

Memory status indicator for chat header

Shows a brain icon with optional message count badge. Visual states:

  • Enabled: Blue brain icon (filled) with count badge
  • Disabled: Gray brain icon (outline)
  • Error: Red brain icon with error styling
  • Loading: Pulsing animation

Signature:

MemoryStatusIndicator({
  isEnabled,
  messageCount,
  isLoading = false,
  hasError = false,
  errorMessage,
  onClick,
  colorMode = 'light',
  className = '',
}: MemoryStatusIndicatorProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
isEnabled,
messageCount,
isLoading = false,
hasError = false,
errorMessage,
onClick,
colorMode = 'light',
className = '',
}`MemoryStatusIndicatorPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { MemoryStatusIndicator } from '@epicdm/flowstate-app-framework';

function ChatHeader() {
  return (
    <MemoryStatusIndicator
      isEnabled={true}
      messageCount={12}
      onClick={() => setShowMemoryControls(true)}
    />
  );
}

getColorFamilyByIndex

Get a color family by its index (0-7). Used when org has a configured colorSchemeIndex in metadata.

Signature:

getColorFamilyByIndex(index: number): OrgColorFamily

Parameters:

ParameterTypeRequiredDescription
indexnumberYes

Returns:

OrgColorFamily -

getOrgColorFamily

Get the color family for an organization. If the org has a configured colorSchemeIndex, use that. Otherwise, uses a hash to assign the same color family to the same org across sessions.

Signature:

getOrgColorFamily(orgId: string, colorSchemeIndex?: number): OrgColorFamily

Parameters:

ParameterTypeRequiredDescription
orgIdstringYes- The organization ID
colorSchemeIndexnumberNo- Optional configured color scheme index from org.metadata

Returns:

OrgColorFamily -

getColorSchemeForOrg

Get the color scheme for a specific badge type within an org's color family. All badges for the same org will use colors from the same family.

Signature:

getColorSchemeForOrg(orgId: string, badgeType: BadgeType, colorSchemeIndex?: number): ColorScheme

Parameters:

ParameterTypeRequiredDescription
orgIdstringYes- The organization ID (determines the color family)
badgeTypeBadgeTypeYes- The type of badge (determines which accent to use)
colorSchemeIndexnumberNo- Optional configured color scheme index from org.metadata

Returns:

ColorScheme -

getBadgeClasses

Get CSS classes for a badge with the given color scheme

Signature:

getBadgeClasses(scheme: ColorScheme): string

Parameters:

ParameterTypeRequiredDescription
schemeColorSchemeYes

Returns:

string -

getColorScheme

Legacy function - get a color scheme based on any ID

Signature:

getColorScheme(id: string): ColorScheme

Parameters:

ParameterTypeRequiredDescription
idstringYes

Returns:

ColorScheme -

ColorSchemeSelector

Color scheme selector for organizations. Displays a visual grid of color options with org/workspace/project/milestone preview.

Signature:

ColorSchemeSelector({
  value,
  onChange,
  label = 'Color Scheme',
  className = '',
}: ColorSchemeSelectorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
value,
onChange,
label = 'Color Scheme',
className = '',
}`ColorSchemeSelectorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

OrgDetailPage

Organization Detail Page

Displays organization details and lists all workspaces under the organization. Provides UI for creating, editing, and deleting workspaces.

Signature:

OrgDetailPage({
  db,
  orgId,
  userId,
  onBack,
  onWorkspaceCreated,
  onWorkspaceUpdated,
  onWorkspaceDeleted,
  className = '',
}: OrgDetailPageProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
db,
orgId,
userId,
onBack,
onWorkspaceCreated,
onWorkspaceUpdated,
onWorkspaceDeleted,
className = '',
}`OrgDetailPagePropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

OrgsPage

Organizations Management Page

Full-featured organization management page with automatic reactive updates. Uses the useOrgs hook from

Signature:

OrgsPage({
  db,
  userId,
  onOrgCreated,
  onOrgUpdated,
  onOrgDeleted,
  onOrgClick,
  className = '',
}: OrgsPageProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
db,
userId,
onOrgCreated,
onOrgUpdated,
onOrgDeleted,
onOrgClick,
className = '',
}`OrgsPagePropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { OrgsPage } from '@epicdm/flowstate-app-framework';

function OrganizationsView() {
const { db } = useDatabase();
const userId = 'user_123';

return (
<OrgsPage
db={db}
userId={userId}
onOrgCreated={(org) => console.log('Created:', org)}
onOrgUpdated={(org) => console.log('Updated:', org)}
onOrgDeleted={(orgId) => console.log('Deleted:', orgId)}
/>
);
}

OrgWorkspaceSelector

Org and Workspace Selector Component

Compact dropdown selectors for organization and workspace selection with automatic reactive updates. Uses context which internally uses useOrgs and useWorkspaces hooks from

Signature:

OrgWorkspaceSelector({
  onOrgChange,
  onWorkspaceChange,
  showCreateButtons = true,
  onCreateOrg,
  onCreateWorkspace,
  showManageButtons = true,
  onManageOrg,
  onManageWorkspace,
  compact = false,
  orientation,
  colorMode,
  className = '',
}: OrgWorkspaceSelectorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onOrgChange,
onWorkspaceChange,
showCreateButtons = true,
onCreateOrg,
onCreateWorkspace,
showManageButtons = true,
onManageOrg,
onManageWorkspace,
compact = false,
orientation,
colorMode,
className = '',
}`OrgWorkspaceSelectorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { OrgWorkspaceSelector } from '@epicdm/flowstate-app-framework';
import { useNavigate } from 'react-router-dom';

function AppHeader() {
const { db } = useDatabase();
const navigate = useNavigate();

return (
<OrgWorkspaceSelector
db={db}
compact={true}
showCreateButtons={true}
showManageButtons={true}
onOrgChange={(org) => console.log('Org changed:', org)}
onWorkspaceChange={(ws) => console.log('Workspace changed:', ws)}
onCreateOrg={() => navigate('/orgs/new')}
onCreateWorkspace={() => navigate('/workspaces/new')}
onManageOrg={() => navigate('/orgs')}
onManageWorkspace={() => navigate('/workspaces')}
/>
);
}

WorkspacesPage

Workspaces Management Page

Full-featured workspace management page with automatic reactive updates. Uses the useWorkspaces hook from

Signature:

WorkspacesPage({
  db,
  userId,
  onWorkspaceCreated,
  onWorkspaceUpdated,
  onWorkspaceDeleted,
  className = '',
}: WorkspacesPageProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
db,
userId,
onWorkspaceCreated,
onWorkspaceUpdated,
onWorkspaceDeleted,
className = '',
}`WorkspacesPagePropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { WorkspacesPage } from '@epicdm/flowstate-app-framework';

function WorkspacesView() {
const { db } = useDatabase();
const userId = 'user_123';

return (
<WorkspacesPage
db={db}
userId={userId}
onWorkspaceCreated={(ws) => console.log('Created:', ws)}
onWorkspaceUpdated={(ws) => console.log('Updated:', ws)}
onWorkspaceDeleted={(wsId) => console.log('Deleted:', wsId)}
/>
);
}

RAGAdminDashboard

Signature:

RAGAdminDashboard({
  colorMode = 'light',
}: RAGAdminDashboardProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
colorMode = 'light',
}`RAGAdminDashboardPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

RAGPipelineStatusCard

Signature:

RAGPipelineStatusCard({
  pipeline,
  colorMode = 'light',
}: RAGPipelineStatusCardProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
pipeline,
colorMode = 'light',
}`RAGPipelineStatusCardPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

RAGRecentErrors

Signature:

RAGRecentErrors({
  errors,
  colorMode = 'light',
}: RAGRecentErrorsProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
errors,
colorMode = 'light',
}`RAGRecentErrorsPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

RAGServiceHealth

Signature:

RAGServiceHealth({
  connections,
  colorMode = 'light',
}: RAGServiceHealthProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
connections,
colorMode = 'light',
}`RAGServiceHealthPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

RAGSyncCollections

Signature:

RAGSyncCollections({
  collections,
  colorMode = 'light',
}: RAGSyncCollectionsProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
collections,
colorMode = 'light',
}`RAGSyncCollectionsPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

RAGVectorStoreStats

Signature:

RAGVectorStoreStats({
  vectorStore,
  colorMode = 'light',
}: RAGVectorStoreStatsProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
vectorStore,
colorMode = 'light',
}`RAGVectorStoreStatsPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

ConnectionStatusIndicator

ConnectionStatusIndicator Component

Displays a visual indicator of the RxDB server connection status with color-coded badges, icons, and optional labels and tooltips.

Visual Indicators:

  • Connected: Green badge with Wifi icon
  • Disconnected: Gray badge with WifiOff icon
  • Connecting: Blue badge with spinning Loader icon
  • Error: Red badge with AlertCircle icon

Signature:

ConnectionStatusIndicator({
  status,
  serverName,
  lastConnected,
  showLabel = false,
  className,
}: ConnectionStatusIndicatorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
status,
serverName,
lastConnected,
showLabel = false,
className,
}`ConnectionStatusIndicatorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element - A badge component displaying the connection status

ServerConfigDialog

ServerConfigDialog Component

Fully controlled dialog for adding or editing RxDB server configurations. Includes comprehensive form validation, accessibility features, and optional connection testing.

Features:

  • Full server configuration form with validation
  • Required and optional field handling
  • URL and database name format validation
  • Optional connection testing before save
  • Accessible form labels and ARIA attributes
  • Keyboard navigation support
  • Loading and error states
  • Edit and Add modes based on server prop

Signature:

ServerConfigDialog({
  open,
  onClose,
  server,
  defaultValues,
  onSave,
  onTest,
  isLoading = false,
  error = null,
}: ServerConfigDialogProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
open,
onClose,
server,
defaultValues,
onSave,
onTest,
isLoading = false,
error = null,
}`ServerConfigDialogPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ServerSelector

ServerSelector component for managing and switching between RxDB server configurations.

This is a controlled component that displays a dropdown for server selection, shows connection status, and provides optional server management capabilities.

Features:

  • Server selection dropdown with visual indicators
  • Connection status badge (green when connected)
  • Server status indicators (connected/active/inactive)
  • Last connected timestamp display
  • Optional "Manage Servers" button
  • Keyboard accessible
  • Disabled state while connected (prevents accidental disconnection)
  • Loading state support
  • Fully controlled (no internal state)

Signature:

ServerSelector({
  servers,
  activeServer,
  onServerChange,
  onManageServers,
  isConnected = false,
  isLoading = false,
  className,
  showLastConnected = true,
  showConnectionStatus = true,
}: ServerSelectorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
servers,
activeServer,
onServerChange,
onManageServers,
isConnected = false,
isLoading = false,
className,
showLastConnected = true,
showConnectionStatus = true,
}`ServerSelectorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element - Rendered ServerSelector component

ServerIndicator

ServerIndicator Component

Displays the current server connection status in a compact, nav-friendly format. Shows a globe icon when connected to a server, or a hard drive icon when offline.

Visual States:

  • Connected: Globe icon + server label (green accent)
  • Offline: Hard drive icon + "Offline" text (muted)
  • No Server: Globe icon + "No Server" text (muted)

Signature:

ServerIndicator({
  currentServer,
  isOffline,
  onClick,
  className,
}: ServerIndicatorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
currentServer,
isOffline,
onClick,
className,
}`ServerIndicatorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element - A clickable button indicating current server/offline status

ServerSwitcherMenu

ServerSwitcherMenu Component

A dropdown menu for switching between servers. Displays available servers with visual indicators for the current selection, plus options for offline mode and server management.

Features:

  • Lists all available servers with radio-style selection
  • Shows "Offline (local)" option for local-first usage
  • "Add Server" action at bottom
  • "Manage Servers" action at bottom
  • Visual indicator for current selection via aria-current
  • Accessible menu structure with proper ARIA roles

Signature:

ServerSwitcherMenu({
  servers,
  currentServerId,
  isOffline,
  onSelectServer,
  onAddServer,
  onManageServers,
  className = '',
}: ServerSwitcherMenuProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
servers,
currentServerId,
isOffline,
onSelectServer,
onAddServer,
onManageServers,
className = '',
}`ServerSwitcherMenuPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

<ServerSwitcherMenu
  servers={[{ id: 'srv1', url: 'https://acme.flowstate.com', ... }]}
  currentServerId="srv1"
  isOffline={false}
  onSelectServer={(id) => switchServer(id)}
  onAddServer={() => openAddServerModal()}
  onManageServers={() => navigate('/settings/servers')}
/>

SettingsModal

SettingsModal component

Signature:

SettingsModal({
  isOpen,
  onClose,
  initialTab,
  paneRenderers = {},
}: SettingsModalProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
isOpen,
onClose,
initialTab,
paneRenderers = {},
}`SettingsModalPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

BottomPanel

BottomPanel component

Signature:

BottomPanel({
  defaultTab,
  minHeight = 100,
  maxHeight = 500,
  defaultHeight = 250,
  panelRenderers = {},
  colorMode = 'dark',
  headerHeight = '2rem',
  onDimensionsChange,
}: BottomPanelProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
defaultTab,
minHeight = 100,
maxHeight = 500,
defaultHeight = 250,
panelRenderers = {},
colorMode = 'dark',
headerHeight = '2rem',
onDimensionsChange,
}`BottomPanelPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Header component

Signature:

Header({
  title = 'FlowState',
  standalone = false,
  colorMode = 'light',
  leftContent,
  rightContent,
  logo,
  showHeaderActions = true,
  showMobileMenuButton = false,
  onMobileMenuClick,
  className = '',
  height,
}: HeaderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
title = 'FlowState',
standalone = false,
colorMode = 'light',
leftContent,
rightContent,
logo,
showHeaderActions = true,
showMobileMenuButton = false,
onMobileMenuClick,
className = '',
height,
}`HeaderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

HeaderActions

HeaderActions component

Signature:

HeaderActions({ className = '', colorMode = 'dark' }: HeaderActionsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ className = '', colorMode = 'dark' }HeaderActionsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

RightSidePanel

RightSidePanel component

Signature:

RightSidePanel({
  children,
  title,
  subtitle,
  minWidth = 320,
  maxWidth = 600,
  colorMode = 'dark',
  headerHeight = '3rem',
  onDimensionsChange,
  onClose,
}: RightSidePanelProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
title,
subtitle,
minWidth = 320,
maxWidth = 600,
colorMode = 'dark',
headerHeight = '3rem',
onDimensionsChange,
onClose,
}`RightSidePanelPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Sidebar component

Signature:

Sidebar({
  title = 'FlowState',
  links = [],
  standalone = false,
  colorMode = 'dark',
  basePath = '',
  logo,
  footer,
  collapsed: controlledCollapsed,
  onCollapsedChange,
  expandedWidth = 256,
  collapsedWidth = 64,
  className = '',
  isActive: customIsActive,
}: SidebarProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
title = 'FlowState',
links = [],
standalone = false,
colorMode = 'dark',
basePath = '',
logo,
footer,
collapsed: controlledCollapsed,
onCollapsedChange,
expandedWidth = 256,
collapsedWidth = 64,
className = '',
isActive: customIsActive,
}`SidebarPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ViewStateWrapper

ViewStateWrapper component

Signature:

ViewStateWrapper({
  children,
  initialState,
  paneRenderers,
}: ViewStateWrapperProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
initialState,
paneRenderers,
}`ViewStateWrapperPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

StatusBar

StatusBar component

Signature:

StatusBar({
  onExecuteCommand,
  className = '',
  leftItems,
  centerItems,
  rightItems,
  dynamicRenderers = {},
}: StatusBarProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onExecuteCommand,
className = '',
leftItems,
centerItems,
rightItems,
dynamicRenderers = {},
}`StatusBarPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

StatusBarItem

StatusBarItem component

Signature:

StatusBarItem({ item, onExecuteCommand, children }: StatusBarItemProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ item, onExecuteCommand, children }StatusBarItemPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TerminalContextBreadcrumb

TerminalContextBreadcrumb component

Signature:

TerminalContextBreadcrumb({
  orgId,
  workspaceId,
  projectId,
  milestoneId,
  taskId,
  colorMode = 'dark',
  maxLabelLength = 20,
}: TerminalContextBreadcrumbProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
orgId,
workspaceId,
projectId,
milestoneId,
taskId,
colorMode = 'dark',
maxLabelLength = 20,
}`TerminalContextBreadcrumbPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TerminalSessionItem

TerminalSessionItem component

Signature:

TerminalSessionItem({
  session,
  isSelected,
  onClick,
  onRename,
  onClose,
  onDelete,
  onEdit,
  colorMode = 'dark',
}: TerminalSessionItemProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
session,
isSelected,
onClick,
onRename,
onClose,
onDelete,
onEdit,
colorMode = 'dark',
}`TerminalSessionItemPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TerminalSessionList

TerminalSessionList component

Signature:

TerminalSessionList({
  sessions,
  selectedSessionId,
  onSelectSession,
  onCreateSession,
  onRenameSession,
  onCloseSession,
  onDeleteSession,
  onEditSession,
  width = 200,
  colorMode = 'dark',
  collapsed = false,
  onToggleCollapse,
  isLoading = false,
}: TerminalSessionListProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
sessions,
selectedSessionId,
onSelectSession,
onCreateSession,
onRenameSession,
onCloseSession,
onDeleteSession,
onEditSession,
width = 200,
colorMode = 'dark',
collapsed = false,
onToggleCollapse,
isLoading = false,
}`TerminalSessionListPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TerminalTab

TerminalTab component

Signature:

TerminalTab({
  tab,
  colorMode = 'dark',
  renderTerminal,
  renderCreateForm,
  renderEditForm,
  renderThemePicker,
  sessions: externalSessions,
  selectedSessionId: externalSelectedId,
  isCreating: externalIsCreating,
  isEditing: externalIsEditing,
  editingSessionId: externalEditingSessionId,
  isLoadingServerSessions = false,
  onSelectSession: externalOnSelect,
  onCreateSession: externalOnCreate,
  onRenameSession: externalOnRename,
  onCloseSession: externalOnClose,
  onDeleteSession: externalOnDelete,
  onEditSession: externalOnEdit,
  onCancelCreate: externalOnCancelCreate,
  onCancelEdit: externalOnCancelEdit,
  sessionListWidth = 180,
  showSessionList = true,
}: TerminalTabProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
tab,
colorMode = 'dark',
renderTerminal,
renderCreateForm,
renderEditForm,
renderThemePicker,
sessions: externalSessions,
selectedSessionId: externalSelectedId,
isCreating: externalIsCreating,
isEditing: externalIsEditing,
editingSessionId: externalEditingSessionId,
isLoadingServerSessions = false,
onSelectSession: externalOnSelect,
onCreateSession: externalOnCreate,
onRenameSession: externalOnRename,
onCloseSession: externalOnClose,
onDeleteSession: externalOnDelete,
onEditSession: externalOnEdit,
onCancelCreate: externalOnCancelCreate,
onCancelEdit: externalOnCancelEdit,
sessionListWidth = 180,
showSessionList = true,
}`TerminalTabPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

TerminalThemePicker

Signature:

TerminalThemePicker({
  presets,
  activeThemeId,
  onSelectTheme,
  colorMode = 'dark',
}: TerminalThemePickerProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
presets,
activeThemeId,
onSelectTheme,
colorMode = 'dark',
}`TerminalThemePickerPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

UserSelector

User Selector Component

Compact dropdown selector for user selection with automatic reactive updates. Uses AuthContext which internally uses useUsers hook from

Signature:

UserSelector({
  onUserChange,
  orientation = 'horizontal',
  colorMode,
  className = '',
}: UserSelectorProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onUserChange,
orientation = 'horizontal',
colorMode,
className = '',
}`UserSelectorPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { UserSelector } from '@epicdm/flowstate-app-framework';

function AppHeader() {
return (
<UserSelector
orientation="horizontal"
colorMode="dark"
onUserChange={(user) => console.log('User changed:', user)}
/>
);
}

UsersPage

Users Management Page

Simple user management page with automatic reactive updates. Uses the useUsers hook from

Signature:

UsersPage({
  db,
  onUserCreated,
  onUserUpdated,
  onUserDeleted,
  className = '',
}: UsersPageProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
db,
onUserCreated,
onUserUpdated,
onUserDeleted,
className = '',
}`UsersPagePropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { UsersPage } from '@epicdm/flowstate-app-framework';

function UsersView() {
const { db } = useDatabase();

return (
<UsersPage
db={db}
onUserCreated={(user) => console.log('Created:', user)}
onUserUpdated={(user) => console.log('Updated:', user)}
onUserDeleted={(userId) => console.log('Deleted:', userId)}
/>
);
}

useRAGAdminStatus

Hook to fetch and poll RAG admin status.

Fetches from /api/rag-sync/admin/status with JWT auth. Supports polling with configurable interval and manual refresh. Preserves last-known-good data when fetch fails (isStale=true).

Signature:

useRAGAdminStatus(options?: UseRAGAdminStatusOptions): UseRAGAdminStatusReturn

Parameters:

ParameterTypeRequiredDescription
optionsUseRAGAdminStatusOptionsNo- Configuration options

Returns:

UseRAGAdminStatusReturn - Status data, loading state, and refresh function

useRAGPolling

Hook for managing polling intervals with visibility-aware behavior.

Automatically pauses polling when the tab is hidden and resumes when visible again. Cleans up properly on unmount or interval change.

Signature:

useRAGPolling(callback: () => void, interval: number): void

Parameters:

ParameterTypeRequiredDescription
callback() => voidYes- Function to call on each interval tick
intervalnumberYes- Polling interval in milliseconds, or null to disable

useGlobalLoadingContext

Hook to access global loading context

Signature:

useGlobalLoadingContext(): UseGlobalLoadingReturn

Returns:

UseGlobalLoadingReturn -

ContextMenu

Context menu that appears at a specific position

Signature:

ContextMenu({
  contextType,
  anchor,
  onClose,
  contextData = {},
}: ContextMenuProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
contextType,
anchor,
onClose,
contextData = {},
}`ContextMenuPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

ContextMenuOverlay

Overlay that captures clicks outside the context menu

Signature:

ContextMenuOverlay({
  children,
  onClose,
}: { children: React.ReactNode; onClose: () => void; }): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
children,
onClose,
}`{ children: React.ReactNode; onClose: () => void; }Yes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Renders a single menu item

Signature:

MenuItem({ item, onClick, className }: MenuItemProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
{ item, onClick, className }MenuItemPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Renders menu items for a specific location

Signature:

MenuRenderer({
  location,
  context = {},
  className,
  horizontal = false,
  onItemClick,
}: MenuRendererProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
location,
context = {},
className,
horizontal = false,
onItemClick,
}`MenuRendererPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Horizontal separator line for menu groups

Signature:

MenuSeparator({ className }: MenuSeparatorProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
{ className }MenuSeparatorPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

CommandPalette

Main command palette component

Signature:

CommandPalette(): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

formatBrowserStorage

Format browser storage for display

Signature:

formatBrowserStorage(estimate: StorageEstimate): string

Parameters:

ParameterTypeRequiredDescription
estimateStorageEstimateYes

Returns:

string -

formatStorageTooltip

Format storage tooltip with details

Signature:

formatStorageTooltip(estimate: StorageEstimate): string

Parameters:

ParameterTypeRequiredDescription
estimateStorageEstimateYes

Returns:

string -

getBrowserStorageEstimate

Get browser storage estimate Uses the Storage API available in modern browsers

Signature:

getBrowserStorageEstimate(): Promise<StorageEstimate>

Returns:

Promise<StorageEstimate> -

getBrowserStorageContributions

Get all contributions from this plugin

Signature:

getBrowserStorageContributions(): StatusBarItemContribution[]

Returns:

StatusBarItemContribution[] -

formatDockerStatus

Format Docker status for display

Signature:

formatDockerStatus(containers: DockerContainerInfo[]): string

Parameters:

ParameterTypeRequiredDescription
containersDockerContainerInfo[]Yes

Returns:

string -

formatDockerTooltip

Format Docker tooltip with container details

Signature:

formatDockerTooltip(containers: DockerContainerInfo[]): string

Parameters:

ParameterTypeRequiredDescription
containersDockerContainerInfo[]Yes

Returns:

string -

getDockerStatusIcon

Get icon based on Docker status

Signature:

getDockerStatusIcon(containers: DockerContainerInfo[]): string

Parameters:

ParameterTypeRequiredDescription
containersDockerContainerInfo[]Yes

Returns:

string -

getDockerStatusContributions

Get all contributions from this plugin

Signature:

getDockerStatusContributions(): StatusBarItemContribution[]

Returns:

StatusBarItemContribution[] -

getEngineStatusContributions

Get all contributions from this plugin

Signature:

getEngineStatusContributions(): StatusBarItemContribution[]

Returns:

StatusBarItemContribution[] -

Get all default footer contributions Returns all status bar items from system plugins

Signature:

getAllFooterContributions(): any[]

Returns:

any[] -

formatRamUsage

Format RAM usage for display

Signature:

formatRamUsage(memory: MemoryUsage): string

Parameters:

ParameterTypeRequiredDescription
memoryMemoryUsageYes

Returns:

string -

formatRamTooltip

Format RAM tooltip with details

Signature:

formatRamTooltip(memory: MemoryUsage): string

Parameters:

ParameterTypeRequiredDescription
memoryMemoryUsageYes

Returns:

string -

formatCpuUsage

Format CPU usage for display

Signature:

formatCpuUsage(cpu: CpuUsage): string

Parameters:

ParameterTypeRequiredDescription
cpuCpuUsageYes

Returns:

string -

formatCpuTooltip

Format CPU tooltip with details

Signature:

formatCpuTooltip(cpu: CpuUsage): string

Parameters:

ParameterTypeRequiredDescription
cpuCpuUsageYes

Returns:

string -

formatDiskUsage

Format disk usage for display

Signature:

formatDiskUsage(disk: DiskUsage): string

Parameters:

ParameterTypeRequiredDescription
diskDiskUsageYes

Returns:

string -

formatDiskTooltip

Format disk tooltip with details

Signature:

formatDiskTooltip(disk: DiskUsage): string

Parameters:

ParameterTypeRequiredDescription
diskDiskUsageYes

Returns:

string -

getSystemResourcesContributions

Get all contributions from this plugin

Signature:

getSystemResourcesContributions(): StatusBarItemContribution[]

Returns:

StatusBarItemContribution[] -

formatBytes

Format bytes to human-readable string

Signature:

formatBytes(bytes: number, decimals?: number): string

Parameters:

ParameterTypeRequiredDescription
bytesnumberYes
decimalsnumberNo

Returns:

string -

formatPercent

Format percentage

Signature:

formatPercent(value: number, decimals?: number): string

Parameters:

ParameterTypeRequiredDescription
valuenumberYes
decimalsnumberNo

Returns:

string -

formatVersion

Format version for display

Signature:

formatVersion(version: string): string

Parameters:

ParameterTypeRequiredDescription
versionstringYes

Returns:

string -

formatVersionTooltip

Format version tooltip

Signature:

formatVersionTooltip(version: string, platform?: string): string

Parameters:

ParameterTypeRequiredDescription
versionstringYes
platformstringNo

Returns:

string -

formatUpdateAvailable

Format update available text

Signature:

formatUpdateAvailable(result: UpdateCheckResult): string

Parameters:

ParameterTypeRequiredDescription
resultUpdateCheckResultYes

Returns:

string -

getUpdateIndicatorContributions

Get all contributions from this plugin

Signature:

getUpdateIndicatorContributions(): StatusBarItemContribution[]

Returns:

StatusBarItemContribution[] -

useReplication

Hook for managing sync progress during onboarding

Connects to the onboarding context to get server configuration, creates the server config in ServerConfigService, and monitors the replication process.

Signature:

useReplication(): UseReplicationResult

Returns:

UseReplicationResult - Sync state and control functions

Examples:

const { startSync, syncProgress, syncStatus, syncError, retrySync } = useReplication();

useEffect(() => {
  startSync();
}, [startSync]);

if (syncStatus === 'error') {
  return <button onClick={retrySync}>Retry</button>;
}

OnboardingContainer

OnboardingContainer

Full-screen centered container for the onboarding flow.

Features:

  • Branded background with gradient pattern
  • Centered card layout with shadow
  • FlowState logo header
  • Step progress dots navigation
  • Start over link footer

Signature:

OnboardingContainer({
  children,
  currentStep,
  totalSteps,
  onStartOver,
  showStartOver = true,
  className,
}: OnboardingContainerProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
children,
currentStep,
totalSteps,
onStartOver,
showStartOver = true,
className,
}`OnboardingContainerPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

Examples:

import { OnboardingContainer } from '@epicdm/flowstate-app-framework';

function OnboardingScreen() {
  return (
    <OnboardingContainer
      currentStep={1}
      totalSteps={5}
      onStartOver={() => console.log('Starting over')}
    >
      <h2>Welcome!</h2>
      <p>Let's get you set up.</p>
    </OnboardingContainer>
  );
}

OnboardingProvider

OnboardingProvider

Manages onboarding flow state including:

  • Current step tracking
  • Step completion status
  • Data collection from steps
  • Progress persistence to localStorage
  • Navigation between steps

Signature:

OnboardingProvider({
  children,
  steps,
  config = {},
}: OnboardingProviderProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
children,
steps,
config = {},
}`OnboardingProviderPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

useOnboarding

Hook to access onboarding context

Signature:

useOnboarding(): PathAwareOnboardingContextValue

Returns:

PathAwareOnboardingContextValue -

OnboardingFlow

OnboardingFlow Component

Main UI component for the onboarding flow with full-screen layout. Renders the current step within the OnboardingContainer for a branded, immersive onboarding experience.

Features:

  • Full-screen branded container with FlowState logo
  • Step progress dots navigation
  • Start over link for resetting onboarding
  • Responsive centered card layout

Signature:

OnboardingFlow({
  className = '',
  showStartOver = true,
}: OnboardingFlowProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
className = '',
showStartOver = true,
}`OnboardingFlowPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

Examples:

import { OnboardingFlow } from '@epicdm/flowstate-app-framework';

function App() {
  return (
    <OnboardingProvider steps={onboardingSteps}>
      <OnboardingFlow />
    </OnboardingProvider>
  );
}

QuickNavModal

Main quick navigation modal component

Signature:

QuickNavModal(): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

CustomApiConfigFields

Signature:

CustomApiConfigFields({
  providerConfig,
  credentials,
  onProviderConfigChange,
  onCredentialsChange,
}: CustomApiConfigFieldsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
providerConfig,
credentials,
onProviderConfigChange,
onCredentialsChange,
}`CustomApiConfigFieldsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncConfigCard

Signature:

SyncConfigCard({
  config,
  onEdit,
  onDelete,
  onToggle,
}: SyncConfigCardProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
config,
onEdit,
onDelete,
onToggle,
}`SyncConfigCardPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncConfigForm

Signature:

SyncConfigForm({
  config,
  providers,
  workspaceId,
  onSubmit,
  onCancel,
}: SyncConfigFormProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
config,
providers,
workspaceId,
onSubmit,
onCancel,
}`SyncConfigFormPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncHistoryLog

Signature:

SyncHistoryLog({
  entries,
  maxEntries = 50,
}: SyncHistoryLogProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
entries,
maxEntries = 50,
}`SyncHistoryLogPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncOAuthCallbackPage

Signature:

SyncOAuthCallbackPage({
  onSuccess,
  onError,
  successRedirectUrl = '/sync',
  errorRedirectUrl = '/sync',
}: SyncOAuthCallbackPageProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onSuccess,
onError,
successRedirectUrl = '/sync',
errorRedirectUrl = '/sync',
}`SyncOAuthCallbackPagePropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncSettingsTab

Signature:

SyncSettingsTab({
  workspaceId,
  orgId,
  userId,
  db,
}: SyncSettingsTabProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
workspaceId,
orgId,
userId,
db,
}`SyncSettingsTabPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncStatusDisplay

Signature:

SyncStatusDisplay({
  state,
  isRunning,
  onStart,
  onStop,
  onSyncNow,
}: SyncStatusDisplayProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
state,
isRunning,
onStart,
onStop,
onSyncNow,
}`SyncStatusDisplayPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

loadContributedProviders

Load all contributed sync providers from plugin manifests

Signature:

loadContributedProviders(): Promise<void>

Returns:

Promise<void> -

watchForContributedProviders

Subscribe to new provider contributions and load them

Signature:

watchForContributedProviders(): () => void

Returns:

() => void -

useSyncConfig

React hook for managing sync configurations

Provides reactive data loading from RxDB with CRUD operations for sync configurations. Automatically refreshes when underlying data changes.

Signature:

useSyncConfig(options: UseSyncConfigOptions): UseSyncConfigResult

Parameters:

ParameterTypeRequiredDescription
optionsUseSyncConfigOptionsYes

Returns:

UseSyncConfigResult -

Examples:

import { useSyncConfig } from '@epicdm/flowstate-app-framework';

function SyncConfigList() {
  const { configs, isLoading, create, remove } = useSyncConfig({
    workspaceId: 'workspace-1',
    db: database,
  });

  if (isLoading) return <Spinner />;

  return (
    <div>
      {configs.map(config => (
        <div key={config.id}>
          {config.name} - {config.providerId}
          <button onClick={() => remove(config.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
}

useSyncHistory

Signature:

useSyncHistory({
  workspaceId,
}: UseSyncHistoryOptions): UseSyncHistoryResult

Parameters:

ParameterTypeRequiredDescription
`{
workspaceId,
}`UseSyncHistoryOptionsYes

Returns:

UseSyncHistoryResult -

registerOAuthConfig

Register an OAuth provider configuration

Signature:

registerOAuthConfig(config: OAuthProviderConfig): void

Parameters:

ParameterTypeRequiredDescription
configOAuthProviderConfigYes- The OAuth provider configuration to register

Examples:

registerOAuthConfig({
  providerId: 'ynab',
  clientId: 'your-client-id',
  redirectUri: 'https://app.example.com/oauth/callback/ynab',
  authorizationEndpoint: 'https://app.ynab.com/oauth/authorize',
  tokenEndpoint: 'https://app.ynab.com/oauth/token',
  tokenProxyEndpoint: '/api/oauth/ynab/token',
  scopes: ['read-only'],
});

getOAuthConfig

Get an OAuth provider configuration by provider ID

Signature:

getOAuthConfig(providerId: string): OAuthProviderConfig

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID to look up

Returns:

OAuthProviderConfig - The OAuth provider configuration, or undefined if not found

Examples:

const ynabConfig = getOAuthConfig('ynab');
if (ynabConfig) {
  console.log('YNAB client ID:', ynabConfig.clientId);
}

getAllOAuthConfigs

Get all registered OAuth provider configurations

Signature:

getAllOAuthConfigs(): OAuthProviderConfig[]

Returns:

OAuthProviderConfig[] - Array of all registered OAuth provider configurations

Examples:

const allConfigs = getAllOAuthConfigs();
console.log('Registered providers:', allConfigs.map(c => c.providerId));

hasOAuthConfig

Check if an OAuth provider configuration exists

Signature:

hasOAuthConfig(providerId: string): boolean

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID to check

Returns:

boolean - True if the configuration exists, false otherwise

Examples:

if (hasOAuthConfig('github')) {
  console.log('GitHub OAuth is configured');
}

removeOAuthConfig

Remove an OAuth provider configuration (primarily for testing)

Signature:

removeOAuthConfig(providerId: string): boolean

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID to remove

Returns:

boolean - True if the configuration was removed, false if it didn't exist

clearOAuthConfigs

Clear all OAuth provider configurations (primarily for testing)

Signature:

clearOAuthConfigs(): void

getOAuthEnvVarNames

Get standard environment variable names for a provider

Signature:

getOAuthEnvVarNames(providerId: string, prefix?: string): OAuthEnvVarNames

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID
prefixstringNo- Optional prefix for variable names

Returns:

OAuthEnvVarNames - Object with environment variable names

createOAuthConfigFromEnv

Create an OAuth provider configuration from environment variables

This function looks for environment variables with the pattern:

  • {PREFIX}{PROVIDER_ID}_CLIENT_ID
  • {PREFIX}{PROVIDER_ID}_REDIRECT_URI
  • etc.

Signature:

createOAuthConfigFromEnv(providerId: string, options?: CreateOAuthConfigFromEnvOptions): OAuthProviderConfig

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID (e.g., 'ynab', 'github')
optionsCreateOAuthConfigFromEnvOptionsNo- Options for creating the configuration

Returns:

OAuthProviderConfig - The OAuth provider configuration, or null if required env vars are missing

Examples:

// With VITE_ prefix and env vars:
// VITE_YNAB_CLIENT_ID, VITE_YNAB_REDIRECT_URI, etc.
const config = createOAuthConfigFromEnv('ynab', {
  envPrefix: 'VITE_',
  defaultScopes: ['read-only'],
});

registerOAuthConfigFromEnv

Register an OAuth provider configuration from environment variables

Convenience function that creates and registers a config in one step.

Signature:

registerOAuthConfigFromEnv(providerId: string, options?: CreateOAuthConfigFromEnvOptions): boolean

Parameters:

ParameterTypeRequiredDescription
providerIdstringYes- The provider ID
optionsCreateOAuthConfigFromEnvOptionsNo- Options for creating the configuration

Returns:

boolean - True if registration was successful, false if env vars were missing

Examples:

if (registerOAuthConfigFromEnv('ynab', { envPrefix: 'VITE_' })) {
  console.log('YNAB OAuth configured from environment');
}

generateState

Generate a cryptographically secure random state string

Signature:

generateState(): string

Returns:

string - A 64-character hex string

Examples:

const state = generateState();
// Returns something like: 'a1b2c3d4e5f6...'

storeOAuthState

Store OAuth state data in session storage for CSRF protection

Signature:

storeOAuthState(state: string, workspaceId: string, providerId: string): void

Parameters:

ParameterTypeRequiredDescription
statestringYes- The random state string
workspaceIdstringYes- The workspace ID initiating the flow
providerIdstringYes- The OAuth provider ID

Examples:

const state = generateState();
storeOAuthState(state, 'workspace-123', 'ynab');

verifyOAuthState

Verify OAuth state and retrieve workspace/provider info

This function verifies the state matches what was stored and clears the session storage after verification.

Signature:

verifyOAuthState(state: string, providerId: string): { workspaceId: string | null; providerId: string | null; }

Parameters:

ParameterTypeRequiredDescription
statestringYes- The state string from the OAuth callback
providerIdstringYes- The expected provider ID

Returns:

{ workspaceId: string \| null; providerId: string \| null; } - Object with workspaceId if valid, or null values if invalid

Examples:

const result = verifyOAuthState(callbackState, 'ynab');
if (result.workspaceId) {
  // State is valid, proceed with token exchange
}

buildAuthorizationUrl

Build the authorization URL for an OAuth provider

Signature:

buildAuthorizationUrl(workspaceId: string, providerId: string, configOverrides?: Partial<OAuthProviderConfig>): string

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID initiating the flow
providerIdstringYes- The OAuth provider ID
configOverridesPartial<OAuthProviderConfig>No- Optional config overrides

Returns:

string - The authorization URL string

Examples:

const authUrl = buildAuthorizationUrl('workspace-123', 'ynab');
// Returns: https://app.ynab.com/oauth/authorize?client_id=...&state=...

startOAuthFlow

Start the OAuth authorization flow by redirecting to the provider

Signature:

startOAuthFlow(workspaceId: string, providerId: string, configOverrides?: Partial<OAuthProviderConfig>): void

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID initiating the flow
providerIdstringYes- The OAuth provider ID
configOverridesPartial<OAuthProviderConfig>No- Optional config overrides

Examples:

// In a button click handler
startOAuthFlow('workspace-123', 'ynab');
// User is redirected to YNAB authorization page

handleOAuthCallback

Handle OAuth callback and exchange authorization code for tokens

Signature:

handleOAuthCallback(code: string, state: string, providerId: string, configOverrides?: Partial<OAuthProviderConfig>): Promise<OAuthCallbackResult>

Parameters:

ParameterTypeRequiredDescription
codestringYes- The authorization code from the callback
statestringYes- The state string from the callback
providerIdstringYes- The OAuth provider ID
configOverridesPartial<OAuthProviderConfig>No- Optional config overrides

Returns:

Promise<OAuthCallbackResult> - Result object with success status and workspace/provider info

Examples:

// In your callback handler
const params = new URLSearchParams(window.location.search);
const result = await handleOAuthCallback(
  params.get('code')!,
  params.get('state')!,
  'ynab'
);

if (result.success) {
  console.log('Connected to workspace:', result.workspaceId);
} else {
  console.error('OAuth failed:', result.error);
}

refreshAccessToken

Refresh the access token using the refresh token

Signature:

refreshAccessToken(workspaceId: string, providerId: string, configOverrides?: Partial<OAuthProviderConfig>): Promise<boolean>

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID
configOverridesPartial<OAuthProviderConfig>No- Optional config overrides

Returns:

Promise<boolean> - True if refresh was successful, false otherwise

Examples:

const refreshed = await refreshAccessToken('workspace-123', 'ynab');
if (!refreshed) {
  // Need to re-authenticate
  startOAuthFlow('workspace-123', 'ynab');
}

getValidAccessToken

Get a valid access token, refreshing if necessary

This function checks if the current token is expired and automatically refreshes it if needed.

Signature:

getValidAccessToken(workspaceId: string, providerId: string, configOverrides?: Partial<OAuthProviderConfig>): Promise<string>

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID
configOverridesPartial<OAuthProviderConfig>No- Optional config overrides

Returns:

Promise<string> - The access token string, or null if unavailable

Examples:

const accessToken = await getValidAccessToken('workspace-123', 'ynab');
if (accessToken) {
  // Make API call with token
  const response = await fetch('https://api.ynab.com/v1/budgets', {
    headers: { 'Authorization': `Bearer ${accessToken}` },
  });
} else {
  // Need to re-authenticate
  startOAuthFlow('workspace-123', 'ynab');
}

storeOAuthTokens

Store OAuth tokens for a workspace and provider

Signature:

storeOAuthTokens(workspaceId: string, providerId: string, tokens: OAuthTokens, metadata?: Record<string, unknown>): void

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID
tokensOAuthTokensYes- The OAuth tokens to store
metadataRecord<string, unknown>No- Optional provider-specific metadata

Examples:

storeOAuthTokens('workspace-1', 'ynab', {
  accessToken: 'xxx',
  refreshToken: 'yyy',
  expiresAt: Date.now() + 3600000,
  tokenType: 'Bearer',
});

getOAuthTokens

Retrieve OAuth tokens for a workspace and provider

Signature:

getOAuthTokens(workspaceId: string, providerId: string): OAuthTokens

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID

Returns:

OAuthTokens - The OAuth tokens, or null if not found

Examples:

const tokens = getOAuthTokens('workspace-1', 'ynab');
if (tokens) {
  console.log('Access token:', tokens.accessToken);
}

getOAuthStoredData

Retrieve full OAuth stored data for a workspace and provider

Signature:

getOAuthStoredData(workspaceId: string, providerId: string): OAuthStoredData

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID

Returns:

OAuthStoredData - The full OAuth stored data, or null if not found

Examples:

const data = getOAuthStoredData('workspace-1', 'ynab');
if (data) {
  console.log('Connected at:', data.connectedAt);
  console.log('Tokens:', data.tokens);
}

updateOAuthTokens

Update OAuth tokens for an existing connection

Preserves existing metadata and connection timestamp, only updates tokens and records the refresh timestamp.

Signature:

updateOAuthTokens(workspaceId: string, providerId: string, tokens: OAuthTokens): void

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID
tokensOAuthTokensYes- The new OAuth tokens

Examples:

// After token refresh
updateOAuthTokens('workspace-1', 'ynab', {
  accessToken: 'new-token',
  refreshToken: 'new-refresh-token',
  expiresAt: Date.now() + 3600000,
  tokenType: 'Bearer',
});

clearOAuthTokens

Clear OAuth tokens for a workspace and provider (disconnect)

Signature:

clearOAuthTokens(workspaceId: string, providerId: string): void

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID

Examples:

// Disconnect YNAB from workspace
clearOAuthTokens('workspace-1', 'ynab');

isOAuthConnected

Check if a provider is connected for a workspace

Signature:

isOAuthConnected(workspaceId: string, providerId: string): boolean

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID
providerIdstringYes- The OAuth provider ID

Returns:

boolean - True if connected, false otherwise

Examples:

if (isOAuthConnected('workspace-1', 'ynab')) {
  console.log('YNAB is connected');
}

isTokenExpired

Check if OAuth tokens are expired or about to expire

Signature:

isTokenExpired(tokens: OAuthTokens, bufferMs?: number): boolean

Parameters:

ParameterTypeRequiredDescription
tokensOAuthTokensYes- The OAuth tokens to check
bufferMsnumberNo- Buffer time in milliseconds before expiration (default: 60000ms / 1 minute)

Returns:

boolean - True if tokens are expired or will expire within buffer time

Examples:

const tokens = getOAuthTokens('workspace-1', 'ynab');
if (tokens && isTokenExpired(tokens)) {
  // Need to refresh token
  await refreshAccessToken('workspace-1', 'ynab');
}

getTokenTimeRemaining

Get the remaining time until token expiration

Signature:

getTokenTimeRemaining(tokens: OAuthTokens): number

Parameters:

ParameterTypeRequiredDescription
tokensOAuthTokensYes- The OAuth tokens to check

Returns:

number - Remaining time in milliseconds, or null if no expiration set

Examples:

const tokens = getOAuthTokens('workspace-1', 'ynab');
const remaining = tokens ? getTokenTimeRemaining(tokens) : null;
if (remaining !== null && remaining < 300000) {
  console.log('Token expires in less than 5 minutes');
}

getOAuthConnectionsForWorkspace

Get all OAuth connections for a workspace

Signature:

getOAuthConnectionsForWorkspace(workspaceId: string): string[]

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID

Returns:

string[] - Array of provider IDs that have stored tokens

Examples:

const connectedProviders = getOAuthConnectionsForWorkspace('workspace-1');
console.log('Connected:', connectedProviders); // ['ynab', 'github']

clearAllOAuthConnectionsForWorkspace

Clear all OAuth connections for a workspace

Signature:

clearAllOAuthConnectionsForWorkspace(workspaceId: string): void

Parameters:

ParameterTypeRequiredDescription
workspaceIdstringYes- The workspace ID

Examples:

// Disconnect all providers when user logs out
clearAllOAuthConnectionsForWorkspace('workspace-1');

isOAuthTokens

Type guard to check if an object is a valid OAuthTokens

Signature:

isOAuthTokens(obj: unknown): boolean

Parameters:

ParameterTypeRequiredDescription
objunknownYes

Returns:

boolean -

isOAuthStoredData

Type guard to check if an object is a valid OAuthStoredData

Signature:

isOAuthStoredData(obj: unknown): boolean

Parameters:

ParameterTypeRequiredDescription
objunknownYes

Returns:

boolean -

isOAuthProviderConfig

Type guard to check if an object is a valid OAuthProviderConfig

Signature:

isOAuthProviderConfig(obj: unknown): boolean

Parameters:

ParameterTypeRequiredDescription
objunknownYes

Returns:

boolean -

useOAuthConnection

React hook for managing OAuth connections

Provides a unified interface for connecting to OAuth providers, managing tokens, and handling connection state.

Signature:

useOAuthConnection(options: UseOAuthConnectionOptions): UseOAuthConnectionResult

Parameters:

ParameterTypeRequiredDescription
optionsUseOAuthConnectionOptionsYes- Hook options

Returns:

UseOAuthConnectionResult - Hook result with state and actions

Examples:

import { useOAuthConnection } from '@epicdm/flowstate-app-framework/sync/oauth';

function YNABConnectionButton() {
  const {
    isConnected,
    isLoading,
    connectedAt,
    error,
    connect,
    disconnect,
    getAccessToken,
  } = useOAuthConnection({
    workspaceId: 'workspace-123',
    providerId: 'ynab',
  });

  if (isLoading) {
    return <span>Checking connection...</span>;
  }

  if (isConnected) {
    return (
      <div>
        <span>Connected since {connectedAt}</span>
        <button onClick={disconnect}>Disconnect</button>
        <button onClick={async () => {
          const token = await getAccessToken();
          if (token) {
            // Make API call
          }
        }}>
          Sync Data
        </button>
      </div>
    );
  }

  return (
    <div>
      {error && <span className="error">{error}</span>}
      <button onClick={connect}>Connect to YNAB</button>
    </div>
  );
}

registerBuiltInProviders

Register all built-in sync providers with the registry.

This function should be called during application initialization to make built-in providers available for use.

Signature:

registerBuiltInProviders(): void

Examples:

import { registerBuiltInProviders } from '@epicdm/flowstate-app-framework/sync';

// Register providers at app startup
registerBuiltInProviders();

// Now providers are available from the registry
const registry = getSyncProviderRegistry();
const github = registry.get('github');

getBuiltInProviderIds

Get all built-in provider IDs.

Signature:

getBuiltInProviderIds(): string[]

Returns:

string[] - Array of built-in provider IDs

convertToUTC

Converts a date to UTC ISO 8601 string format for database storage

Signature:

convertToUTC(date: string | number | Date, timezone?: string): string

Parameters:

ParameterTypeRequiredDescription
datestring | number | DateYes- Date input (string, Date object, or number timestamp)
timezonestringNo- Source timezone (defaults to system timezone)

Returns:

string - UTC ISO 8601 string (e.g., "2024-12-07T14:30:00.000Z")

formatInTimezone

Formats a UTC string in the specified timezone for display

Signature:

formatInTimezone(utcString: string, timezone: string, formatString?: string): string

Parameters:

ParameterTypeRequiredDescription
utcStringstringYes- UTC ISO 8601 string from database
timezonestringYes- Target timezone for display
formatStringstringNo- Date format string (date-fns format)

Returns:

string - Formatted date string in target timezone

detectUserTimezone

Detects the user's current timezone using browser API

Signature:

detectUserTimezone(): string

Returns:

string - IANA timezone identifier (e.g., "America/New_York")

isValidTimezone

Validates if a timezone string is valid IANA timezone identifier

Signature:

isValidTimezone(timezone: string): boolean

Parameters:

ParameterTypeRequiredDescription
timezonestringYes- Timezone string to validate

Returns:

boolean - boolean indicating if timezone is valid

getCommonTimezones

Gets a list of common timezone options for UI dropdowns

Signature:

getCommonTimezones(): { label: string; value: string; }[]

Returns:

{ label: string; value: string; }[] - Array of timezone objects with label and value

datetimeLocalToUTC

Converts datetime-local input value to UTC for form submissions

Signature:

datetimeLocalToUTC(datetimeLocal: string, userTimezone: string): string

Parameters:

ParameterTypeRequiredDescription
datetimeLocalstringYes- Value from datetime-local input (YYYY-MM-DDTHH:MM)
userTimezonestringYes- User's timezone for interpreting the local time

Returns:

string - UTC ISO 8601 string

utcToDatetimeLocal

Converts UTC string to datetime-local format for form inputs

Signature:

utcToDatetimeLocal(utcString: string, userTimezone: string): string

Parameters:

ParameterTypeRequiredDescription
utcStringstringYes- UTC ISO 8601 string from database
userTimezonestringYes- User's timezone for displaying local time

Returns:

string - datetime-local formatted string (YYYY-MM-DDTHH:MM)

BrandingSettings

BrandingSettings component

Signature:

BrandingSettings({ tab }: BrandingSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }BrandingSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

DocsSettings

DocsSettings component

Signature:

DocsSettings({ tab }: DocsSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }DocsSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ExtensionsSettings

ExtensionsSettings component

Signature:

ExtensionsSettings({ tab }: ExtensionsSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }ExtensionsSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

GeneralSettings

GeneralSettings component

Signature:

GeneralSettings({ tab }: GeneralSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }GeneralSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

LoadingTestSettings

LoadingTestSettings component

Signature:

LoadingTestSettings({ tab }: LoadingTestSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }LoadingTestSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ToolsMcpSettings

ToolsMcpSettings component

Signature:

ToolsMcpSettings({ tab }: ToolsMcpSettingsProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
{ tab }ToolsMcpSettingsPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

CreateOrgStep

CreateOrgStep

Onboarding step for creating an organization. Integrates with OrgWorkspacePlugin to create and select the organization.

Signature:

CreateOrgStep({
  onNext,
  onBack,
  stepData,
  currentStepIndex,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
stepData,
currentStepIndex,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

CreateUserStep

CreateUserStep

Onboarding step for creating a user account. Integrates with AuthPlugin to create and select the user.

If stepData contains authUserId (from server login), the created user will be linked to the server AuthUser for authentication continuity.

Signature:

CreateUserStep({
  onNext,
  onBack,
  stepData,
  currentStepIndex,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
stepData,
currentStepIndex,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

CreateWorkspaceStep

CreateWorkspaceStep

Onboarding step for creating a workspace. Integrates with OrgWorkspacePlugin to create and select the workspace. This is typically the final step in the onboarding flow.

Signature:

CreateWorkspaceStep({
  onNext,
  onBack,
  stepData,
  currentStepIndex,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
stepData,
currentStepIndex,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ModeSelectionStep

ModeSelectionStep

First step of onboarding flow where user chooses between:

  • Connect to a Server (online mode with replication)
  • Work Offline (local-first mode)

Signature:

ModeSelectionStep(_props: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
_propsOnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

OrgWorkspaceSelectStep

OrgWorkspaceSelectStep

Final step in the server onboarding path - allows users to select their organization and workspace before starting the app.

Features:

  • Auto-proceeds when org and workspace can be unambiguously determined (e.g., user was auto-linked and has exactly one org with one workspace)
  • Organization dropdown (select from available orgs)
  • Workspace dropdown (filtered by selected org)
  • Auto-selects if only one option available
  • "Get Started" button with celebratory rocket icon

Signature:

OrgWorkspaceSelectStep({
  onNext,
  onBack,
  stepData,
  currentStepIndex,
}: OnboardingStepProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
stepData,
currentStepIndex,
}`OnboardingStepPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

ServerAuthStep

ServerAuthStep

Two-phase authentication step for the onboarding flow. Phase 1: User enters their email address and requests a verification code. Phase 2: User enters the 6-digit verification code to authenticate.

On successful authentication, passes authUserId and authUserEmail to onNext.

Signature:

ServerAuthStep({
  onNext,
  onBack,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

ServerConfigStep

ServerConfigStep

Step for entering the FlowState server URL. Validates the URL format before proceeding.

Signature:

ServerConfigStep({
  onNext,
  onBack,
  stepData,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
stepData,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

SyncProgressStep

SyncProgressStep

Shows sync progress during initial data replication. Auto-proceeds when sync completes, shows retry/skip options on error.

Features:

  • Progress bar showing sync progress (0-100%)
  • States: 'pending', 'syncing', 'complete', 'error'
  • Auto-proceed when sync completes
  • On error, show Retry and Skip buttons

Signature:

SyncProgressStep({
  onNext,
  onBack,
}: OnboardingStepProps): import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
}`OnboardingStepPropsYes

Returns:

import("/Users/sthornock/code/epic/epic-flowstate/node_modules/@types/react/jsx-runtime").JSX.Element -

UserSelectionStep

UserSelectionStep

Onboarding step that allows users to select/claim an existing unclaimed user profile or create a new one.

This step:

  • Auto-detects if the authenticated user already has a linked profile (authUserId matches) and auto-proceeds if so
  • Shows list of unclaimed user profiles (authUserId is null) for manual selection
  • Offers option to create a new profile

Signature:

UserSelectionStep({
  onNext,
  onBack,
  currentStepIndex,
}: OnboardingStepProps): React.ReactElement<unknown, string | React.JSXElementConstructor<any>>

Parameters:

ParameterTypeRequiredDescription
`{
onNext,
onBack,
currentStepIndex,
}`OnboardingStepPropsYes

Returns:

React.ReactElement<unknown, string \| React.JSXElementConstructor<any>> -

registerGitHubOAuth

Register GitHub OAuth configuration from environment variables.

Looks for environment variables with these prefixes (in order):

  1. VITE_ prefix (Vite apps)
  2. NEXT_PUBLIC_ prefix (Next.js apps) - uses literal access
  3. No prefix (server-side or custom setups)

Required variables:

  • {PREFIX}GITHUB_CLIENT_ID
  • {PREFIX}GITHUB_REDIRECT_URI
  • {PREFIX}GITHUB_AUTHORIZATION_ENDPOINT
  • {PREFIX}GITHUB_TOKEN_ENDPOINT
  • {PREFIX}GITHUB_TOKEN_PROXY_ENDPOINT
  • {PREFIX}GITHUB_SCOPES

Signature:

registerGitHubOAuth(): boolean

Returns:

boolean -

githubStateToStatus

Convert GitHub issue state to FlowState task status

Signature:

githubStateToStatus(state: "open" | "closed", stateReason?: "completed" | "not_planned" | "reopened"): string

Parameters:

ParameterTypeRequiredDescription
state"open" | "closed"Yes- GitHub issue state ('open' or 'closed')
stateReason"completed" | "not_planned" | "reopened"No- GitHub state reason ('completed', 'not_planned', 'reopened', or null)

Returns:

string - FlowState task status string

Examples:

githubStateToStatus('open'); // 'To Do'
githubStateToStatus('closed', 'completed'); // 'Done'
githubStateToStatus('closed', 'not_planned'); // 'Cancelled'

githubStateToCompleted

Convert GitHub issue state to FlowState task completed boolean

Signature:

githubStateToCompleted(state: "open" | "closed"): boolean

Parameters:

ParameterTypeRequiredDescription
state"open" | "closed"Yes- GitHub issue state ('open' or 'closed')

Returns:

boolean - True if the issue is closed, false otherwise

Examples:

githubStateToCompleted('open'); // false
githubStateToCompleted('closed'); // true

statusToGithubState

Convert FlowState task status to GitHub issue state

Signature:

statusToGithubState(status: string): { state: "open" | "closed"; state_reason?: "completed" | "not_planned" | "reopened"; }

Parameters:

ParameterTypeRequiredDescription
statusstringYes- FlowState task status

Returns:

{ state: "open" \| "closed"; state_reason?: "completed" \| "not_planned" \| "reopened"; } - GitHub issue state and optional state_reason

Examples:

statusToGithubState('To Do'); // { state: 'open' }
statusToGithubState('Done'); // { state: 'closed', state_reason: 'completed' }
statusToGithubState('Cancelled'); // { state: 'closed', state_reason: 'not_planned' }
Previous
Classes