Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat!(tests): e2e / integration tests (#3343)

teoc934b4608497
diff --git a/RUNNING_LOCALLY.md b/RUNNING_LOCALLY.md
index 5bf3854b98..f3f3e17b85 100644
--- a/RUNNING_LOCALLY.md
+++ b/RUNNING_LOCALLY.md
@@ -42,3 +42,39 @@ locally as they are not needed by the frontend when using dev assets.
You can run the following command to get the frontend running pointed to local
services `cd js/app && bun i && just local`.
+
+### Local E2E smoke test
+
+After `just setup`, run:
+
+```bash
+just local-e2e
+```
+
+This starts the local stack using `docker-compose.local-e2e.yml` overrides so
+services use local Postgres/LocalStack instead of shared dev assets, seeds
+deterministic smoke-test data, launches the frontend with local services and
+local bearer-token auth, and runs the Playwright smoke test.
+
+The local E2E seed scenario is guarded in code: it requires `LOCAL_E2E_SEED=true`
+and refuses any `DATABASE_URL` that is not the local Docker database
+`postgres://user:...@(localhost|127.0.0.1|postgres):5432/macrodb`.
+
+Shared fixture data lives under `rust/cloud-storage/seed_cli/seed`; local users
+are in `local_e2e/users.json`, Playwright tests can read the same data via
+`js/app/tests/e2e/fixtures/local-e2e-seed.ts`, and Rust tests can use
+`local_e2e_test_support`. The Rust helper also rejects non-local service URLs
+for mutating tests.
+
+To run the ignored Rust integration tests against the same local stack:
+
+```bash
+just local-e2e-rust
+```
+
+To run both Rust integration tests and Playwright tests after one stack startup
+and seed pass:
+
+```bash
+just local-e2e-all
+```
diff --git a/docker-compose.local-e2e.yml b/docker-compose.local-e2e.yml
new file mode 100644
index 0000000000..6e057c0834
--- /dev/null
+++ b/docker-compose.local-e2e.yml
@@ -0,0 +1,111 @@
+# Local E2E overrides for docker-compose.yml.
+#
+# The default .env can point at shared dev infrastructure. Keep Playwright's
+# deterministic smoke suite on local Docker dependencies by overriding the
+# service environment here and running compose with:
+# COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml
+
+x-local-e2e-env: &local-e2e-env
+ DATABASE_URL: postgres://user:password@postgres:5432/macrodb
+ DATABASE_URL_READONLY: postgres://user:password@postgres:5432/macrodb
+ LOCAL_AWS_URL: http://localstack:4566
+ AWS_ACCESS_KEY_ID: test
+ AWS_SECRET_ACCESS_KEY: test
+ AWS_REGION: us-east-1
+ AWS_DEFAULT_REGION: us-east-1
+ REDIS_URI: redis://redis:6379
+ DOCUMENT_STORAGE_SERVICE_REDIS_URI: redis://redis:6379
+
+ ATTACHMENT_BUCKET: macro-email-attachments
+ DOCUMENT_STORAGE_BUCKET: doc-storage
+ DOCX_DOCUMENT_UPLOAD_BUCKET: docx-upload
+ STATIC_STORAGE_BUCKET: static-file-storage
+ UPLOAD_STAGING_BUCKET: bulk-upload-staging
+
+ BULK_UPLOAD_REQUESTS_TABLE: bulk-upload
+ CONNECTION_GATEWAY_TABLE: connection-gateway-table
+ STATIC_FILE_SERVICE_DYNAMODB_TABLE_NAME: static-file-metadata
+
+ BACKFILL_QUEUE: email-service-backfill-queue
+ CHAT_DELETE_QUEUE: delete-chat-handler-queue
+ CONTACTS_QUEUE: contacts-queue
+ CONVERT_QUEUE: convert-service-queue
+ DOCUMENT_DELETE_QUEUE: delete-document-handler-queue
+ DOCUMENT_TEXT_EXTRACTOR_QUEUE: document-text-extractor-lambda-queue
+ EMAIL_SCHEDULED_QUEUE: email-service-scheduled-queue
+ GMAIL_INBOX_SYNC_QUEUE: email-service-gmail-inbox-sync-queue
+ GMAIL_INBOX_SYNC_RETRY_QUEUE: email-service-gmail-inbox-retry-queue
+ GMAIL_OPS_QUEUE: email-service-gmail-ops-queue
+ GMAIL_OPS_RETRY_QUEUE: email-service-gmail-ops-retry-queue
+ LINK_MANAGER_QUEUE: email-service-refresh-queue
+ NOTIFICATION_QUEUE: notification-queue
+ NOTIFICATION_INGRESS_QUEUE: http://localstack:4566/000000000000/notification-ingress-queue
+ PUSH_NOTIFICATION_EVENT_HANDLER_QUEUE: push-delivery-queue
+ SEARCH_EVENT_QUEUE: search-event-queue
+ SFS_DELETE_QUEUE: email-sfs-delete-queue
+ SFS_UPLOADER_QUEUE: email-service-sfs-mapper-queue
+ STATIC_FILE_SERVICE_S3_EVENT_QUEUE_URL: http://localstack:4566/000000000000/static-file-s3-event-notification-queue
+
+services:
+ authentication-service:
+ environment: *local-e2e-env
+ connection_gateway:
+ environment: *local-e2e-env
+ contacts_service:
+ environment: *local-e2e-env
+ # Not needed by the smoke suite. Keep this behind an inactive profile so
+ # missing cognition-only env vars do not block local E2E startup.
+ document_cognition_service:
+ profiles:
+ - local-e2e-unused
+ environment: *local-e2e-env
+ # lexical_service is intentionally disabled below for local E2E, so remove
+ # it from the base service dependency set if this profile is enabled manually.
+ depends_on: !override
+ - document_storage_service
+ - email_service
+ - static_file_service
+ - sync_service
+ document_storage_service:
+ environment: *local-e2e-env
+ document_upload_finalizer:
+ environment:
+ <<: *local-e2e-env
+ DOCUMENT_UPLOAD_FINALIZER_QUEUE_URL: http://localstack:4566/000000000000/document-upload-finalizer-queue
+ # lexical_service is intentionally disabled below for local E2E, so remove
+ # it from the base service dependency set.
+ depends_on: !override
+ - postgres
+ - sync_service
+ email_service:
+ environment: *local-e2e-env
+ # Not needed by the smoke suite. Keep this behind an inactive profile because
+ # it requires push/SNS/email notification env that is unrelated to local E2E.
+ notification_service:
+ profiles:
+ - local-e2e-unused
+ environment: *local-e2e-env
+ depends_on: !override
+ - redis
+ - authentication-service
+ - connection_gateway
+ - document_storage_service
+ search_processing_service:
+ environment: *local-e2e-env
+ static_file_service:
+ environment: *local-e2e-env
+ healthcheck:
+ test: ["CMD", "curl", "-f", "http://localhost:8080/api/health"]
+ unfurl_service:
+ environment: *local-e2e-env
+ image_proxy_service:
+ environment: *local-e2e-env
+ sync_service:
+ environment: *local-e2e-env
+ # Not needed by the smoke suite. Keep this behind an inactive profile because
+ # its Docker image currently depends on sibling js/lexical-core sources that
+ # are outside its build context.
+ lexical_service:
+ profiles:
+ - local-e2e-unused
+ environment: *local-e2e-env
diff --git a/docker-compose.yml b/docker-compose.yml
index 20a28fc163..5f93a580e9 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -267,7 +267,7 @@ services:
aliases:
- static-file-service
healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
+ test: ["CMD", "curl", "-f", "http://localhost:8080/api/health"]
interval: 30s
timeout: 10s
retries: 3
diff --git a/js/app/README.md b/js/app/README.md
index 951f27f373..4acc6b41df 100644
--- a/js/app/README.md
+++ b/js/app/README.md
@@ -15,6 +15,22 @@ If you have the [nix](https://nixos.org/learn/) package manager installed on you
## Using Claude/Playwright
To setup the authentication please make sure you create a `.env` file with **REFRESH_TOKEN** environment variable set to your dev macro refresh token. This can be found in your cookies.
+For the local smoke suite, prefer the repo-level harness:
+
+```bash
+just local-e2e
+```
+
+This starts the backend with local E2E compose overrides, seeds local fixture data, and runs `bun run local:e2e` with local bearer-token auth.
+
+The local smoke suite can import `localE2ESeed` from `tests/e2e/fixtures/local-e2e-seed.ts`. That helper loads the actual seed files used by `seed_cli` (`local_e2e/users.json`, `documents.json`, `channels.json`, and `channel_messages.json`) and exposes raw rows plus lookup maps by id/name/email. The small `local_e2e/manifest.json` only names the smoke aliases.
+
+For Playwright UI mode, run:
+
+```bash
+just local-e2e-ui
+```
+
## Tauri 🤝 Macro
We are currently in the process of bundling the frontend javascript application as a [Tauri](https://tauri.app/) app.
@@ -44,4 +60,3 @@ Run the Android App
Run the iOS App (note: I haven't had the chance to test this yet)
> `cargo tauri ios dev`
-
diff --git a/js/app/package.json b/js/app/package.json
index d55243baa4..63af494566 100644
--- a/js/app/package.json
+++ b/js/app/package.json
@@ -6,6 +6,8 @@
"dev": "cd packages/app && bun run --bun dev",
"build": "cd packages/app && MODE=development NODE_ENV=production bun run --bun build",
"test": "bunx vitest run",
+ "local:e2e": "LOCAL_E2E=true bunx playwright test",
+ "local:e2e:ui": "LOCAL_E2E=true bunx playwright test --ui",
"gen-api": "bun scripts/generate-api-schema.ts",
"gen-tools": "bun scripts/generate-dcs-tools.ts",
"check": "tsc --noEmit --skipLibCheck --project packages/app/tsconfig.json",
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 5756477e6b..4035cbc561 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -753,6 +753,8 @@ const SidebarLink = (props: SidebarLinkProps) => {
<Button
draggable={false}
variant="ghost"
+ data-sidebar-link={props.id}
+ data-active={isActive() ? '' : undefined}
class={cn(
'flex items-center justify-start group-data-[slim=true]/sidebar:justify-center text-sm gap-2 cursor-default w-full rounded-sm py-1 text-ink-extra-muted not-disabled:hover:bg-ink/3',
isActive() && 'bg-ink/6 not-disabled:hover:bg-ink/6 text-ink'
diff --git a/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx b/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx
index ed79c10dd9..a67704e502 100644
--- a/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx
@@ -126,7 +126,10 @@ export function EmptyStateInner(props: EmptyStateInnerProps) {
const handleFileUpload = useHandleFileUpload({ projectId: projectId() });
return (
- <div class="size-full flex items-center justify-center p-4 text-ink-muted">
+ <div
+ class="size-full flex items-center justify-center p-4 text-ink-muted"
+ data-soup-empty-state
+ >
<div class="panel w-full flex flex-col items-center size-full">
{getRandomArcanumGraphic()}
<p class="text-ink-muted font-mono">
@@ -182,7 +185,7 @@ export function EmptyStateInner(props: EmptyStateInnerProps) {
function AgentsEmptyState() {
return (
- <div class="size-full relative overflow-hidden">
+ <div class="size-full relative overflow-hidden" data-soup-empty-state>
<div class="absolute inset-0 flex flex-col items-center pointer-events-none p-4">
{getRandomArcanumGraphic('h-72 m-8 mt-32 @max-sm:mt-20 opacity-5')}
</div>
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index 62a3bddaae..170c2d0473 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -74,6 +74,10 @@ import { Resize } from '@core/component/Resize';
import { UserIcon } from '@core/component/UserIcon';
import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
+import {
+ soupListContainerAttribute,
+ soupListContainerSelector,
+} from '@core/dom-selectors';
import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { isMobile } from '@core/mobile/isMobile';
@@ -456,7 +460,7 @@ export const SoupView = (props: SoupViewProps) => {
disableLocalSearch={props.disableLocalSearch}
additionalEntities={props.additionalEntities}
>
- <div class="size-full flex flex-col">
+ <div class="size-full flex flex-col" data-list-view={activeListView()}>
<div class="flex flex-col w-full">
<SplitHeaderLeft>
<div
@@ -1374,7 +1378,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
const listEl = localEntityListRef();
if (!listEl) return undefined;
const scrollContainer = listEl.querySelector(
- '[data-soup-list-container]'
+ soupListContainerSelector
) as HTMLElement;
return scrollContainer || undefined;
}}
@@ -1485,7 +1489,7 @@ const SoupList = (props: SoupListProps) => {
itemSize={itemSize()}
bufferSize={overscan() * itemSize()}
onScroll={handleScroll}
- data-soup-list-container
+ {...soupListContainerAttribute}
>
{(row, i) => props.children(row, i)}
</VList>
diff --git a/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts b/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts
index b9e03be15e..16d3a2788f 100644
--- a/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/use-soup-navigation-hotkeys.ts
@@ -1,5 +1,6 @@
import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';
import type { SplitHandle } from '@app/component/split-layout/layoutManager';
+import { entityIdSelector } from '@core/dom-selectors';
import { createHotkeyGroup, registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import type { EntityData } from '@entity';
@@ -181,7 +182,7 @@ export const useSoupNavigationHotkeys = (
`[data-split-id="${splitHandle.id}"]`
);
if (!splitEl) return undefined;
- const entityEl = splitEl.querySelector(`[data-entity-id="${focusedId}"]`);
+ const entityEl = splitEl.querySelector(entityIdSelector(focusedId));
if (!entityEl) return undefined;
return entityEl.querySelector(
'button[data-collapsible-toggle]'
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index d101d26e85..dc3185793e 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -7,6 +7,10 @@ import { URL_PARAMS as EMAIL_PARAMS } from '@block-email/constants';
import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
import { fileTypeToBlockName } from '@core/constant/allBlocks';
+import {
+ ENTITY_ID_DATA_ATTRIBUTE,
+ entityIdSelector,
+} from '@core/dom-selectors';
import type { BlockOrchestrator } from '@core/orchestrator';
import type { DateValue } from '@core/util/date';
import { throwOnErr } from '@core/util/result';
@@ -279,13 +283,13 @@ export const restoreSoupFocus = async (
// up by focusing the soup container (which has `tabindex={-1}`) — that's
// what actually reactivates the hotkey scope.
if (entityId) {
- const entityEl = domRef.querySelector(`[data-entity-id="${entityId}"]`);
+ const entityEl = domRef.querySelector(entityIdSelector(entityId));
if (entityEl instanceof HTMLElement) entityEl.focus();
}
if (document.activeElement && domRef.contains(document.activeElement)) return;
- const firstEntityEl = domRef.querySelector('[data-entity-id]');
+ const firstEntityEl = domRef.querySelector(`[${ENTITY_ID_DATA_ATTRIBUTE}]`);
if (firstEntityEl instanceof HTMLElement) firstEntityEl.focus();
if (document.activeElement && domRef.contains(document.activeElement)) return;
diff --git a/js/app/packages/app/component/split-layout/SplitLayout.tsx b/js/app/packages/app/component/split-layout/SplitLayout.tsx
index 68cc40aa6b..d4ada279ed 100644
--- a/js/app/packages/app/component/split-layout/SplitLayout.tsx
+++ b/js/app/packages/app/component/split-layout/SplitLayout.tsx
@@ -2,6 +2,7 @@ import { useGlobalBlockOrchestrator } from '@app/component/GlobalAppState';
import { isSidebarVisible } from '@app/component/sidebarVisibility';
import { activeElement } from '@app/signal/focus';
import { Resize } from '@core/component/Resize';
+import { splitContainerSelector } from '@core/dom-selectors';
import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';
import { tabTitleSignal } from '@core/signal/tabTitle';
import { useNavigate } from '@solidjs/router';
@@ -44,7 +45,7 @@ type SplitLayoutContainerProps = {
function getParentSplitId(element: Element | null) {
if (!element || !element.isConnected) return null;
- const splitParent = element.closest('[data-split-container]');
+ const splitParent = element.closest(splitContainerSelector);
if (!splitParent) return null;
const splitId = splitParent.getAttribute('data-split-id');
if (!splitId) return null;
diff --git a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx b/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
index 7e841dcda8..0f17c67287 100644
--- a/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
+++ b/js/app/packages/app/component/split-layout/components/SplitPanel.tsx
@@ -2,6 +2,7 @@ import { createSoupState } from '@app/component/next-soup/create-soup-state';
import { SoupContextProvider } from '@app/component/next-soup/soup-context';
import { isListViewID, LIST_VIEW_ID } from '@app/constants/list-views';
import { globalSplitManager } from '@app/signal/splitLayout';
+import { splitContainerAttribute } from '@core/dom-selectors';
import { isMobile } from '@core/mobile/isMobile';
import { createElementSize } from '@solid-primitives/resize-observer';
import { cn, Panel } from '@ui';
@@ -163,7 +164,7 @@ export function SplitPanel(props: SplitPanelProps) {
attachHotKeys(ref);
}}
data-split-id={props.split.id}
- data-split-container
+ {...splitContainerAttribute}
data-modal={props.handle.isSpotLight()}
tabindex={-1}
>
diff --git a/js/app/packages/app/package.json b/js/app/packages/app/package.json
index d6a2f4b242..ea0b26f612 100644
--- a/js/app/packages/app/package.json
+++ b/js/app/packages/app/package.json
@@ -8,8 +8,8 @@
"dev": "vite -c vite.config.ts",
"build": "vite build -c vite.config.ts && bun run postbuild:semver",
"postbuild:semver": "echo $npm_package_version+$(git rev-parse --short HEAD) > ./dist/semver.txt",
- "preview:dev": "vite preview -c vite-ci.config.ts --outDir dist --base /app",
- "preview:prod": "vite preview -c vite-ci.config.ts --outDir dist --base /app",
+ "preview:dev": "vite preview -c vite.config.ts --outDir dist --base /app",
+ "preview:prod": "vite preview -c vite.config.ts --outDir dist --base /app",
"check": "tsc --noEmit --skipLibCheck",
"ddupload:dev": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $(cat ./dist/semver.txt) --minified-path-prefix https://dev.macro.com/app",
"ddupload:prod": "datadog-ci sourcemaps upload ./dist --service web-app --release-version $(cat ./dist/semver.txt) --minified-path-prefix https://macro.com/app"
diff --git a/js/app/packages/app/vite.base.ts b/js/app/packages/app/vite.base.ts
index b5f8da06d3..51ddd080e5 100644
--- a/js/app/packages/app/vite.base.ts
+++ b/js/app/packages/app/vite.base.ts
@@ -197,6 +197,13 @@ export const createAppViteConfig = (): UserConfigFn => {
],
},
},
+ preview: {
+ port: Number(process.env.PORT || 3000),
+ host: '0.0.0.0',
+ strictPort: true,
+ allowedHosts: true,
+ cors: true,
+ },
};
};
};
diff --git a/js/app/packages/core/dom-selectors.ts b/js/app/packages/core/dom-selectors.ts
new file mode 100644
index 0000000000..0d1d5dd849
--- /dev/null
+++ b/js/app/packages/core/dom-selectors.ts
@@ -0,0 +1,21 @@
+export const SPLIT_CONTAINER_DATA_ATTRIBUTE = 'data-split-container';
+export const SOUP_LIST_CONTAINER_DATA_ATTRIBUTE = 'data-soup-list-container';
+export const ENTITY_ID_DATA_ATTRIBUTE = 'data-entity-id';
+
+export const splitContainerAttribute = {
+ [SPLIT_CONTAINER_DATA_ATTRIBUTE]: true,
+} as const;
+export const soupListContainerAttribute = {
+ [SOUP_LIST_CONTAINER_DATA_ATTRIBUTE]: true,
+} as const;
+
+export function entityIdAttribute(entityId: string) {
+ return { [ENTITY_ID_DATA_ATTRIBUTE]: entityId } as const;
+}
+
+export const splitContainerSelector = `[${SPLIT_CONTAINER_DATA_ATTRIBUTE}]`;
+export const soupListContainerSelector = `[${SOUP_LIST_CONTAINER_DATA_ATTRIBUTE}]`;
+
+export function entityIdSelector(entityId: string): string {
+ return `[${ENTITY_ID_DATA_ATTRIBUTE}="${entityId}"]`;
+}
diff --git a/js/app/packages/entity/src/core/Root.tsx b/js/app/packages/entity/src/core/Root.tsx
index 4964bea274..84c9394feb 100644
--- a/js/app/packages/entity/src/core/Root.tsx
+++ b/js/app/packages/entity/src/core/Root.tsx
@@ -1,3 +1,4 @@
+import { entityIdAttribute } from '@core/dom-selectors';
import { cn } from '@ui';
import { type JSX, splitProps } from 'solid-js';
import type { EntityData } from '../types/entity';
@@ -11,7 +12,7 @@ export function Root(
<div
class={cn('entity-root group/entity', local.class)}
data-entity
- data-entity-id={local.entity.id}
+ {...entityIdAttribute(local.entity.id)}
{...rest}
>
{local.children}
diff --git a/js/app/playwright.config.ts b/js/app/playwright.config.ts
index 3a0b4cc466..b0a83a2eb7 100644
--- a/js/app/playwright.config.ts
+++ b/js/app/playwright.config.ts
@@ -1,5 +1,120 @@
+import { execFileSync } from 'node:child_process';
+
import { defineConfig, devices } from '@playwright/test';
+const isLocalE2E = process.env.LOCAL_E2E === 'true';
+const localE2EPort = process.env.PORT ?? '3000';
+
+function shellQuote(value: string): string {
+ return `'${value.replaceAll("'", "'\\''")}'`;
+}
+
+function commandOutput(error: unknown): string {
+ const processError = error as {
+ message?: string;
+ stderr?: Buffer | string;
+ stdout?: Buffer | string;
+ };
+
+ const stdout = processError.stdout?.toString().trim();
+ const stderr = processError.stderr?.toString().trim();
+ return [stderr, stdout, processError.message].filter(Boolean).join('\n');
+}
+
+function localE2EToken(): string {
+ if (process.env.LOCAL_JWT) {
+ return process.env.LOCAL_JWT;
+ }
+
+ try {
+ return execFileSync('bun', ['scripts/generate-local-e2e-token.ts'], {
+ encoding: 'utf8',
+ }).trim();
+ } catch (error) {
+ const details = commandOutput(error);
+ const message = [
+ 'Failed to generate LOCAL_JWT for LOCAL_E2E Playwright.',
+ 'Prefer running the repo-level harness: `just local-e2e`.',
+ 'If you are running Playwright directly, run `just local-e2e-seed` first and ensure `.env` exists from `just get_environment`.',
+ 'You can also bypass token generation by exporting LOCAL_JWT.',
+ details ? `Generator output:\n${details}` : undefined,
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+
+ console.error(message);
+ throw new Error(message);
+ }
+}
+
+function localE2EWebServerCommand(): string {
+ return [
+ `PORT=${shellQuote(localE2EPort)}`,
+ 'VITE_LOCAL_SERVERS=ALL',
+ 'VITE_ENABLE_BEARER_TOKEN_AUTH=true',
+ `LOCAL_JWT=${shellQuote(localE2EToken())}`,
+ 'bun run dev',
+ ].join(' ');
+}
+
+function ciPreviewWebServerCommand(): string {
+ return [
+ `PORT=${shellQuote(localE2EPort)}`,
+ 'bunx vite preview -c packages/app/vite.config.ts --outDir packages/app/dist',
+ ].join(' ');
+}
+
+const authenticatedProjects = isLocalE2E
+ ? [
+ {
+ name: 'local-chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ },
+ },
+ ]
+ : [
+ { name: 'setup', testMatch: /.*setup.ts/ },
+ // {
+ // name: 'editor',
+ // use: {
+ // ...devices['Desktop Chrome'],
+ // storageState: 'playwright/.auth/user.json',
+ // launchOptions: {
+ // /* This makes it so that layout that relies on a scrollbar renders correctly */
+ // ignoreDefaultArgs: ['--hide-scrollbars'],
+ // },
+ // },
+ // dependencies: ['setup'],
+ // // editor tests shouldn't ever run more than 15 seconds without cache
+ // timeout: 15000,
+ // },
+ {
+ name: 'chromium',
+ use: {
+ ...devices['Desktop Chrome'],
+ storageState: 'playwright/.auth/user.json',
+ },
+ dependencies: ['setup'],
+ },
+ {
+ name: 'firefox',
+ use: {
+ ...devices['Desktop Firefox'],
+ storageState: 'playwright/.auth/user.json',
+ },
+ dependencies: ['setup'],
+ },
+ {
+ name: 'webkit',
+ use: {
+ ...devices['Desktop Safari'],
+ storageState: 'playwright/.auth/user.json',
+ },
+ dependencies: ['setup'],
+ },
+ ];
+
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
@@ -24,7 +139,7 @@ export default defineConfig({
/* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
use: {
/* Base URL to use in actions like `await page.goto('/')`. */
- baseURL: 'http://localhost:3000/app',
+ baseURL: `http://localhost:${localE2EPort}/app`,
/* Only retain traces on the failed test. See https://playwright.dev/docs/trace-viewer */
trace: 'retain-on-failure',
},
@@ -33,45 +148,7 @@ export default defineConfig({
'{testDir}/{testFilePath}-snapshots/{arg}-{projectName}{ext}',
/* Configure projects for major browsers */
projects: [
- { name: 'setup', testMatch: /.*setup.ts/ },
- // {
- // name: 'editor',
- // use: {
- // ...devices['Desktop Chrome'],
- // storageState: 'playwright/.auth/user.json',
- // launchOptions: {
- // /* This makes it so that layout that relies on a scrollbar renders correctly */
- // ignoreDefaultArgs: ['--hide-scrollbars'],
- // },
- // },
- // dependencies: ['setup'],
- // // editor tests shouldn't ever run more than 15 seconds without cache
- // timeout: 15000,
- // },
- {
- name: 'chromium',
- use: {
- ...devices['Desktop Chrome'],
- storageState: 'playwright/.auth/user.json',
- },
- dependencies: ['setup'],
- },
- {
- name: 'firefox',
- use: {
- ...devices['Desktop Firefox'],
- storageState: 'playwright/.auth/user.json',
- },
- dependencies: ['setup'],
- },
- {
- name: 'webkit',
- use: {
- ...devices['Desktop Safari'],
- storageState: 'playwright/.auth/user.json',
- },
- dependencies: ['setup'],
- },
+ ...authenticatedProjects,
/* Test against mobile viewports. */
// {
@@ -106,11 +183,13 @@ export default defineConfig({
/* Run your local dev server before starting the tests */
webServer: {
- command: process.env.CI
- ? 'bunx vite preview -c packages/app/vite-ci.config.ts --outDir packages/app/dist'
- : 'bun run dev',
- url: 'http://localhost:3000/app',
- reuseExistingServer: !process.env.CI,
- timeout: 15000,
+ command: isLocalE2E
+ ? localE2EWebServerCommand()
+ : process.env.CI
+ ? ciPreviewWebServerCommand()
+ : 'bun run dev',
+ url: `http://localhost:${localE2EPort}/app`,
+ reuseExistingServer: !process.env.CI && !isLocalE2E,
+ timeout: isLocalE2E ? 60_000 : 15000,
},
});
diff --git a/js/app/scripts/generate-local-e2e-token.ts b/js/app/scripts/generate-local-e2e-token.ts
new file mode 100644
index 0000000000..f2b637e16b
--- /dev/null
+++ b/js/app/scripts/generate-local-e2e-token.ts
@@ -0,0 +1,45 @@
+#!/usr/bin/env bun
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+function findRepoRoot(): string {
+ let current = resolve(dirname(fileURLToPath(import.meta.url)));
+
+ while (true) {
+ if (existsSync(join(current, 'rust/cloud-storage/Cargo.toml'))) {
+ return current;
+ }
+
+ const parent = dirname(current);
+ if (parent === current) {
+ throw new Error('Could not find repo root from local E2E token script');
+ }
+ current = parent;
+ }
+}
+
+const repoRoot = findRepoRoot();
+const token = execFileSync(
+ 'cargo',
+ [
+ 'run',
+ '--quiet',
+ '--manifest-path',
+ join(repoRoot, 'rust/cloud-storage/Cargo.toml'),
+ '-p',
+ 'local_e2e_test_support',
+ '--bin',
+ 'generate_local_e2e_token',
+ '--',
+ ...process.argv.slice(2),
+ ],
+ {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'inherit'],
+ }
+).trim();
+
+console.log(token);
diff --git a/js/app/tests/e2e/fixtures/local-e2e-seed.ts b/js/app/tests/e2e/fixtures/local-e2e-seed.ts
new file mode 100644
index 0000000000..3d26dee403
--- /dev/null
+++ b/js/app/tests/e2e/fixtures/local-e2e-seed.ts
@@ -0,0 +1,178 @@
+import { existsSync, readFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+type SeedManifest = {
+ user: {
+ email: string;
+ };
+ documents: {
+ projectRoadmap: {
+ id: string;
+ name: string;
+ };
+ };
+ channels: {
+ general: {
+ id: string;
+ name: string;
+ message: string;
+ };
+ };
+};
+
+export type SeedUser = {
+ macro_user_id: string;
+ fusion_user_id: string;
+ user_id: string;
+ username: string;
+ email: string;
+ stripe_customer_id: string;
+ first_name: string;
+ last_name: string;
+ roles: string[];
+ tutorial_complete: boolean;
+ has_onboarding_documents: boolean;
+ has_trialed: boolean;
+ is_verified: boolean;
+};
+
+export type SeedDocument = {
+ document_id: string;
+ document_name: string;
+ file_name: string;
+ is_public: boolean;
+};
+
+export type SeedChannel = {
+ channel_id: string;
+ channel_name?: string;
+ channel_type:
+ | 'public'
+ | 'private'
+ | 'direct_message'
+ | 'organization'
+ | 'team';
+ participants: string[];
+};
+
+export type SeedMention = {
+ entity_type: 'document' | 'user' | string;
+ entity_id: string;
+};
+
+export type SeedChannelMessage = {
+ message_id: string;
+ channel_id: string;
+ sender_id: string;
+ content: string;
+ thread_id?: string;
+ entity_mentions?: SeedMention[];
+};
+
+function findRepoRoot(): string {
+ let current = resolve(dirname(fileURLToPath(import.meta.url)));
+
+ while (true) {
+ if (existsSync(join(current, 'rust/cloud-storage/seed_cli/seed'))) {
+ return current;
+ }
+
+ const parent = dirname(current);
+ if (parent === current) {
+ throw new Error('Could not find repo root from local e2e seed fixture');
+ }
+ current = parent;
+ }
+}
+
+function readJson<T>(relativePath: string): T {
+ return JSON.parse(
+ readFileSync(join(findRepoRoot(), relativePath), 'utf8')
+ ) as T;
+}
+
+function indexBy<T>(rows: readonly T[], key: (row: T) => string | undefined) {
+ const out = new Map<string, T>();
+ for (const row of rows) {
+ const value = key(row);
+ if (value) out.set(value, row);
+ }
+ return out;
+}
+
+function required<T>(value: T | undefined, description: string): T {
+ if (!value) throw new Error(`Missing local e2e seed fixture: ${description}`);
+ return value;
+}
+
+const manifest = readJson<SeedManifest>(
+ 'rust/cloud-storage/seed_cli/seed/local_e2e/manifest.json'
+);
+const users = readJson<SeedUser[]>(
+ 'rust/cloud-storage/seed_cli/seed/local_e2e/users.json'
+);
+const documents = readJson<SeedDocument[]>(
+ 'rust/cloud-storage/seed_cli/seed/documents/documents.json'
+);
+const channels = readJson<SeedChannel[]>(
+ 'rust/cloud-storage/seed_cli/seed/channels.json'
+);
+const channelMessages = readJson<SeedChannelMessage[]>(
+ 'rust/cloud-storage/seed_cli/seed/channel_messages.json'
+);
+
+const usersById = indexBy(users, (row) => row.user_id);
+const usersByEmail = indexBy(users, (row) => row.email);
+const usersByMacroUserId = indexBy(users, (row) => row.macro_user_id);
+const documentsById = indexBy(documents, (row) => row.document_id);
+const documentsByName = indexBy(documents, (row) => row.document_name);
+const channelsById = indexBy(channels, (row) => row.channel_id);
+const channelsByName = indexBy(channels, (row) => row.channel_name);
+const channelMessagesById = indexBy(channelMessages, (row) => row.message_id);
+
+function channelMessagesByChannelId(channelId: string): SeedChannelMessage[] {
+ return channelMessages.filter((message) => message.channel_id === channelId);
+}
+
+export const localE2ESeed = {
+ user: required(
+ usersByEmail.get(manifest.user.email),
+ `user ${manifest.user.email}`
+ ),
+ users,
+ usersById,
+ usersByEmail,
+ usersByMacroUserId,
+ documents,
+ documentsById,
+ documentsByName,
+ channels,
+ channelsById,
+ channelsByName,
+ channelMessages,
+ channelMessagesById,
+ channelMessagesByChannelId,
+ smoke: {
+ user: required(
+ usersByEmail.get(manifest.user.email),
+ `user ${manifest.user.email}`
+ ),
+ projectRoadmap: required(
+ documentsById.get(manifest.documents.projectRoadmap.id),
+ `document ${manifest.documents.projectRoadmap.id}`
+ ),
+ generalChannel: required(
+ channelsById.get(manifest.channels.general.id),
+ `channel ${manifest.channels.general.id}`
+ ),
+ generalWelcomeMessage: required(
+ channelMessages.find(
+ (message) =>
+ message.channel_id === manifest.channels.general.id &&
+ message.content === manifest.channels.general.message
+ ),
+ `message ${manifest.channels.general.message}`
+ ),
+ },
+} as const;
diff --git a/js/app/tests/e2e/helpers/local-app.ts b/js/app/tests/e2e/helpers/local-app.ts
new file mode 100644
index 0000000000..a552ed06a7
--- /dev/null
+++ b/js/app/tests/e2e/helpers/local-app.ts
@@ -0,0 +1,51 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+import {
+ entityIdSelector,
+ soupListContainerSelector,
+ splitContainerSelector,
+} from '../../../packages/core/dom-selectors';
+
+export const LOCAL_E2E = process.env.LOCAL_E2E === 'true';
+
+export async function gotoApp(page: Page, path: `/${string}`) {
+ await page.goto(`/app${path}`);
+ await expect(page).not.toHaveURL(/\/app\/(welcome|signup|login)/);
+ await expect(page.locator(splitContainerSelector).first()).toBeVisible({
+ timeout: 30_000,
+ });
+}
+
+export async function expectEntityInCurrentList(
+ page: Page,
+ entityId: string,
+ label: string
+) {
+ const row = page.locator(entityIdSelector(entityId)).first();
+
+ const scroller = page.locator(soupListContainerSelector).first();
+
+ await expect(scroller).toBeVisible({ timeout: 30_000 });
+
+ for (let attempt = 0; attempt < 30; attempt += 1) {
+ if ((await row.count()) > 0 && (await row.isVisible())) {
+ await expect(row).toContainText(label);
+ return;
+ }
+
+ await scroller.evaluate((element) => {
+ element.scrollBy(0, element.clientHeight * 0.9);
+ });
+ await page.waitForTimeout(150);
+ }
+
+ throw new Error(`Could not find seeded entity ${label} (${entityId})`);
+}
+
+export async function fillEditable(locator: Locator, text: string) {
+ await expect(locator).toBeVisible({ timeout: 30_000 });
+ await locator.fill(text);
+}
+
+export function uniqueE2EText(prefix: string): string {
+ return `${prefix} ${Date.now()} ${Math.random().toString(36).slice(2)}`;
+}
diff --git a/js/app/tests/e2e/local-channel-actions.spec.ts b/js/app/tests/e2e/local-channel-actions.spec.ts
new file mode 100644
index 0000000000..beb66607c5
--- /dev/null
+++ b/js/app/tests/e2e/local-channel-actions.spec.ts
@@ -0,0 +1,113 @@
+import { expect, type Locator, type Page, test } from '@playwright/test';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import {
+ fillEditable,
+ gotoApp,
+ LOCAL_E2E,
+ uniqueE2EText,
+} from './helpers/local-app';
+
+test.skip(
+ !LOCAL_E2E,
+ 'local channel action tests require LOCAL_E2E=true and seeded local data'
+);
+
+test.describe('local channel actions', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('sends a message and reacts in a seeded channel', async ({ page }) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const channelId = channel.channel_id;
+ const messageText = uniqueE2EText('local e2e channel message');
+
+ await openSeededChannel(page, channelId);
+
+ const message = await sendChannelMessage(page, channelId, messageText);
+
+ await reactToMessage(message, '👍');
+ await expect(
+ message.locator('[data-message-reaction-chip][data-emoji="👍"]')
+ ).toBeVisible({ timeout: 10_000 });
+ });
+
+ test('opens a reply composer for a seeded channel message', async ({
+ page,
+ }) => {
+ const channel = localE2ESeed.smoke.generalChannel;
+ const message = localE2ESeed.smoke.generalWelcomeMessage;
+
+ await openSeededChannel(
+ page,
+ channel.channel_id,
+ `?channel_message_id=${message.message_id}`
+ );
+
+ const messageRow = page.locator(
+ `[data-message-id="${message.message_id}"]`
+ );
+ await expect(messageRow).toBeVisible({ timeout: 30_000 });
+
+ await openReplyInput(messageRow);
+ await expect(
+ page.locator(`[data-inline-input-container-id="${message.message_id}"]`)
+ ).toContainText('Send a reply', { timeout: 10_000 });
+ });
+});
+
+async function openSeededChannel(
+ page: Page,
+ channelId: string,
+ searchParams: string = ''
+) {
+ const channelName =
+ localE2ESeed.smoke.generalChannel.channel_name ?? 'general';
+
+ await gotoApp(page, `/channel/${channelId}${searchParams}`);
+ await expect(
+ page.getByText(channelName, { exact: true }).first()
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(page.locator('[data-channel-message-list]')).toBeVisible({
+ timeout: 30_000,
+ });
+}
+
+async function sendChannelMessage(
+ page: Page,
+ channelId: string,
+ text: string
+): Promise<Locator> {
+ const input = page.locator(`[data-input-id="channel-input-${channelId}"]`);
+ await fillEditable(input.locator('[contenteditable="true"]').first(), text);
+ await clickSend(input);
+
+ const message = messageByText(page, text);
+ await expect(message).toBeVisible({ timeout: 30_000 });
+ return message;
+}
+
+async function clickSend(input: Locator) {
+ const sendButton = input.locator('[data-input-action="send"]');
+ await expect(sendButton).toBeEnabled({ timeout: 10_000 });
+ await sendButton.click();
+}
+
+async function reactToMessage(message: Locator, emoji: string) {
+ await message.hover();
+ const reaction = message.locator(
+ `[data-message-action="react-quick"][data-emoji="${emoji}"]`
+ );
+ await expect(reaction).toBeVisible({ timeout: 10_000 });
+ await reaction.click();
+}
+
+async function openReplyInput(message: Locator) {
+ await message.hover();
+ const reply = message.locator('[data-message-action="reply"]');
+ await expect(reply).toBeVisible({ timeout: 10_000 });
+ await reply.click();
+}
+
+function messageByText(page: Page, text: string) {
+ return page.locator('[data-message]').filter({ hasText: text }).last();
+}
diff --git a/js/app/tests/e2e/local-sidebar.spec.ts b/js/app/tests/e2e/local-sidebar.spec.ts
new file mode 100644
index 0000000000..a7bda737f7
--- /dev/null
+++ b/js/app/tests/e2e/local-sidebar.spec.ts
@@ -0,0 +1,120 @@
+import { expect, type Locator, type Page, test } from '@playwright/test';
+import { soupListContainerSelector } from '../../packages/core/dom-selectors';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import {
+ expectEntityInCurrentList,
+ gotoApp,
+ LOCAL_E2E,
+} from './helpers/local-app';
+
+const SIDEBAR_LIST_VIEWS = [
+ { id: 'inbox', label: 'Inbox', tabs: ['Signal', 'Noise', 'All'] },
+ { id: 'search', label: 'Search', tabs: [] },
+ {
+ id: 'agents',
+ label: 'Agents',
+ tabs: ['Owned', 'Running', 'Shared', 'Automations'],
+ },
+ {
+ id: 'mail',
+ label: 'Email',
+ tabs: ['Signal', 'Noise', 'Calendar', 'Sent', 'Drafts', 'Shared', 'All'],
+ },
+ {
+ id: 'documents',
+ label: 'Documents',
+ tabs: ['Owned', 'Shared', 'Attachments', 'All'],
+ },
+ { id: 'tasks', label: 'Tasks', tabs: ['Assigned', 'Created', 'All'] },
+ { id: 'channels', label: 'Channels', tabs: ['Recent', 'People', 'Teams'] },
+ { id: 'calls', label: 'Calls', tabs: ['All', 'Unattended'] },
+ { id: 'folders', label: 'Folders', tabs: ['Owned', 'All'] },
+] as const;
+
+test.skip(
+ !LOCAL_E2E,
+ 'local sidebar tests require LOCAL_E2E=true and seeded local data'
+);
+
+test.describe('local sidebar views', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ for (const view of SIDEBAR_LIST_VIEWS) {
+ test(`opens ${view.label} from the sidebar`, async ({ page }) => {
+ await gotoApp(
+ page,
+ view.id === 'documents' ? '/component/inbox' : '/component/documents'
+ );
+
+ await openSidebarView(page, view.id);
+
+ await expect(page).toHaveURL(new RegExp(`/app/component/${view.id}$`));
+ await expectActiveSidebarLink(page, view.id);
+ await expectLoadedListView(page, view.id);
+ await expectListViewChrome(page, view.tabs);
+
+ if (view.id === 'search') {
+ await expect(page.locator('[data-soup-search]').first()).toBeVisible({
+ timeout: 30_000,
+ });
+ }
+
+ if (view.id === 'documents') {
+ await expectEntityInCurrentList(
+ page,
+ localE2ESeed.smoke.projectRoadmap.document_id,
+ localE2ESeed.smoke.projectRoadmap.document_name
+ );
+ }
+
+ if (view.id === 'channels') {
+ await expectEntityInCurrentList(
+ page,
+ localE2ESeed.smoke.generalChannel.channel_id,
+ localE2ESeed.smoke.generalChannel.channel_name ?? 'general'
+ );
+ }
+ });
+ }
+});
+
+async function openSidebarView(page: Page, id: string) {
+ const link = sidebarLink(page, id);
+ await expect(link).toBeVisible({ timeout: 30_000 });
+ await link.click();
+}
+
+async function expectActiveSidebarLink(page: Page, id: string) {
+ await expect(sidebarLink(page, id)).toHaveAttribute('data-active', '', {
+ timeout: 10_000,
+ });
+}
+
+async function expectLoadedListView(page: Page, id: string) {
+ const view = page.locator(`[data-list-view="${id}"]`).first();
+ await expect(view).toBeVisible({ timeout: 30_000 });
+ await expect(
+ view
+ .locator(`${soupListContainerSelector}, [data-soup-empty-state]`)
+ .first()
+ ).toBeVisible({ timeout: 30_000 });
+ await expect(page.getByText('Something went terribly wrong')).toHaveCount(0);
+}
+
+async function expectListViewChrome(page: Page, tabs: readonly string[]) {
+ const header = page.locator('[data-split-header]').first();
+ await expect(header).toBeVisible({ timeout: 30_000 });
+
+ if (tabs.length === 0) return;
+
+ for (const tab of tabs) {
+ await expect(header.getByText(tab, { exact: true })).toBeVisible({
+ timeout: 30_000,
+ });
+ }
+}
+
+function sidebarLink(page: Page, id: string): Locator {
+ return page.locator(`nav [data-sidebar-link="${id}"]`).first();
+}
diff --git a/js/app/tests/e2e/local-smoke.spec.ts b/js/app/tests/e2e/local-smoke.spec.ts
new file mode 100644
index 0000000000..7d44905a25
--- /dev/null
+++ b/js/app/tests/e2e/local-smoke.spec.ts
@@ -0,0 +1,69 @@
+import { expect, test } from '@playwright/test';
+
+import { localE2ESeed } from './fixtures/local-e2e-seed';
+import {
+ expectEntityInCurrentList,
+ gotoApp,
+ LOCAL_E2E,
+} from './helpers/local-app';
+
+const SEEDED = {
+ document: {
+ id: localE2ESeed.smoke.projectRoadmap.document_id,
+ name: localE2ESeed.smoke.projectRoadmap.document_name,
+ },
+ channel: {
+ id: localE2ESeed.smoke.generalChannel.channel_id,
+ name: localE2ESeed.smoke.generalChannel.channel_name ?? 'general',
+ messageId: localE2ESeed.smoke.generalWelcomeMessage.message_id,
+ message: localE2ESeed.smoke.generalWelcomeMessage.content,
+ },
+} as const;
+
+test.skip(
+ !LOCAL_E2E,
+ 'local smoke tests require LOCAL_E2E=true and seeded local data'
+);
+
+test.describe('local app smoke', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('documents view shows seeded documents', async ({ page }) => {
+ await gotoApp(page, '/component/documents');
+ await expect(page.locator('[data-list-view="documents"]')).toBeVisible({
+ timeout: 30_000,
+ });
+
+ await expectEntityInCurrentList(
+ page,
+ SEEDED.document.id,
+ SEEDED.document.name
+ );
+ });
+
+ test('channels view and channel page show seeded channel data', async ({
+ page,
+ }) => {
+ await gotoApp(page, '/component/channels');
+ await expect(page.locator('[data-list-view="channels"]')).toBeVisible({
+ timeout: 30_000,
+ });
+
+ await expectEntityInCurrentList(
+ page,
+ SEEDED.channel.id,
+ SEEDED.channel.name
+ );
+
+ await gotoApp(
+ page,
+ `/channel/${SEEDED.channel.id}?channel_message_id=${SEEDED.channel.messageId}`
+ );
+ await expect(
+ page.getByText(SEEDED.channel.name, { exact: true })
+ ).toBeVisible();
+ await expect(page.getByText(SEEDED.channel.message)).toBeVisible({
+ timeout: 30_000,
+ });
+ });
+});
diff --git a/justfile b/justfile
index df94262d8e..4b61fc4faf 100644
--- a/justfile
+++ b/justfile
@@ -111,6 +111,46 @@ run_local *ARGS:
docker compose up
fi
+# Reset and seed deterministic data used by local E2E tests.
+local-e2e-seed:
+ just run_dbs -d
+ -just rust/cloud-storage/macro_db_client/drop_db -y -f
+ just rust/cloud-storage/initialize_dbs
+ just rust/cloud-storage/seed_cli/local-e2e-smoke
+
+# Start only the services needed by the local E2E suites. Avoid unrelated
+# local services with extra env/dependency requirements blocking E2E.
+local-e2e-services := "authentication-service connection_gateway contacts_service document_storage_service email_service static_file_service static_file_cdn sync_service websocket_service"
+
+# Start the local stack, seed deterministic data, and run the Playwright smoke suite.
+local-e2e *ARGS:
+ AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ just local-e2e-seed
+ cd js/app && LOCAL_E2E=true bunx playwright test {{ ARGS }}
+
+# Start the local stack, seed deterministic data, and run ignored Rust local E2E integration tests.
+local-e2e-rust *ARGS:
+ AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ just local-e2e-seed
+ cd rust/cloud-storage && SQLX_OFFLINE=true cargo test -p local_e2e_integration_tests -- --ignored --nocapture {{ ARGS }}
+
+# Start the local stack once, seed deterministic data, and run Rust + Playwright local E2E tests.
+local-e2e-all *ARGS:
+ AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ just local-e2e-seed
+ cd rust/cloud-storage && SQLX_OFFLINE=true cargo test -p local_e2e_integration_tests -- --ignored --nocapture
+ cd js/app && LOCAL_E2E=true bunx playwright test {{ ARGS }}
+
+# Start the local stack, seed deterministic data, and open Playwright UI mode.
+local-e2e-ui *ARGS:
+ AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test AWS_DEFAULT_REGION=us-east-1 just setup_localstack
+ COMPOSE_FILE=docker-compose.yml:docker-compose.local-e2e.yml just run_local -d --wait {{ local-e2e-services }}
+ just local-e2e-seed
+ cd js/app && LOCAL_E2E=true bunx playwright test --ui {{ ARGS }}
+
# Patches .env with local FusionAuth values if the Pulumi stack exists.
# Requires FusionAuth to be running — starts it temporarily if needed.
patch_local_fusionauth_env:
diff --git a/local_stack.just b/local_stack.just
index c92a234b3e..cb8e3f7874 100644
--- a/local_stack.just
+++ b/local_stack.just
@@ -26,6 +26,8 @@ create_local_queues:
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-scheduled-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-inbox-sync-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-inbox-retry-queue || true
+ aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-ops-queue || true
+ aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-gmail-ops-retry-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-service-refresh-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name search-event-queue || true
aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name email-sfs-delete-queue || true
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 94593abb91..7025b676db 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -6155,6 +6155,32 @@ dependencies = [
"tungstenite 0.28.0",
]
+[[package]]
+name = "local_e2e_integration_tests"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "futures",
+ "local_e2e_test_support",
+ "reqwest 0.13.3",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-tungstenite 0.28.0",
+]
+
+[[package]]
+name = "local_e2e_test_support"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "dotenvy",
+ "macro_auth",
+ "serde",
+ "serde_json",
+ "url",
+]
+
[[package]]
name = "lock_api"
version = "0.4.14"
@@ -10129,6 +10155,7 @@ dependencies = [
"tempfile",
"tokio",
"tracing",
+ "url",
"uuid",
]
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 869dae2964..108a5ab697 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -62,6 +62,7 @@ members = [
"invite_email",
"lambda_client",
"lexical_client",
+ "local_e2e_test_support",
"macro_auth",
"macro_aws_config",
"macro_cache_client",
@@ -240,6 +241,7 @@ thiserror = "2.0.0"
time = "0.3.37"
tokio = { version = "1.43.0", features = ["macros", "rt-multi-thread"] }
tokio-stream = { version = "0.1.17" }
+tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }
tokio-util = "0.7.13"
tungstenite = { version = "0.28", features = ["url"] }
tower = { version = "0.5.1", features = ["util"] }
diff --git a/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml b/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
index 58af0cd356..238aaa2e54 100644
--- a/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
+++ b/rust/cloud-storage/document_cognition_service/load-test/Cargo.toml
@@ -12,5 +12,5 @@ reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
-tokio-tungstenite = { version = "0.28.0", default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }
+tokio-tungstenite = { workspace = true, default-features = false, features = ["connect", "rustls-tls-webpki-roots"] }
tungstenite = { workspace = true }
diff --git a/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml b/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml
new file mode 100644
index 0000000000..12574e926d
--- /dev/null
+++ b/rust/cloud-storage/integration_tests/local_e2e/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+edition = "2024"
+name = "local_e2e_integration_tests"
+publish = false
+version = "0.1.0"
+
+[dev-dependencies]
+anyhow = { workspace = true }
+futures = { workspace = true }
+local_e2e_test_support = { path = "../../local_e2e_test_support" }
+reqwest = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true, features = ["time"] }
+tokio-tungstenite = { workspace = true }
diff --git a/rust/cloud-storage/integration_tests/local_e2e/README.md b/rust/cloud-storage/integration_tests/local_e2e/README.md
new file mode 100644
index 0000000000..1d13118e82
--- /dev/null
+++ b/rust/cloud-storage/integration_tests/local_e2e/README.md
@@ -0,0 +1,11 @@
+# Local E2E integration tests
+
+These tests run against the deterministic local E2E stack and seed data.
+
+```bash
+just local-e2e-rust
+```
+
+The tests are `#[ignore]` so normal workspace test runs do not require Docker
+services. They load fixtures through `local_e2e_test_support`, which reads the
+same seed files used by `seed_cli` and Playwright.
diff --git a/rust/cloud-storage/integration_tests/local_e2e/src/lib.rs b/rust/cloud-storage/integration_tests/local_e2e/src/lib.rs
new file mode 100644
index 0000000000..d37ef3a705
--- /dev/null
+++ b/rust/cloud-storage/integration_tests/local_e2e/src/lib.rs
@@ -0,0 +1 @@
+//! Integration tests for the local E2E stack.
diff --git a/rust/cloud-storage/integration_tests/local_e2e/tests/channel_websocket.rs b/rust/cloud-storage/integration_tests/local_e2e/tests/channel_websocket.rs
new file mode 100644
index 0000000000..666fa639a1
--- /dev/null
+++ b/rust/cloud-storage/integration_tests/local_e2e/tests/channel_websocket.rs
@@ -0,0 +1,232 @@
+use std::time::Duration;
+
+use anyhow::{Context, ensure};
+use futures::{SinkExt, StreamExt};
+use local_e2e_test_support::{
+ LocalE2eConfig, LocalE2eSeed, LocalE2eServices, LocalJwtOptions, encode_local_jwt_with,
+};
+use serde::Deserialize;
+use serde_json::{Value, json};
+use tokio::time::{Instant, timeout};
+use tokio_tungstenite::connect_async;
+use tokio_tungstenite::tungstenite::{Error as WebsocketError, Message as WebsocketMessage};
+
+const WEBSOCKET_TIMEOUT: Duration = Duration::from_secs(10);
+
+#[tokio::test]
+#[ignore = "requires `just local-e2e-seed` plus connection_gateway and document_storage_service"]
+async fn channel_message_posts_to_http_and_delivers_to_websocket() -> anyhow::Result<()> {
+ let config = LocalE2eConfig::load()?;
+ let seed = LocalE2eSeed::from_config(&config)?;
+ let services = LocalE2eServices::from_config(&config)?;
+
+ let user = seed.smoke_user()?;
+ let channel = seed.general_channel()?;
+ let token = encode_local_jwt_with(&config, LocalJwtOptions::new(user))?;
+ let ws_url = services.connection_gateway_ws_url_with_token(&token)?;
+
+ let (websocket, _) = connect_async(&ws_url)
+ .await
+ .context("failed to connect to connection gateway websocket")?;
+ let (mut websocket_write, mut websocket_read) = websocket.split();
+
+ websocket_write
+ .send(WebsocketMessage::Text("ping".into()))
+ .await
+ .context("failed to send websocket ping")?;
+ wait_for_pong(&mut websocket_read).await?;
+
+ let nonce = format!("rust-local-e2e-{}", uuid_like_nonce());
+ let content = format!("Rust local E2E websocket delivery {nonce}");
+
+ let http = reqwest::Client::new();
+ let post_response = http
+ .post(services.post_channel_message_url(&channel.channel_id))
+ .bearer_auth(&token)
+ .json(&json!({
+ "content": content,
+ "mentions": [],
+ "thread_id": null,
+ "attachments": [],
+ "nonce": nonce,
+ }))
+ .send()
+ .await
+ .context("failed to POST channel message")?;
+ let post_response = require_success(post_response, "POST channel message").await?;
+ let posted: PostMessageResponse = post_response
+ .json()
+ .await
+ .context("failed to decode post message response")?;
+
+ ensure!(
+ posted.nonce.as_deref() == Some(nonce.as_str()),
+ "post response did not echo nonce; response={posted:?}"
+ );
+
+ let delivered = wait_for_comms_message(&mut websocket_read, &posted.id, &nonce).await?;
+ ensure!(
+ delivered.get("content").and_then(Value::as_str) == Some(content.as_str()),
+ "websocket message content mismatch: {delivered}"
+ );
+ ensure!(
+ delivered.get("channel_id").and_then(Value::as_str) == Some(channel.channel_id.as_str()),
+ "websocket message channel mismatch: {delivered}"
+ );
+ ensure!(
+ delivered.get("sender_id").and_then(Value::as_str) == Some(user.user_id.as_str()),
+ "websocket message sender mismatch: {delivered}"
+ );
+
+ let get_response = http
+ .get(format!(
+ "{}?limit=25",
+ services.get_channel_url(&channel.channel_id)
+ ))
+ .bearer_auth(&token)
+ .send()
+ .await
+ .context("failed to GET channel")?;
+ let get_response = require_success(get_response, "GET channel").await?;
+ let channel_response: Value = get_response
+ .json()
+ .await
+ .context("failed to decode get channel response")?;
+
+ let persisted = channel_response
+ .get("messages")
+ .and_then(Value::as_array)
+ .and_then(|messages| {
+ messages.iter().find(|message| {
+ message.get("id").and_then(Value::as_str) == Some(posted.id.as_str())
+ })
+ })
+ .with_context(|| {
+ format!(
+ "posted message {} was not returned by GET channel",
+ posted.id
+ )
+ })?;
+
+ ensure!(
+ persisted.get("content").and_then(Value::as_str) == Some(content.as_str()),
+ "persisted message content mismatch: {persisted}"
+ );
+
+ websocket_write
+ .send(WebsocketMessage::Close(None))
+ .await
+ .ok();
+
+ Ok(())
+}
+
+#[derive(Debug, Deserialize)]
+struct PostMessageResponse {
+ id: String,
+ nonce: Option<String>,
+}
+
+#[derive(Debug, Deserialize)]
+struct GatewayMessage {
+ #[serde(rename = "type")]
+ message_type: String,
+ data: String,
+}
+
+async fn require_success(
+ response: reqwest::Response,
+ context: &str,
+) -> anyhow::Result<reqwest::Response> {
+ if response.status().is_success() {
+ return Ok(response);
+ }
+
+ let status = response.status();
+ let body = response.text().await.unwrap_or_default();
+ anyhow::bail!("{context} failed with {status}: {body}")
+}
+
+async fn wait_for_pong<S>(websocket_read: &mut S) -> anyhow::Result<()>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ loop {
+ let message = next_websocket_message(websocket_read, WEBSOCKET_TIMEOUT).await?;
+ if let WebsocketMessage::Text(text) = message
+ && text == "pong"
+ {
+ return Ok(());
+ }
+ }
+}
+
+async fn wait_for_comms_message<S>(
+ websocket_read: &mut S,
+ expected_message_id: &str,
+ expected_nonce: &str,
+) -> anyhow::Result<Value>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ let deadline = Instant::now() + WEBSOCKET_TIMEOUT;
+
+ loop {
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ ensure!(
+ !remaining.is_zero(),
+ "timed out waiting for websocket comms_message {expected_message_id}"
+ );
+
+ let message = next_websocket_message(websocket_read, remaining).await?;
+ let WebsocketMessage::Text(text) = message else {
+ continue;
+ };
+
+ if text == "pong" {
+ continue;
+ }
+
+ let Some((message_type, data)) = parse_gateway_message(&text) else {
+ continue;
+ };
+
+ if message_type != "comms_message" {
+ continue;
+ }
+
+ if data.get("id").and_then(Value::as_str) == Some(expected_message_id)
+ && data.get("nonce").and_then(Value::as_str) == Some(expected_nonce)
+ {
+ return Ok(data);
+ }
+ }
+}
+
+async fn next_websocket_message<S>(
+ websocket_read: &mut S,
+ duration: Duration,
+) -> anyhow::Result<WebsocketMessage>
+where
+ S: StreamExt<Item = Result<WebsocketMessage, WebsocketError>> + Unpin,
+{
+ timeout(duration, websocket_read.next())
+ .await
+ .context("timed out waiting for websocket message")?
+ .context("websocket closed before expected message")?
+ .context("websocket returned an error")
+}
+
+fn parse_gateway_message(text: &str) -> Option<(String, Value)> {
+ let gateway: GatewayMessage = serde_json::from_str(text).ok()?;
+ let data = serde_json::from_str(&gateway.data).ok()?;
+ Some((gateway.message_type, data))
+}
+
+fn uuid_like_nonce() -> String {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .expect("system clock before unix epoch")
+ .as_nanos()
+ .to_string()
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/Cargo.toml b/rust/cloud-storage/local_e2e_test_support/Cargo.toml
new file mode 100644
index 0000000000..2c5c6ac38b
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+edition = "2024"
+name = "local_e2e_test_support"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+anyhow = { workspace = true }
+dotenvy = { workspace = true }
+macro_auth = { path = "../macro_auth" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+url = { workspace = true }
diff --git a/rust/cloud-storage/local_e2e_test_support/README.md b/rust/cloud-storage/local_e2e_test_support/README.md
new file mode 100644
index 0000000000..161ef2dbfe
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/README.md
@@ -0,0 +1,12 @@
+# local_e2e_test_support
+
+Shared Rust helpers for local E2E tests.
+
+- Loads fixture data from `rust/cloud-storage/seed_cli/seed`.
+- Generates local Macro API JWTs from `.env` / process env.
+- Provides standard local service URLs for the `run_local` stack.
+- Refuses non-local service URLs so tests do not mutate shared dev services.
+
+Use this crate from ignored integration tests that are run by `just local-e2e-rust`.
+Override service URLs only with local endpoints via `LOCAL_E2E_DOCUMENT_STORAGE_URL`
+or `LOCAL_E2E_CONNECTION_GATEWAY_WS_URL`.
diff --git a/rust/cloud-storage/local_e2e_test_support/src/bin/generate_local_e2e_token.rs b/rust/cloud-storage/local_e2e_test_support/src/bin/generate_local_e2e_token.rs
new file mode 100644
index 0000000000..4dba947e5f
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/bin/generate_local_e2e_token.rs
@@ -0,0 +1,76 @@
+//! Generate a local E2E Macro API JWT using the shared Rust token encoder.
+
+use anyhow::{Context, ensure};
+use local_e2e_test_support::{
+ LocalE2eConfig, LocalE2eSeed, LocalJwtClaims, encode_local_jwt_claims_with,
+};
+
+fn read_arg(name: &str) -> Option<String> {
+ let prefix = format!("--{name}=");
+ let mut args = std::env::args().skip(1).peekable();
+
+ while let Some(arg) = args.next() {
+ if let Some(value) = arg.strip_prefix(&prefix) {
+ return Some(value.to_owned());
+ }
+
+ if arg == format!("--{name}") {
+ return args.next();
+ }
+ }
+
+ None
+}
+
+fn main() -> anyhow::Result<()> {
+ let config = LocalE2eConfig::load()?;
+ let seed = LocalE2eSeed::from_config(&config)?;
+ let email = read_arg("email").unwrap_or_else(|| seed.manifest.user.email.clone());
+ let seed_user = seed.user_by_email(&email);
+
+ let macro_user_id = read_arg("macro-user-id")
+ .or_else(|| seed_user.map(|user| user.user_id.clone()))
+ .unwrap_or_else(|| format!("macro|{email}"));
+ let fusion_user_id = read_arg("fusion-user-id")
+ .or_else(|| seed_user.map(|user| user.fusion_user_id.clone()))
+ .or_else(|| seed_user.map(|user| user.macro_user_id.clone()))
+ .unwrap_or_else(|| "00000000-0000-0000-0003-000000000001".to_owned());
+
+ let expiry_seconds = read_arg("expiry-seconds")
+ .or_else(|| {
+ config
+ .get("MACRO_API_TOKEN_EXPIRY_SECONDS")
+ .map(str::to_owned)
+ })
+ .map(|value| {
+ let parsed = value.parse::<usize>().with_context(|| {
+ format!("expiry-seconds must be a positive integer, got {value}")
+ })?;
+ ensure!(parsed > 0, "expiry-seconds must be positive, got {value}");
+ Ok(parsed)
+ })
+ .transpose()?;
+
+ let organization_id = read_arg("organization-id")
+ .map(|value| {
+ value
+ .parse::<i32>()
+ .with_context(|| format!("organization-id must be an integer, got {value}"))
+ })
+ .transpose()?;
+ let issuer = read_arg("issuer");
+
+ let token = encode_local_jwt_claims_with(
+ &config,
+ LocalJwtClaims {
+ fusion_user_id: &fusion_user_id,
+ macro_user_id: &macro_user_id,
+ organization_id,
+ issuer: issuer.as_deref(),
+ expiry_seconds,
+ },
+ )?;
+
+ println!("{token}");
+ Ok(())
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/src/config.rs b/rust/cloud-storage/local_e2e_test_support/src/config.rs
new file mode 100644
index 0000000000..c714076e49
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/config.rs
@@ -0,0 +1,77 @@
+use std::{
+ collections::HashMap,
+ path::{Path, PathBuf},
+};
+
+use anyhow::Context;
+
+const SEED_DIR_MARKER: &str = "rust/cloud-storage/seed_cli/seed";
+
+/// Local E2E runtime configuration loaded from the repository `.env` plus the
+/// process environment.
+#[derive(Clone, Debug)]
+pub struct LocalE2eConfig {
+ repo_root: PathBuf,
+ values: HashMap<String, String>,
+}
+
+impl LocalE2eConfig {
+ /// Load configuration from the repository root derived from this crate path.
+ ///
+ /// Values from the process environment override values from `.env`.
+ pub fn load() -> anyhow::Result<Self> {
+ let repo_root = find_repo_root()?;
+ Self::from_repo_root(repo_root)
+ }
+
+ /// Load configuration using an explicit repository root.
+ pub fn from_repo_root(repo_root: PathBuf) -> anyhow::Result<Self> {
+ let mut values = HashMap::new();
+ let dotenv_path = repo_root.join(".env");
+
+ if dotenv_path.exists() {
+ for item in dotenvy::from_path_iter(&dotenv_path)
+ .with_context(|| format!("failed to read {}", dotenv_path.display()))?
+ {
+ let (key, value) = item.with_context(|| {
+ format!("failed to parse dotenv entry in {}", dotenv_path.display())
+ })?;
+ values.insert(key, value);
+ }
+ }
+
+ values.extend(std::env::vars());
+
+ Ok(Self { repo_root, values })
+ }
+
+ /// Repository root containing `rust/cloud-storage/seed_cli/seed`.
+ pub fn repo_root(&self) -> &Path {
+ &self.repo_root
+ }
+
+ /// Path to the shared seed directory.
+ pub fn seed_dir(&self) -> PathBuf {
+ self.repo_root.join(SEED_DIR_MARKER)
+ }
+
+ /// Get a configuration value.
+ pub fn get(&self, key: &str) -> Option<&str> {
+ self.values.get(key).map(String::as_str)
+ }
+
+ /// Get a required configuration value.
+ pub fn required(&self, key: &str) -> anyhow::Result<&str> {
+ self.get(key)
+ .with_context(|| format!("{key} is required in environment or .env"))
+ }
+}
+
+fn find_repo_root() -> anyhow::Result<PathBuf> {
+ Path::new(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .and_then(Path::parent)
+ .and_then(Path::parent)
+ .map(Path::to_path_buf)
+ .context("CARGO_MANIFEST_DIR must be under rust/cloud-storage/<crate>")
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/src/fixtures.rs b/rust/cloud-storage/local_e2e_test_support/src/fixtures.rs
new file mode 100644
index 0000000000..3573d1fa95
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/fixtures.rs
@@ -0,0 +1,301 @@
+use std::{fs, path::Path};
+
+use anyhow::Context;
+use serde::Deserialize;
+
+use crate::LocalE2eConfig;
+
+/// Alias data for stable local E2E fixtures.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eManifest {
+ /// Primary authenticated user for local E2E.
+ pub user: LocalE2eUserAlias,
+ /// Stable document aliases.
+ pub documents: LocalE2eDocumentAliases,
+ /// Stable channel aliases.
+ pub channels: LocalE2eChannelAliases,
+}
+
+/// User alias in the local E2E manifest.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eUserAlias {
+ /// User email.
+ pub email: String,
+}
+
+/// Document aliases in the local E2E manifest.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eDocumentAliases {
+ /// Project roadmap document fixture.
+ #[serde(rename = "projectRoadmap")]
+ pub project_roadmap: LocalE2eDocumentAlias,
+}
+
+/// Document alias in the local E2E manifest.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eDocumentAlias {
+ /// Document id.
+ pub id: String,
+ /// Document name.
+ pub name: String,
+}
+
+/// Channel aliases in the local E2E manifest.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eChannelAliases {
+ /// General channel fixture.
+ pub general: LocalE2eChannelAlias,
+}
+
+/// Channel alias in the local E2E manifest.
+#[derive(Clone, Debug, Deserialize)]
+pub struct LocalE2eChannelAlias {
+ /// Channel id.
+ pub id: String,
+ /// Channel name.
+ pub name: String,
+ /// Canonical seeded message content for the channel.
+ pub message: String,
+}
+
+/// User row from `seed/local_e2e/users.json`.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SeedUser {
+ /// Stable database id in `macro_user`.
+ pub macro_user_id: String,
+ /// Stable FusionAuth id used in locally generated JWTs.
+ pub fusion_user_id: String,
+ /// Macro auth user id, e.g. `macro|[email protected]`.
+ pub user_id: String,
+ /// Display username.
+ pub username: String,
+ /// Email address.
+ pub email: String,
+ /// Stripe customer id fixture value.
+ pub stripe_customer_id: String,
+ /// First name.
+ pub first_name: String,
+ /// Last name.
+ pub last_name: String,
+ /// Role ids assigned to the user.
+ pub roles: Vec<String>,
+ /// Whether onboarding tutorial is complete.
+ pub tutorial_complete: bool,
+ /// Whether onboarding documents exist.
+ pub has_onboarding_documents: bool,
+ /// Whether the user has trialed.
+ pub has_trialed: bool,
+ /// Whether the user's email is verified.
+ pub is_verified: bool,
+}
+
+/// Document row from `seed/documents/documents.json`.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SeedDocument {
+ /// Stable document id.
+ pub document_id: String,
+ /// Display document name.
+ pub document_name: String,
+ /// Source file name.
+ pub file_name: String,
+ /// Whether the document is public.
+ pub is_public: bool,
+}
+
+/// Channel row from `seed/channels.json`.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SeedChannel {
+ /// Stable channel id.
+ pub channel_id: String,
+ /// Optional channel name.
+ pub channel_name: Option<String>,
+ /// Channel type string as accepted by the seed CLI.
+ pub channel_type: String,
+ /// Participant user ids excluding the owner appended by the seed CLI.
+ #[serde(default)]
+ pub participants: Vec<String>,
+}
+
+/// Entity mention row from a seeded channel message.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SeedMention {
+ /// Mentioned entity type.
+ pub entity_type: String,
+ /// Mentioned entity id.
+ pub entity_id: String,
+}
+
+/// Message row from `seed/channel_messages.json`.
+#[derive(Clone, Debug, Deserialize)]
+pub struct SeedChannelMessage {
+ /// Stable message id.
+ pub message_id: String,
+ /// Channel id containing this message.
+ pub channel_id: String,
+ /// Sender user id.
+ pub sender_id: String,
+ /// Message content.
+ pub content: String,
+ /// Optional thread root id.
+ pub thread_id: Option<String>,
+ /// Entity mentions in the message.
+ #[serde(default)]
+ pub entity_mentions: Vec<SeedMention>,
+}
+
+/// Fully loaded local E2E seed world.
+#[derive(Clone, Debug)]
+pub struct LocalE2eSeed {
+ /// Stable fixture aliases.
+ pub manifest: LocalE2eManifest,
+ /// Seeded users.
+ pub users: Vec<SeedUser>,
+ /// Seeded documents.
+ pub documents: Vec<SeedDocument>,
+ /// Seeded channels.
+ pub channels: Vec<SeedChannel>,
+ /// Seeded channel messages.
+ pub channel_messages: Vec<SeedChannelMessage>,
+}
+
+impl LocalE2eSeed {
+ /// Load seed data using the default local E2E configuration.
+ pub fn load() -> anyhow::Result<Self> {
+ let config = LocalE2eConfig::load()?;
+ Self::from_config(&config)
+ }
+
+ /// Load seed data from a configuration's repository root.
+ pub fn from_config(config: &LocalE2eConfig) -> anyhow::Result<Self> {
+ Self::from_seed_dir(&config.seed_dir())
+ }
+
+ /// Load seed data from an explicit seed directory.
+ pub fn from_seed_dir(seed_dir: &Path) -> anyhow::Result<Self> {
+ Ok(Self {
+ manifest: read_json(&seed_dir.join("local_e2e/manifest.json"))?,
+ users: read_json(&seed_dir.join("local_e2e/users.json"))?,
+ documents: read_json(&seed_dir.join("documents/documents.json"))?,
+ channels: read_json(&seed_dir.join("channels.json"))?,
+ channel_messages: read_json(&seed_dir.join("channel_messages.json"))?,
+ })
+ }
+
+ /// Find a seeded user by email.
+ pub fn user_by_email(&self, email: &str) -> Option<&SeedUser> {
+ self.users.iter().find(|user| user.email == email)
+ }
+
+ /// Find a seeded user by auth user id.
+ pub fn user_by_id(&self, user_id: &str) -> Option<&SeedUser> {
+ self.users.iter().find(|user| user.user_id == user_id)
+ }
+
+ /// Find a seeded document by id.
+ pub fn document_by_id(&self, document_id: &str) -> Option<&SeedDocument> {
+ self.documents
+ .iter()
+ .find(|document| document.document_id == document_id)
+ }
+
+ /// Find a seeded channel by id.
+ pub fn channel_by_id(&self, channel_id: &str) -> Option<&SeedChannel> {
+ self.channels
+ .iter()
+ .find(|channel| channel.channel_id == channel_id)
+ }
+
+ /// Find a seeded channel message by id.
+ pub fn channel_message_by_id(&self, message_id: &str) -> Option<&SeedChannelMessage> {
+ self.channel_messages
+ .iter()
+ .find(|message| message.message_id == message_id)
+ }
+
+ /// Messages in a channel, in seed-file order.
+ pub fn channel_messages_by_channel_id(&self, channel_id: &str) -> Vec<&SeedChannelMessage> {
+ self.channel_messages
+ .iter()
+ .filter(|message| message.channel_id == channel_id)
+ .collect()
+ }
+
+ /// Primary authenticated smoke-test user.
+ pub fn smoke_user(&self) -> anyhow::Result<&SeedUser> {
+ self.user_by_email(&self.manifest.user.email)
+ .with_context(|| format!("missing local E2E user {}", self.manifest.user.email))
+ }
+
+ /// Project roadmap smoke-test document.
+ pub fn project_roadmap_document(&self) -> anyhow::Result<&SeedDocument> {
+ self.document_by_id(&self.manifest.documents.project_roadmap.id)
+ .with_context(|| {
+ format!(
+ "missing local E2E document {}",
+ self.manifest.documents.project_roadmap.id
+ )
+ })
+ }
+
+ /// General channel smoke-test fixture.
+ pub fn general_channel(&self) -> anyhow::Result<&SeedChannel> {
+ self.channel_by_id(&self.manifest.channels.general.id)
+ .with_context(|| {
+ format!(
+ "missing local E2E channel {}",
+ self.manifest.channels.general.id
+ )
+ })
+ }
+
+ /// Canonical welcome message in the general channel.
+ pub fn general_welcome_message(&self) -> anyhow::Result<&SeedChannelMessage> {
+ self.channel_messages
+ .iter()
+ .find(|message| {
+ message.channel_id == self.manifest.channels.general.id
+ && message.content == self.manifest.channels.general.message
+ })
+ .with_context(|| {
+ format!(
+ "missing local E2E general-channel message {:?}",
+ self.manifest.channels.general.message
+ )
+ })
+ }
+}
+
+fn read_json<T>(path: &Path) -> anyhow::Result<T>
+where
+ T: for<'de> Deserialize<'de>,
+{
+ let content = fs::read_to_string(path)
+ .with_context(|| format!("failed to read seed file {}", path.display()))?;
+ serde_json::from_str(&content)
+ .with_context(|| format!("failed to parse seed file {}", path.display()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::LocalE2eSeed;
+
+ #[test]
+ fn loads_shared_seed_contract() {
+ let seed = LocalE2eSeed::load().unwrap();
+
+ let user = seed.smoke_user().unwrap();
+ assert_eq!(user.email, seed.manifest.user.email);
+
+ let document = seed.project_roadmap_document().unwrap();
+ assert_eq!(
+ document.document_id,
+ seed.manifest.documents.project_roadmap.id
+ );
+
+ let channel = seed.general_channel().unwrap();
+ assert_eq!(channel.channel_id, seed.manifest.channels.general.id);
+
+ let message = seed.general_welcome_message().unwrap();
+ assert_eq!(message.channel_id, channel.channel_id);
+ }
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/src/jwt.rs b/rust/cloud-storage/local_e2e_test_support/src/jwt.rs
new file mode 100644
index 0000000000..fbeefe0aa7
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/jwt.rs
@@ -0,0 +1,108 @@
+use anyhow::Context;
+use macro_auth::macro_api_token::{EncodeMacroApiTokenArgs, encode_macro_api_token};
+
+use crate::{LocalE2eConfig, SeedUser};
+
+/// Default local E2E JWT lifetime: eight hours.
+pub const DEFAULT_EXPIRY_SECONDS: usize = 8 * 60 * 60;
+
+/// Options for generating a local Macro API token.
+#[derive(Clone, Debug)]
+pub struct LocalJwtOptions<'a> {
+ /// Seed user to encode into the token.
+ pub user: &'a SeedUser,
+ /// Optional organization id claim.
+ pub organization_id: Option<i32>,
+ /// Optional token lifetime in seconds. Falls back to env, then [`DEFAULT_EXPIRY_SECONDS`].
+ pub expiry_seconds: Option<usize>,
+}
+
+impl<'a> LocalJwtOptions<'a> {
+ /// Create default token options for a seed user.
+ pub fn new(user: &'a SeedUser) -> Self {
+ Self {
+ user,
+ organization_id: None,
+ expiry_seconds: None,
+ }
+ }
+
+ /// Override the token lifetime.
+ pub fn with_expiry_seconds(mut self, expiry_seconds: usize) -> Self {
+ self.expiry_seconds = Some(expiry_seconds);
+ self
+ }
+}
+
+/// Explicit claims for generating a local Macro API token.
+#[derive(Clone, Copy, Debug)]
+pub struct LocalJwtClaims<'a> {
+ /// FusionAuth user id claim.
+ pub fusion_user_id: &'a str,
+ /// Macro auth user id claim.
+ pub macro_user_id: &'a str,
+ /// Optional organization id claim.
+ pub organization_id: Option<i32>,
+ /// Optional issuer claim. Falls back to env, then `local`.
+ pub issuer: Option<&'a str>,
+ /// Optional token lifetime in seconds. Falls back to env, then [`DEFAULT_EXPIRY_SECONDS`].
+ pub expiry_seconds: Option<usize>,
+}
+
+/// Generate a local Macro API token for a seed user.
+pub fn encode_local_jwt(user: &SeedUser) -> anyhow::Result<String> {
+ let config = LocalE2eConfig::load()?;
+ encode_local_jwt_with(&config, LocalJwtOptions::new(user))
+}
+
+/// Generate a local Macro API token using explicit config and options.
+pub fn encode_local_jwt_with(
+ config: &LocalE2eConfig,
+ options: LocalJwtOptions<'_>,
+) -> anyhow::Result<String> {
+ encode_local_jwt_claims_with(
+ config,
+ LocalJwtClaims {
+ fusion_user_id: &options.user.fusion_user_id,
+ macro_user_id: &options.user.user_id,
+ organization_id: options.organization_id,
+ expiry_seconds: options.expiry_seconds,
+ issuer: None,
+ },
+ )
+}
+
+/// Generate a local Macro API token using explicit claims.
+pub fn encode_local_jwt_claims_with(
+ config: &LocalE2eConfig,
+ claims: LocalJwtClaims<'_>,
+) -> anyhow::Result<String> {
+ let issuer = claims
+ .issuer
+ .or_else(|| config.get("MACRO_API_TOKEN_ISSUER"))
+ .unwrap_or("local")
+ .to_owned();
+ let private_key = normalize_pem(config.required("MACRO_API_TOKEN_PRIVATE_SECRET_KEY")?);
+ let expiry_seconds = match claims.expiry_seconds {
+ Some(expiry_seconds) => expiry_seconds,
+ None => config
+ .get("MACRO_API_TOKEN_EXPIRY_SECONDS")
+ .map(str::parse::<usize>)
+ .transpose()
+ .context("MACRO_API_TOKEN_EXPIRY_SECONDS must be an integer")?
+ .unwrap_or(DEFAULT_EXPIRY_SECONDS),
+ };
+
+ encode_macro_api_token(EncodeMacroApiTokenArgs {
+ fusionauth_id: claims.fusion_user_id.to_owned(),
+ macro_user_id: claims.macro_user_id.to_owned(),
+ organization_id: claims.organization_id,
+ issuer,
+ private_key,
+ expiry_seconds,
+ })
+}
+
+fn normalize_pem(value: &str) -> String {
+ value.replace("\\n", "\n")
+}
diff --git a/rust/cloud-storage/local_e2e_test_support/src/lib.rs b/rust/cloud-storage/local_e2e_test_support/src/lib.rs
new file mode 100644
index 0000000000..b9530f63f3
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/lib.rs
@@ -0,0 +1,20 @@
+//! Shared helpers for local E2E tests that run against the `run_local` stack.
+//!
+//! The crate intentionally reads the same seed files used by `seed_cli` and
+//! Playwright so Rust integration tests do not duplicate fixture constants.
+
+mod config;
+mod fixtures;
+mod jwt;
+mod services;
+
+pub use config::LocalE2eConfig;
+pub use fixtures::{
+ LocalE2eManifest, LocalE2eSeed, SeedChannel, SeedChannelMessage, SeedDocument, SeedMention,
+ SeedUser,
+};
+pub use jwt::{
+ DEFAULT_EXPIRY_SECONDS, LocalJwtClaims, LocalJwtOptions, encode_local_jwt,
+ encode_local_jwt_claims_with, encode_local_jwt_with,
+};
+pub use services::LocalE2eServices;
diff --git a/rust/cloud-storage/local_e2e_test_support/src/services.rs b/rust/cloud-storage/local_e2e_test_support/src/services.rs
new file mode 100644
index 0000000000..e91ac58d55
--- /dev/null
+++ b/rust/cloud-storage/local_e2e_test_support/src/services.rs
@@ -0,0 +1,123 @@
+use anyhow::{Context, ensure};
+use url::Url;
+
+use crate::LocalE2eConfig;
+
+const DEFAULT_DOCUMENT_STORAGE_URL: &str = "http://localhost:8086";
+const DEFAULT_CONNECTION_GATEWAY_WS_URL: &str = "ws://localhost:8082/";
+
+/// Host URLs for services used by local E2E tests.
+#[derive(Clone, Debug)]
+pub struct LocalE2eServices {
+ document_storage_url: String,
+ connection_gateway_ws_url: String,
+}
+
+impl LocalE2eServices {
+ /// Load service URLs from config, falling back to the standard local ports.
+ pub fn from_config(config: &LocalE2eConfig) -> anyhow::Result<Self> {
+ let document_storage_url = trim_trailing_slash(
+ config
+ .get("LOCAL_E2E_DOCUMENT_STORAGE_URL")
+ .unwrap_or(DEFAULT_DOCUMENT_STORAGE_URL),
+ );
+ let connection_gateway_ws_url = config
+ .get("LOCAL_E2E_CONNECTION_GATEWAY_WS_URL")
+ .unwrap_or(DEFAULT_CONNECTION_GATEWAY_WS_URL)
+ .to_owned();
+
+ validate_local_service_url(
+ &document_storage_url,
+ "document storage",
+ &["http", "https"],
+ )?;
+ validate_local_service_url(
+ &connection_gateway_ws_url,
+ "connection gateway websocket",
+ &["ws", "wss"],
+ )?;
+
+ Ok(Self {
+ document_storage_url,
+ connection_gateway_ws_url,
+ })
+ }
+
+ /// Load service URLs using default config discovery.
+ pub fn load() -> anyhow::Result<Self> {
+ let config = LocalE2eConfig::load()?;
+ Self::from_config(&config)
+ }
+
+ /// Base URL for document storage service HTTP endpoints.
+ pub fn document_storage_url(&self) -> &str {
+ &self.document_storage_url
+ }
+
+ /// URL for posting a channel message through document storage's comms API.
+ pub fn post_channel_message_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/comms/channels/{}/message",
+ self.document_storage_url, channel_id
+ )
+ }
+
+ /// URL for fetching channel data through document storage's comms API.
+ pub fn get_channel_url(&self, channel_id: &str) -> String {
+ format!(
+ "{}/comms/channels/{}",
+ self.document_storage_url, channel_id
+ )
+ }
+
+ /// Connection gateway websocket URL with a `macro-api-token` query param.
+ pub fn connection_gateway_ws_url_with_token(&self, token: &str) -> anyhow::Result<String> {
+ let mut url = Url::parse(&self.connection_gateway_ws_url)
+ .with_context(|| format!("invalid websocket URL {}", self.connection_gateway_ws_url))?;
+ url.query_pairs_mut().append_pair("macro-api-token", token);
+ Ok(url.to_string())
+ }
+}
+
+fn trim_trailing_slash(value: &str) -> String {
+ value.trim_end_matches('/').to_owned()
+}
+
+fn validate_local_service_url(
+ raw_url: &str,
+ service_name: &str,
+ allowed_schemes: &[&str],
+) -> anyhow::Result<()> {
+ let url =
+ Url::parse(raw_url).with_context(|| format!("invalid {service_name} URL {raw_url}"))?;
+ let host = url.host_str().unwrap_or_default();
+
+ ensure!(
+ allowed_schemes.contains(&url.scheme()),
+ "refusing to run local E2E tests against {service_name} URL {raw_url}; expected scheme in {allowed_schemes:?}"
+ );
+ ensure!(
+ matches!(host, "localhost" | "127.0.0.1" | "::1"),
+ "refusing to run local E2E tests against non-local {service_name} URL {raw_url}"
+ );
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::validate_local_service_url;
+
+ #[test]
+ fn local_service_urls_must_be_localhost() {
+ validate_local_service_url("http://localhost:8086", "document storage", &["http"]).unwrap();
+ validate_local_service_url("ws://127.0.0.1:8082/", "gateway", &["ws"]).unwrap();
+ validate_local_service_url(
+ "http://macro-db-dev.example.com",
+ "document storage",
+ &["http"],
+ )
+ .unwrap_err();
+ validate_local_service_url("http://localhost:8082", "gateway", &["ws"]).unwrap_err();
+ }
+}
diff --git a/rust/cloud-storage/seed_cli/Cargo.toml b/rust/cloud-storage/seed_cli/Cargo.toml
index fe0d4b991c..e638480aca 100644
--- a/rust/cloud-storage/seed_cli/Cargo.toml
+++ b/rust/cloud-storage/seed_cli/Cargo.toml
@@ -33,6 +33,7 @@ serde_json = { workspace = true }
sqlx = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
+url = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
diff --git a/rust/cloud-storage/seed_cli/justfile b/rust/cloud-storage/seed_cli/justfile
index e9d6ac20a1..8554dbc12a 100644
--- a/rust/cloud-storage/seed_cli/justfile
+++ b/rust/cloud-storage/seed_cli/justfile
@@ -14,3 +14,21 @@ get_environment:
[positional-arguments]
seed *ARGS:
cargo r "$@"
+
+# Reset and seed deterministic data for the local Playwright smoke suite.
+local-e2e-smoke:
+ LOCAL_E2E_SEED="true" \
+ DATABASE_URL="postgres://user:password@localhost:5432/macrodb" \
+ LOCAL_AWS_URL="http://localhost:4566" \
+ DOCUMENT_STORAGE_BUCKET="doc-storage" \
+ AWS_ACCESS_KEY_ID="test" \
+ AWS_SECRET_ACCESS_KEY="test" \
+ SQLX_OFFLINE="true" \
+ ENVIRONMENT="local" \
+ FUSIONAUTH_BASE_URL="http://localhost:9011" \
+ FUSIONAUTH_API_KEY_SECRET_KEY="local" \
+ FUSIONAUTH_TENANT_ID="local" \
+ FUSIONAUTH_CLIENT_ID="local" \
+ FUSIONAUTH_CLIENT_SECRET_KEY="local" \
+ FUSIONAUTH_OAUTH_REDIRECT_URI="http://localhost:8080/oauth/redirect" \
+ cargo r -- scenario local-e2e-smoke
diff --git a/rust/cloud-storage/seed_cli/seed/local_e2e/manifest.json b/rust/cloud-storage/seed_cli/seed/local_e2e/manifest.json
new file mode 100644
index 0000000000..01ce6c6f1d
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/local_e2e/manifest.json
@@ -0,0 +1,18 @@
+{
+ "user": {
+ "email": "[email protected]"
+ },
+ "documents": {
+ "projectRoadmap": {
+ "id": "00000000-0000-0000-0002-000000000001",
+ "name": "Project Roadmap"
+ }
+ },
+ "channels": {
+ "general": {
+ "id": "00000000-0000-0000-0000-000000000001",
+ "name": "general",
+ "message": "Welcome to the general channel everyone!"
+ }
+ }
+}
diff --git a/rust/cloud-storage/seed_cli/seed/local_e2e/reset.sql b/rust/cloud-storage/seed_cli/seed/local_e2e/reset.sql
new file mode 100644
index 0000000000..90bb4309b3
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/local_e2e/reset.sql
@@ -0,0 +1,19 @@
+DELETE FROM entity_access
+WHERE source_id LIKE '00000000-0000-0000-0000-00000000000%'
+ OR entity_id::text LIKE '00000000-0000-0000-0002-%';
+
+DELETE FROM "ChannelSharePermission"
+WHERE channel_id LIKE '00000000-0000-0000-0000-00000000000%';
+
+DELETE FROM comms_entity_mentions
+WHERE source_entity_id LIKE '00000000-0000-0000-0001-%'
+ OR entity_id LIKE '00000000-0000-0000-0002-%';
+
+DELETE FROM comms_activity
+WHERE channel_id::text LIKE '00000000-0000-0000-0000-00000000000%';
+
+DELETE FROM comms_channels
+WHERE id::text LIKE '00000000-0000-0000-0000-00000000000%';
+
+DELETE FROM "Document"
+WHERE id LIKE '00000000-0000-0000-0002-%';
diff --git a/rust/cloud-storage/seed_cli/seed/local_e2e/users.json b/rust/cloud-storage/seed_cli/seed/local_e2e/users.json
new file mode 100644
index 0000000000..80deeb73aa
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/local_e2e/users.json
@@ -0,0 +1,77 @@
+[
+ {
+ "macro_user_id": "00000000-0000-0000-0003-000000000001",
+ "fusion_user_id": "00000000-0000-0000-0003-000000000001",
+ "user_id": "macro|[email protected]",
+ "username": "e2e",
+ "email": "[email protected]",
+ "stripe_customer_id": "stripe-local-e2e",
+ "first_name": "E2E",
+ "last_name": "User",
+ "roles": ["self_serve"],
+ "tutorial_complete": true,
+ "has_onboarding_documents": true,
+ "has_trialed": false,
+ "is_verified": true
+ },
+ {
+ "macro_user_id": "00000000-0000-0000-0003-000000000002",
+ "fusion_user_id": "00000000-0000-0000-0003-000000000002",
+ "user_id": "macro|[email protected]",
+ "username": "bob",
+ "email": "[email protected]",
+ "stripe_customer_id": "stripe-local-bob",
+ "first_name": "Bob",
+ "last_name": "Example",
+ "roles": ["self_serve"],
+ "tutorial_complete": true,
+ "has_onboarding_documents": true,
+ "has_trialed": false,
+ "is_verified": true
+ },
+ {
+ "macro_user_id": "00000000-0000-0000-0003-000000000003",
+ "fusion_user_id": "00000000-0000-0000-0003-000000000003",
+ "user_id": "macro|[email protected]",
+ "username": "charlie",
+ "email": "[email protected]",
+ "stripe_customer_id": "stripe-local-charlie",
+ "first_name": "Charlie",
+ "last_name": "Example",
+ "roles": ["self_serve"],
+ "tutorial_complete": true,
+ "has_onboarding_documents": true,
+ "has_trialed": false,
+ "is_verified": true
+ },
+ {
+ "macro_user_id": "00000000-0000-0000-0003-000000000004",
+ "fusion_user_id": "00000000-0000-0000-0003-000000000004",
+ "user_id": "macro|[email protected]",
+ "username": "dana",
+ "email": "[email protected]",
+ "stripe_customer_id": "stripe-local-dana",
+ "first_name": "Dana",
+ "last_name": "Example",
+ "roles": ["self_serve"],
+ "tutorial_complete": true,
+ "has_onboarding_documents": true,
+ "has_trialed": false,
+ "is_verified": true
+ },
+ {
+ "macro_user_id": "00000000-0000-0000-0003-000000000005",
+ "fusion_user_id": "00000000-0000-0000-0003-000000000005",
+ "user_id": "macro|[email protected]",
+ "username": "eve",
+ "email": "[email protected]",
+ "stripe_customer_id": "stripe-local-eve",
+ "first_name": "Eve",
+ "last_name": "Example",
+ "roles": ["self_serve"],
+ "tutorial_complete": true,
+ "has_onboarding_documents": true,
+ "has_trialed": false,
+ "is_verified": true
+ }
+]
diff --git a/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs b/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs
index 0f1e53f1da..10426b2574 100644
--- a/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs
@@ -138,10 +138,19 @@ async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
.as_deref()
.map(std::path::PathBuf::from)
.unwrap_or(default_path);
- seed_from_file(args, ctx, &path).await
+ seed_from_file_ref(&args, &ctx, &path).await
}
+#[cfg(test)]
async fn seed_from_file(args: SeedArgs, ctx: SeedCliContext, path: &Path) -> anyhow::Result<()> {
+ seed_from_file_ref(&args, &ctx, path).await
+}
+
+pub(crate) async fn seed_from_file_ref(
+ args: &SeedArgs,
+ ctx: &SeedCliContext,
+ path: &Path,
+) -> anyhow::Result<()> {
tracing::info!("seeding channels");
let content = std::fs::read_to_string(path)
diff --git a/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs b/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs
index fc8b682119..ea861ed5aa 100644
--- a/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs
@@ -111,10 +111,15 @@ async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
.file_path
.map(std::path::PathBuf::from)
.unwrap_or(default_path);
- seed_from_file(ctx, &path).await
+ seed_from_file_ref(&ctx, &path).await
}
+#[cfg(test)]
async fn seed_from_file(ctx: SeedCliContext, path: &Path) -> anyhow::Result<()> {
+ seed_from_file_ref(&ctx, path).await
+}
+
+pub(crate) async fn seed_from_file_ref(ctx: &SeedCliContext, path: &Path) -> anyhow::Result<()> {
tracing::info!("seeding channel messages");
let content = std::fs::read_to_string(path)
diff --git a/rust/cloud-storage/seed_cli/src/entity/document/mod.rs b/rust/cloud-storage/seed_cli/src/entity/document/mod.rs
index 404a5fcb51..e17d295cce 100644
--- a/rust/cloud-storage/seed_cli/src/entity/document/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/document/mod.rs
@@ -167,10 +167,19 @@ async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
.as_deref()
.map(std::path::PathBuf::from)
.unwrap_or(default_path);
- seed_from_file(args, ctx, &path).await
+ seed_from_file_ref(&args, &ctx, &path).await
}
+#[cfg(test)]
async fn seed_from_file(args: SeedArgs, ctx: SeedCliContext, path: &Path) -> anyhow::Result<()> {
+ seed_from_file_ref(&args, &ctx, path).await
+}
+
+pub(crate) async fn seed_from_file_ref(
+ args: &SeedArgs,
+ ctx: &SeedCliContext,
+ path: &Path,
+) -> anyhow::Result<()> {
tracing::info!("seeding documents");
let content = std::fs::read_to_string(path)
@@ -185,13 +194,18 @@ async fn seed_from_file(args: SeedArgs, ctx: SeedCliContext, path: &Path) -> any
println!("Found {} documents to seed", rows.len());
- let owner = MacroUserIdStr::parse_from_str(args.user_id.leak()).context("valid owner id")?;
+ let owner_user_id = args.user_id.clone();
+ let owner = MacroUserIdStr::parse_from_str(owner_user_id.leak()).context("valid owner id")?;
let mut created = 0;
let mut failed = 0;
+ let files_dir = path
+ .parent()
+ .context("document seed json should have a parent directory")?
+ .join("files");
for row in rows {
- let file_path = format!("seed/documents/files/{}", row.file_name);
+ let file_path = files_dir.join(&row.file_name);
let file_type = row
.file_name
.split('.')
@@ -238,7 +252,7 @@ async fn seed_from_file(args: SeedArgs, ctx: SeedCliContext, path: &Path) -> any
file_type.as_str()
);
- match ctx.s3.upload_file(&key, &file_path).await {
+ match ctx.s3.upload_file(&key, &file_path.to_string_lossy()).await {
Ok(()) => {
println!("Seeded document '{}' with id {}", row.document_name, doc_id);
created += 1;
diff --git a/rust/cloud-storage/seed_cli/src/entity/mod.rs b/rust/cloud-storage/seed_cli/src/entity/mod.rs
index 73976d7d59..f8f0e3c79b 100644
--- a/rust/cloud-storage/seed_cli/src/entity/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/mod.rs
@@ -4,11 +4,12 @@ pub mod channel;
pub mod channel_message;
pub mod document;
pub mod email;
+pub mod scenario;
pub mod user;
use clap::Subcommand;
-use crate::config::SeedCliContext;
+use crate::config::{EnvVars, SeedCliContext};
/// Top-level entity subcommands for the seed CLI.
#[derive(Debug, Subcommand)]
@@ -23,9 +24,19 @@ pub enum EntityCommand {
Document(document::DocumentArgs),
/// Manage email seed data
Email(email::EmailArgs),
+ /// Apply predefined seed scenarios
+ Scenario(scenario::ScenarioArgs),
}
impl EntityCommand {
+ /// Validate environment-sensitive safety checks before connecting to services.
+ pub fn validate_environment(&self, env_vars: &EnvVars) -> anyhow::Result<()> {
+ match self {
+ EntityCommand::Scenario(args) => args.validate_environment(env_vars),
+ _ => Ok(()),
+ }
+ }
+
/// Execute the entity command.
pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {
match self {
@@ -34,6 +45,7 @@ impl EntityCommand {
EntityCommand::ChannelMessage(args) => args.execute(ctx).await,
EntityCommand::Document(args) => args.execute(ctx).await,
EntityCommand::Email(args) => args.execute(ctx).await,
+ EntityCommand::Scenario(args) => args.execute(ctx).await,
}
}
}
diff --git a/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs b/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs
new file mode 100644
index 0000000000..865d7433b4
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/src/entity/scenario/mod.rs
@@ -0,0 +1,349 @@
+//! Predefined seed scenarios for local development and e2e tests.
+
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, ensure};
+use clap::{Args, Subcommand};
+use serde::Deserialize;
+
+use crate::config::{EnvVars, SeedCliContext};
+use crate::entity::{channel, channel_message, document};
+
+const LOCAL_E2E_MANIFEST_JSON: &str = include_str!("../../../seed/local_e2e/manifest.json");
+const LOCAL_E2E_RESET_SQL: &str = include_str!("../../../seed/local_e2e/reset.sql");
+const LOCAL_E2E_USERS_JSON: &str = include_str!("../../../seed/local_e2e/users.json");
+
+#[derive(Debug, Deserialize)]
+struct LocalE2eManifest {
+ user: LocalE2eUserAlias,
+}
+
+#[derive(Debug, Deserialize)]
+struct LocalE2eUserAlias {
+ email: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct LocalE2eUser {
+ macro_user_id: String,
+ user_id: String,
+ username: String,
+ email: String,
+ stripe_customer_id: String,
+ first_name: String,
+ last_name: String,
+ roles: Vec<String>,
+ tutorial_complete: bool,
+ has_onboarding_documents: bool,
+ has_trialed: bool,
+ is_verified: bool,
+}
+
+struct LocalE2eSeedData {
+ manifest: LocalE2eManifest,
+ users: Vec<LocalE2eUser>,
+}
+
+fn local_e2e_seed_data() -> anyhow::Result<LocalE2eSeedData> {
+ let manifest =
+ serde_json::from_str(LOCAL_E2E_MANIFEST_JSON).context("valid local e2e manifest")?;
+ let users = serde_json::from_str(LOCAL_E2E_USERS_JSON).context("valid local e2e users")?;
+
+ Ok(LocalE2eSeedData { manifest, users })
+}
+
+fn seed_path(relative_path: &str) -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join(relative_path)
+}
+
+fn sql_string(value: &str) -> String {
+ format!("'{}'", value.replace('\'', "''"))
+}
+
+fn sql_bool(value: bool) -> &'static str {
+ if value { "true" } else { "false" }
+}
+
+fn values_sql(rows: impl IntoIterator<Item = Vec<String>>) -> String {
+ rows.into_iter()
+ .map(|row| format!("({})", row.join(", ")))
+ .collect::<Vec<_>>()
+ .join(",\n ")
+}
+
+fn reset_users_sql(users: &[LocalE2eUser]) -> String {
+ let user_ids = users
+ .iter()
+ .map(|user| sql_string(&user.user_id))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let macro_user_ids = users
+ .iter()
+ .map(|user| sql_string(&user.macro_user_id))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let emails = users
+ .iter()
+ .map(|user| sql_string(&user.email))
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ format!(
+ r#"DELETE FROM "User" WHERE id IN ({user_ids}) OR email IN ({emails});
+DELETE FROM macro_user WHERE id IN ({macro_user_ids}) OR email IN ({emails});"#,
+ )
+}
+
+fn seed_users_sql(users: &[LocalE2eUser]) -> String {
+ let macro_user_values = values_sql(users.iter().map(|user| {
+ vec![
+ sql_string(&user.macro_user_id),
+ sql_string(&user.username),
+ sql_string(&user.email),
+ sql_string(&user.stripe_customer_id),
+ sql_bool(user.has_trialed).to_string(),
+ ]
+ }));
+
+ let user_values = values_sql(users.iter().map(|user| {
+ vec![
+ sql_string(&user.user_id),
+ sql_string(&user.email),
+ sql_string(&user.stripe_customer_id),
+ sql_string(&user.macro_user_id),
+ sql_bool(user.tutorial_complete).to_string(),
+ sql_bool(user.has_onboarding_documents).to_string(),
+ ]
+ }));
+
+ let verification_values = values_sql(users.iter().map(|user| {
+ vec![
+ sql_string(&user.macro_user_id),
+ sql_string(&user.email),
+ sql_bool(user.is_verified).to_string(),
+ ]
+ }));
+
+ let info_values = values_sql(users.iter().map(|user| {
+ vec![
+ sql_string(&user.macro_user_id),
+ sql_string(&user.first_name),
+ sql_string(&user.last_name),
+ ]
+ }));
+
+ let role_rows = users.iter().flat_map(|user| {
+ user.roles
+ .iter()
+ .map(|role| vec![sql_string(&user.user_id), sql_string(role)])
+ });
+ let role_values = values_sql(role_rows);
+ let role_insert = if role_values.is_empty() {
+ String::new()
+ } else {
+ format!(
+ r#"
+INSERT INTO "RolesOnUsers" ("userId", "roleId") VALUES
+ {role_values}
+ON CONFLICT DO NOTHING;"#
+ )
+ };
+
+ format!(
+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id, has_trialed) VALUES
+ {macro_user_values}
+ON CONFLICT (id) DO UPDATE SET
+ username = EXCLUDED.username,
+ email = EXCLUDED.email,
+ stripe_customer_id = EXCLUDED.stripe_customer_id,
+ has_trialed = EXCLUDED.has_trialed;
+
+INSERT INTO "User" (id, email, "stripeCustomerId", macro_user_id, "tutorialComplete", "hasOnboardingDocuments") VALUES
+ {user_values}
+ON CONFLICT (id) DO UPDATE SET
+ email = EXCLUDED.email,
+ "stripeCustomerId" = EXCLUDED."stripeCustomerId",
+ macro_user_id = EXCLUDED.macro_user_id,
+ "tutorialComplete" = EXCLUDED."tutorialComplete",
+ "hasOnboardingDocuments" = EXCLUDED."hasOnboardingDocuments";
+
+INSERT INTO macro_user_email_verification (macro_user_id, email, is_verified) VALUES
+ {verification_values}
+ON CONFLICT (email) DO UPDATE SET
+ macro_user_id = EXCLUDED.macro_user_id,
+ is_verified = EXCLUDED.is_verified;
+
+INSERT INTO macro_user_info (macro_user_id, first_name, last_name) VALUES
+ {info_values}
+ON CONFLICT (macro_user_id) DO UPDATE SET
+ first_name = EXCLUDED.first_name,
+ last_name = EXCLUDED.last_name;
+{role_insert}"#,
+ )
+}
+
+/// Arguments for the `scenario` subcommand.
+#[derive(Debug, Args)]
+pub struct ScenarioArgs {
+ /// The scenario to apply.
+ #[command(subcommand)]
+ pub command: ScenarioCommand,
+}
+
+/// Available seed scenarios.
+#[derive(Debug, Subcommand)]
+pub enum ScenarioCommand {
+ /// Reset and apply the local Playwright smoke-test fixture data.
+ LocalE2eSmoke,
+}
+
+impl ScenarioArgs {
+ /// Validate environment-sensitive safety checks before connecting to services.
+ pub fn validate_environment(&self, env_vars: &EnvVars) -> anyhow::Result<()> {
+ match &self.command {
+ ScenarioCommand::LocalE2eSmoke => {
+ validate_local_e2e_environment(env_vars.database_url.as_ref())
+ }
+ }
+ }
+
+ /// Execute the scenario command.
+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {
+ match self.command {
+ ScenarioCommand::LocalE2eSmoke => local_e2e_smoke(&ctx).await,
+ }
+ }
+}
+
+fn validate_local_e2e_environment(database_url: &str) -> anyhow::Result<()> {
+ ensure!(
+ std::env::var("LOCAL_E2E_SEED").as_deref() == Ok("true"),
+ "refusing to run destructive local-e2e-smoke seed without LOCAL_E2E_SEED=true"
+ );
+
+ validate_local_e2e_database_url(database_url)
+}
+
+fn validate_local_e2e_database_url(database_url: &str) -> anyhow::Result<()> {
+ let parsed = url::Url::parse(database_url).context("DATABASE_URL must be a valid URL")?;
+ let host = parsed.host_str().unwrap_or_default();
+ let username = parsed.username();
+ let database = parsed.path().trim_start_matches('/');
+ let port = parsed.port_or_known_default();
+
+ let is_local_host = matches!(host, "localhost" | "127.0.0.1" | "::1" | "postgres");
+ let is_local_compose_db = username == "user" && database == "macrodb" && port == Some(5432);
+
+ ensure!(
+ is_local_host && is_local_compose_db,
+ "refusing to run local-e2e-smoke seed against DATABASE_URL host={host:?} user={username:?} database={database:?}; expected local docker database postgres://user:...@(localhost|127.0.0.1|postgres):5432/macrodb"
+ );
+
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{local_e2e_seed_data, validate_local_e2e_database_url};
+
+ #[test]
+ fn local_e2e_database_url_accepts_localhost_compose_db() {
+ validate_local_e2e_database_url("postgres://user:password@localhost:5432/macrodb").unwrap();
+ validate_local_e2e_database_url("postgres://user:[email protected]:5432/macrodb").unwrap();
+ validate_local_e2e_database_url("postgres://user:password@postgres:5432/macrodb").unwrap();
+ }
+
+ #[test]
+ fn local_e2e_database_url_rejects_dev_like_db() {
+ assert!(
+ validate_local_e2e_database_url(
+ "postgres://macrouser:[email protected]:5432/macrodb"
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn local_e2e_database_url_rejects_wrong_local_user() {
+ assert!(
+ validate_local_e2e_database_url("postgres://macrouser:secret@localhost:5432/macrodb")
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn local_e2e_manifest_user_exists_in_users_json() {
+ let seed_data = local_e2e_seed_data().unwrap();
+
+ assert!(
+ seed_data
+ .users
+ .iter()
+ .any(|user| user.email == seed_data.manifest.user.email)
+ );
+ }
+}
+
+#[tracing::instrument(skip(ctx), err)]
+async fn local_e2e_smoke(ctx: &SeedCliContext) -> anyhow::Result<()> {
+ let seed_data = local_e2e_seed_data()?;
+ let local_e2e_user_id = seed_data
+ .users
+ .iter()
+ .find(|user| user.email == seed_data.manifest.user.email)
+ .map(|user| user.user_id.clone())
+ .with_context(|| {
+ format!(
+ "local e2e user {} must exist in users.json",
+ seed_data.manifest.user.email
+ )
+ })?;
+
+ tracing::info!("resetting local e2e smoke data");
+ ctx.db
+ .execute_sql_if_table_exists(
+ "public.contacts_backfill_outbox",
+ "DELETE FROM contacts_backfill_outbox WHERE comms_channel_id::text LIKE '00000000-0000-0000-0000-00000000000%'",
+ )
+ .await?;
+ ctx.db.execute_sql_script(LOCAL_E2E_RESET_SQL).await?;
+ ctx.db
+ .execute_sql_script(&reset_users_sql(&seed_data.users))
+ .await?;
+
+ tracing::info!("creating local e2e smoke users");
+ ctx.db
+ .execute_sql_script(&seed_users_sql(&seed_data.users))
+ .await?;
+
+ tracing::info!("seeding local e2e smoke documents");
+ let documents_path = seed_path("seed/documents/documents.json");
+ document::seed_from_file_ref(
+ &document::SeedArgs {
+ user_id: local_e2e_user_id.clone(),
+ file_path: None,
+ },
+ ctx,
+ &documents_path,
+ )
+ .await?;
+
+ tracing::info!("seeding local e2e smoke channels");
+ let channels_path = seed_path("seed/channels.json");
+ channel::seed_from_file_ref(
+ &channel::SeedArgs {
+ user_id: local_e2e_user_id.clone(),
+ file_path: None,
+ },
+ ctx,
+ &channels_path,
+ )
+ .await?;
+
+ tracing::info!("seeding local e2e smoke channel messages");
+ let channel_messages_path = seed_path("seed/channel_messages.json");
+ channel_message::seed_from_file_ref(ctx, &channel_messages_path).await?;
+
+ println!("Local e2e smoke seed data ready for {local_e2e_user_id}");
+ Ok(())
+}
diff --git a/rust/cloud-storage/seed_cli/src/main.rs b/rust/cloud-storage/seed_cli/src/main.rs
index 4a5fdaf3f8..173f7df6a9 100644
--- a/rust/cloud-storage/seed_cli/src/main.rs
+++ b/rust/cloud-storage/seed_cli/src/main.rs
@@ -33,7 +33,9 @@ pub struct Cli {
pub async fn main() -> anyhow::Result<()> {
// Force to use local tracing
MacroEntrypoint::new(Environment::Local).init();
+ let cli = Cli::parse();
let env_vars = EnvVars::new()?;
+ cli.command.validate_environment(&env_vars)?;
tracing::trace!("initializing");
let db = PgPoolOptions::new()
@@ -69,7 +71,6 @@ pub async fn main() -> anyhow::Result<()> {
),
};
- let cli = Cli::parse();
cli.command.execute(context).await
}
diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rs
index 0c97f331a2..c8c879b588 100644
--- a/rust/cloud-storage/seed_cli/src/service/db/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs
@@ -35,6 +35,39 @@ impl SeedDb {
Self { inner }
}
+ /// Execute a semicolon-delimited SQL script inside a transaction.
+ #[tracing::instrument(skip(self, sql), err)]
+ pub async fn execute_sql_script(&self, sql: &str) -> anyhow::Result<()> {
+ let mut transaction = self.inner.begin().await?;
+
+ for statement in sql.split(';').map(str::trim).filter(|s| !s.is_empty()) {
+ sqlx::query(statement).execute(&mut *transaction).await?;
+ }
+
+ transaction.commit().await?;
+ Ok(())
+ }
+
+ /// Execute SQL only when the table exists in the current database.
+ #[tracing::instrument(skip(self, sql), err)]
+ pub async fn execute_sql_if_table_exists(
+ &self,
+ table_name: &str,
+ sql: &str,
+ ) -> anyhow::Result<()> {
+ let exists = sqlx::query_scalar::<_, Option<String>>("SELECT to_regclass($1)::text")
+ .bind(table_name)
+ .fetch_one(&self.inner)
+ .await?
+ .is_some();
+
+ if exists {
+ sqlx::query(sql).execute(&self.inner).await?;
+ }
+
+ Ok(())
+ }
+
/// Create a document in the database.
#[tracing::instrument(skip(self), err)]
pub async fn create_document<'a>(