Skip to content

feat: source file dates, dbmate migrations, and subpath deployment support - #870

Merged
larryro merged 5 commits into
mainfrom
feat/subpath-deployment
Mar 26, 2026
Merged

larryro merged 5 commits into
mainfrom
feat/subpath-deployment

Conversation

@larryro

@larryro larryro commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Source file dates: Extract and store original creation/modification dates from uploaded documents (OOXML, PDF, plaintext). Dates flow through the crawler, Convex schema, PostgreSQL knowledge DB, and RAG search results — enabling date-aware agent retrieval. Adds list_indexed agent operation and denormalized indexed field for fast lookups.
  • Database migrations: Replace ad-hoc ensure_* functions in the RAG service with versioned dbmate migrations that run automatically on DB container startup.
  • Subpath deployments: Allow deploying behind a reverse proxy at a subpath (e.g. https://example.com/tale/) via BASE_PATH env var. Wires through OAuth callbacks, SSO redirects, webhook URLs, frontend routing, auth, Convex WebSocket URLs, and Caddy proxy config.
  • Misc: Dependency updates (workflow v0.3.7, better-auth v0.11.3, react-json-view v1.31.14), lint fixes, removal of unused example workflow configs.

Test plan

  • Verify document upload extracts and displays file dates in the documents table (Modified / Uploaded at columns)
  • Verify RAG search results include source_created_at / source_modified_at annotations
  • Verify list_indexed agent operation returns indexed documents correctly
  • Verify dbmate migrations apply cleanly on a fresh database and on an existing database with prior ensure_* state
  • Deploy with BASE_PATH=/tale/ behind a reverse proxy and verify login, OAuth, SSO, file uploads/downloads, and WebSocket connections all work
  • Deploy without BASE_PATH and verify no regressions
  • Run existing platform and RAG test suites

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for reverse-proxy subpath deployments via BASE_PATH configuration for serving the application under a URL subpath (e.g., https://example.com/app).
    • Improved file download URL generation and public storage URL handling.
  • Bug Fixes

    • Fixed OAuth2 and SSO callback handling to respect configured base paths.
    • Added authorization checks for document RAG indexing operations.
    • Fixed webhook and API URL construction to include configured base paths.
  • Documentation

    • Added subpath deployment configuration guide with reverse-proxy examples.
  • Improvements

    • File generation tools now provide proper download URLs based on availability.
    • Enhanced error logging for file processing and data extraction.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

larryro added 4 commits March 26, 2026 08:51
Replace ad-hoc ensure_* functions with a proper versioned migration system
using dbmate. Migrations run automatically on DB container startup after
init scripts, with a healthcheck sentinel to block services until complete.

- Install dbmate binary in DB Docker image
- Convert ensure_error_column, ensure_content_hash_index, ensure_file_id_column,
  and ensure_document_date_columns to versioned SQL migration files
- Add baseline migration to mark init-script state as version zero
- Update entrypoint to run migrations after init scripts with /tmp/.db_ready sentinel
- Rename ensure_embedding_dimensions to pin_embedding_dimensions (runtime config)
- Remove migrated ensure_* functions from RAG service database.py
Use datetime.UTC alias instead of datetime.timezone.utc (ruff UP017)
and remove dbmate scripts from db package.json (knip unlisted binary).
Allow deploying Tale behind a reverse proxy at a subpath (e.g.,
https://example.com/tale/) by introducing the BASE_PATH environment
variable. The proxy strips the prefix before forwarding, the frontend
uses it for asset paths, routing, auth, and Convex WebSocket URLs,
and the backend injects it into download/upload URLs. Also extracts
storage URL helpers into a shared module and adds a dedicated Caddy
route for Convex storage uploads.
… tools

Wire BASE_PATH through OAuth2 callbacks, SSO redirects, webhook URLs,
and frontend navigation. Fix sub-agent file generation to surface
download URLs when chat file cards are not visible. Add org membership
check to retryRagIndexing, support env var removal in docker entrypoint,
and propagate source_created_at through RAG search results.
@larryro
larryro force-pushed the feat/subpath-deployment branch from b0ef347 to f194554 Compare March 26, 2026 00:56
@coderabbitai

coderabbitai Bot commented Mar 26, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR implements support for BASE_PATH environment variable to enable subpath deployments behind reverse proxies. Changes include adding configuration for the new variable across development and runtime environments, updating frontend components to prepend BASE_PATH to asset and API endpoint paths, modifying backend services to incorporate BASE_PATH into redirect URIs and webhook URLs, refactoring shared document URL helpers into a new public storage module, adding authorization checks to RAG document processing, and updating infrastructure scripts (Docker, Vite, proxy configuration) to handle base path stripping and injection. The RAG service is also updated to include source_created_at fields in search results.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the three main features introduced in the changeset: source file dates extraction and propagation, database migrations system, and subpath deployment support via BASE_PATH.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/subpath-deployment

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
services/platform/vite-plugins/inject-env.ts (1)

3-9: ⚠️ Potential issue | 🟡 Minor

EnvConfig is missing TALE_VERSION compared to server.ts and lib/env.ts.

The EnvConfig interface here omits TALE_VERSION, which is present in both services/platform/server.ts (line 12) and the Window.__ENV__ interface in services/platform/lib/env.ts. During development (non-production), this plugin injects window.__ENV__ without TALE_VERSION, causing getEnv('TALE_VERSION') to always return undefined in dev mode.

Consider adding:

 interface EnvConfig {
   SITE_URL: string;
   BASE_PATH: string;
   MICROSOFT_AUTH_ENABLED: boolean;
   SENTRY_DSN?: string;
   SENTRY_TRACES_SAMPLE_RATE: number;
+  TALE_VERSION?: string;
 }

And in getEnvConfig():

   return {
     SITE_URL: process.env.SITE_URL,
     BASE_PATH: (process.env.BASE_PATH ?? '').replace(/\/$/, ''),
     MICROSOFT_AUTH_ENABLED: process.env.MICROSOFT_AUTH_ENABLED === 'true',
     SENTRY_DSN: process.env.SENTRY_DSN,
     SENTRY_TRACES_SAMPLE_RATE: parseFloat(
       process.env.SENTRY_TRACES_SAMPLE_RATE || '1.0',
     ),
+    TALE_VERSION: process.env.TALE_VERSION,
   };
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/vite-plugins/inject-env.ts` around lines 3 - 9, EnvConfig
in inject-env.ts omits TALE_VERSION which causes getEnv('TALE_VERSION') to be
undefined in dev; update the EnvConfig interface to include TALE_VERSION: string
and ensure getEnvConfig() (the function that builds the injected object)
includes TALE_VERSION in its returned object (sourcing the same env value used
in server.ts/lib/env.ts) so window.__ENV__ contains TALE_VERSION in development
builds.
services/platform/server.ts (1)

80-94: 🧹 Nitpick | 🔵 Trivial

Minor redundancy: getBasePath() is called twice per HTML request.

getEnvConfig() on line 78 already calls getBasePath() to populate envConfig.BASE_PATH. Line 80 then calls getBasePath() again. Consider reusing envConfig.BASE_PATH instead:

-    const basePath = getBasePath();
+    const basePath = envConfig.BASE_PATH;

The <base href> injection correctly ensures relative URLs resolve from the subpath root.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/server.ts` around lines 80 - 94, getBasePath() is being
called twice; reuse the already-computed value in envConfig to avoid redundant
calls. Replace the second call in the HTML generation block by referencing
envConfig.BASE_PATH (or assign const basePath = envConfig.BASE_PATH) and keep
the existing truthiness check before injecting the <base href> into
indexHtmlTemplate; update references to basePath to use envConfig.BASE_PATH so
getBasePath() is only invoked once (the call inside getEnvConfig()).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@services/platform/convex/documents/actions.ts`:
- Around line 37-46: The current code in actions.ts reveals whether a document
exists by returning "Document not found" for missing docs and "Unauthorized" for
existing-but-inaccessible docs; change the branch that checks
internal.documents.internal_queries.verifyOrganizationMembership so that when
the user is not a member it returns the same generic error used for missing
documents (e.g., "Document not found" or a generic "Not found") instead of
"Unauthorized" to avoid disclosing cross-organization existence. Update the
return in the membership check (the block using verifyOrganizationMembership and
authUser._id) to mirror the other error path so callers cannot distinguish
existence vs access.

In `@services/platform/convex/documents/generate_signed_url.ts`:
- Around line 29-32: The change replaced ctx.storage.getUrl() with
buildDownloadUrl(), which always returns a string and can mask missing storage
entries; update generate_signed_url to validate the storage exists before
returning a URL: call ctx.storage.getUrl(document.fileId) (or an equivalent
storage lookup) and if it returns null/undefined return { success: false, error:
"Failed to generate signed URL" } (or a clear error) instead of returning
buildDownloadUrl's value, otherwise use buildDownloadUrl(document.fileId,
document.title ?? 'download') as before; reference functions/identifiers:
generate_signed_url, ctx.storage.getUrl, buildDownloadUrl, and document.fileId.

In `@services/platform/convex/integrations/oauth2_callback.ts`:
- Around line 118-119: buildRedirectUrl currently builds user-facing
post-callback links without honoring BASE_PATH, causing redirects to drop users
outside subpath deployments; update buildRedirectUrl to prefix the returned
paths with the same basePath used for redirectUri (use the basePath constant
derived from process.env.BASE_PATH || '' and siteUrl) so that dashboard/settings
redirects become `${siteUrl}${basePath}/dashboard/...` or
`${siteUrl}${basePath}/settings/...`, taking care to normalize slashes when
concatenating.

In `@services/platform/convex/lib/helpers/public_storage_url.ts`:
- Around line 30-32: The query string currently only encodes fileName; update
buildDownloadUrl to also encode storageId before interpolation so both params
are URL-safe. In the buildDownloadUrl function (which calls
getPublicHttpApiUrl()), replace raw storageId usage with an encoded value (e.g.,
encodeURIComponent(storageId)) while retaining encodeURIComponent(fileName) to
defensively handle any future storage ID characters.
- Around line 15-22: getPublicHttpApiUrl() can produce double slashes because it
concatenates SITE_URL and BASE_PATH without normalization; update it to mirror
toPublicUrl() by stripping a trailing slash from siteUrl and normalizing
basePath so there is exactly one slash between them. Concretely, in
getPublicHttpApiUrl(): set siteUrl = siteUrl.replace(/\/$/, '') and normalize
basePath to either '' or `/${basePath.replace(/^\/|\/$/g, '')}`, then return
`${siteUrl}${basePath}/http_api`; reference getPublicHttpApiUrl(),
toPublicUrl(), siteUrl, basePath, SITE_URL, BASE_PATH.

In `@services/platform/convex/sso_providers/sso_callback_handler.ts`:
- Around line 12-13: The success redirect is not using BASE_PATH while error
redirects do; update the success redirect logic (where it builds
`${frontendOrigin}/dashboard`, referenced near the success branch in
sso_callback_handler.ts) to incorporate basePath/origin the same way errorUrl
does (use basePath and origin to construct the dashboard URL, e.g. new
URL(`${basePath}/dashboard`, origin) or otherwise join basePath safely), and
replace the existing `${frontendOrigin}/dashboard` construction so successful
logins land under the configured BASE_PATH consistently with
redirectWithError/errorUrl.

In `@services/platform/convex/sso_providers/sso_set_session_handler.ts`:
- Around line 85-95: The error recovery link in the SSO HTML should use the same
BASE_PATH-aware basePath as the success redirect; update the error-page
HTML/template that currently points to '/log-in' to use `${basePath}/log-in` (or
join safely to avoid double slashes) and mirror both the meta refresh and the
script fallback to use the basePath variable (same approach used where basePath
is defined and used in the success html string).

In `@services/platform/lib/site-url-context.tsx`:
- Around line 21-25: Remove the dead convexUrl field from the SiteUrlContext:
stop calling getEnv('BASE_PATH') and stop returning convexUrl in the object;
instead only supply siteUrl (which is what useSiteUrl() consumes). Update the
context creation in site-url-context.tsx by removing the convexUrl property and
any related BASE_PATH usage, leaving only siteUrl so no unused symbols remain.

---

Outside diff comments:
In `@services/platform/server.ts`:
- Around line 80-94: getBasePath() is being called twice; reuse the
already-computed value in envConfig to avoid redundant calls. Replace the second
call in the HTML generation block by referencing envConfig.BASE_PATH (or assign
const basePath = envConfig.BASE_PATH) and keep the existing truthiness check
before injecting the <base href> into indexHtmlTemplate; update references to
basePath to use envConfig.BASE_PATH so getBasePath() is only invoked once (the
call inside getEnvConfig()).

In `@services/platform/vite-plugins/inject-env.ts`:
- Around line 3-9: EnvConfig in inject-env.ts omits TALE_VERSION which causes
getEnv('TALE_VERSION') to be undefined in dev; update the EnvConfig interface to
include TALE_VERSION: string and ensure getEnvConfig() (the function that builds
the injected object) includes TALE_VERSION in its returned object (sourcing the
same env value used in server.ts/lib/env.ts) so window.__ENV__ contains
TALE_VERSION in development builds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7f612344-d730-435b-8b38-70dda003defc

📥 Commits

Reviewing files that changed from the base of the PR and between 7f61f2a and f194554.

📒 Files selected for processing (45)
  • .env.example
  • README.md
  • services/platform/app/components/ui/data-display/image.tsx
  • services/platform/app/components/ui/logo/tale-logo-text.tsx
  • services/platform/app/components/ui/logo/tale-logo.tsx
  • services/platform/app/components/user-button.tsx
  • services/platform/app/features/automations/triggers/components/webhooks-section.tsx
  • services/platform/app/features/custom-agents/components/custom-agent-webhook-section.tsx
  • services/platform/app/features/documents/components/microsoft-reauth-button.tsx
  • services/platform/app/router.tsx
  • services/platform/app/routes/_auth/log-in.tsx
  • services/platform/app/routes/_auth/sign-up.tsx
  • services/platform/app/routes/dashboard.tsx
  • services/platform/convex/agent_tools/files/docx_tool.ts
  • services/platform/convex/agent_tools/files/excel_tool.ts
  • services/platform/convex/agent_tools/files/helpers/append_file_part.ts
  • services/platform/convex/agent_tools/files/image_tool.ts
  • services/platform/convex/agent_tools/files/pdf_tool.ts
  • services/platform/convex/agent_tools/files/pptx_tool.ts
  • services/platform/convex/agent_tools/files/text_tool.ts
  • services/platform/convex/documents/actions.ts
  • services/platform/convex/documents/generate_document_helpers.ts
  • services/platform/convex/documents/generate_signed_url.ts
  • services/platform/convex/documents/internal_actions.ts
  • services/platform/convex/documents/internal_queries.ts
  • services/platform/convex/documents/list_indexed_documents_for_agent.ts
  • services/platform/convex/documents/transform_to_document_item.ts
  • services/platform/convex/files/mutations.ts
  • services/platform/convex/integrations/generate_oauth2_auth_url.ts
  • services/platform/convex/integrations/oauth2_callback.ts
  • services/platform/convex/lib/helpers/public_storage_url.ts
  • services/platform/convex/sso_providers/sso_callback_handler.ts
  • services/platform/convex/sso_providers/sso_set_session_handler.ts
  • services/platform/convex/websites/internal_actions.ts
  • services/platform/docker-entrypoint.sh
  • services/platform/lib/auth-client.ts
  • services/platform/lib/env.ts
  • services/platform/lib/site-url-context.tsx
  • services/platform/server.ts
  • services/platform/vite-plugins/inject-env.ts
  • services/platform/vite.config.ts
  • services/proxy/Caddyfile
  • services/proxy/docker-entrypoint.sh
  • services/rag/app/routers/search.py
  • services/rag/app/services/indexing_service.py

Comment on lines +37 to +46
const isMember = await ctx.runQuery(
internal.documents.internal_queries.verifyOrganizationMembership,
{
organizationId: document.organizationId,
userId: String(authUser._id),
},
);
if (!isMember) {
return { success: false, error: 'Unauthorized' };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid document-ID existence disclosure across organizations.

Line [45] returns "Unauthorized" while Line [34] returns "Document not found", which lets callers distinguish “exists but inaccessible” from “doesn’t exist”.

🔒 Proposed minimal fix
       if (!isMember) {
-        return { success: false, error: 'Unauthorized' };
+        return { success: false, error: 'Document not found' };
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const isMember = await ctx.runQuery(
internal.documents.internal_queries.verifyOrganizationMembership,
{
organizationId: document.organizationId,
userId: String(authUser._id),
},
);
if (!isMember) {
return { success: false, error: 'Unauthorized' };
}
const isMember = await ctx.runQuery(
internal.documents.internal_queries.verifyOrganizationMembership,
{
organizationId: document.organizationId,
userId: String(authUser._id),
},
);
if (!isMember) {
return { success: false, error: 'Document not found' };
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/documents/actions.ts` around lines 37 - 46, The
current code in actions.ts reveals whether a document exists by returning
"Document not found" for missing docs and "Unauthorized" for
existing-but-inaccessible docs; change the branch that checks
internal.documents.internal_queries.verifyOrganizationMembership so that when
the user is not a member it returns the same generic error used for missing
documents (e.g., "Document not found" or a generic "Not found") instead of
"Unauthorized" to avoid disclosing cross-organization existence. Update the
return in the membership check (the block using verifyOrganizationMembership and
authUser._id) to mirror the other error path so callers cannot distinguish
existence vs access.

Comment on lines 29 to 32
return {
success: true,
url,
url: buildDownloadUrl(document.fileId, document.title ?? 'download'),
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Changed error handling behavior for invalid storage IDs.

The previous implementation used ctx.storage.getUrl() which returns null for non-existent storage IDs, allowing the function to return { success: false, error: "Failed to generate signed URL" }. The new buildDownloadUrl() always returns a URL string regardless of whether the storage ID is valid.

This is likely acceptable because:

  1. The document record is validated to exist (lines 14-20)
  2. The fileId field is validated to be present (lines 22-27)
  3. Document records with fileId should have valid storage entries (DB consistency)

However, if a storage entry is deleted without updating the document record, this will now return a broken URL instead of an error. Consider whether this edge case warrants additional validation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/documents/generate_signed_url.ts` around lines 29 -
32, The change replaced ctx.storage.getUrl() with buildDownloadUrl(), which
always returns a string and can mask missing storage entries; update
generate_signed_url to validate the storage exists before returning a URL: call
ctx.storage.getUrl(document.fileId) (or an equivalent storage lookup) and if it
returns null/undefined return { success: false, error: "Failed to generate
signed URL" } (or a clear error) instead of returning buildDownloadUrl's value,
otherwise use buildDownloadUrl(document.fileId, document.title ?? 'download') as
before; reference functions/identifiers: generate_signed_url,
ctx.storage.getUrl, buildDownloadUrl, and document.fileId.

Comment on lines +118 to +119
const basePath = process.env.BASE_PATH || '';
const redirectUri = `${siteUrl}${basePath}/api/integrations/oauth2/callback`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Post-callback UI redirect still ignores BASE_PATH.

This update fixes the provider-facing redirectUri, but the user-facing redirect built in buildRedirectUrl (Line 50) still sends users to root paths (/dashboard/... or /settings/...). In subpath deployments, that drops users outside the app prefix.

🔧 Proposed fix
 function buildRedirectUrl(
   organizationId: string | undefined,
   params: {
     integration_oauth2?: string;
     integration_oauth2_error?: ErrorType;
     description?: string;
   },
 ): string {
   const siteUrl = process.env.SITE_URL || 'http://localhost:3000';
-  const basePath = organizationId
+  const appBasePath = process.env.BASE_PATH || '';
+  const settingsPath = organizationId
     ? `/dashboard/${organizationId}/settings/integrations`
     : '/settings/integrations';
@@
   const queryString = searchParams.toString();
-  return `${siteUrl}${basePath}${queryString ? `?${queryString}` : ''}`;
+  return `${siteUrl}${appBasePath}${settingsPath}${queryString ? `?${queryString}` : ''}`;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/integrations/oauth2_callback.ts` around lines 118 -
119, buildRedirectUrl currently builds user-facing post-callback links without
honoring BASE_PATH, causing redirects to drop users outside subpath deployments;
update buildRedirectUrl to prefix the returned paths with the same basePath used
for redirectUri (use the basePath constant derived from process.env.BASE_PATH ||
'' and siteUrl) so that dashboard/settings redirects become
`${siteUrl}${basePath}/dashboard/...` or `${siteUrl}${basePath}/settings/...`,
taking care to normalize slashes when concatenating.

Comment on lines +15 to +22
export function getPublicHttpApiUrl(): string {
const siteUrl = process.env.SITE_URL;
if (!siteUrl) {
throw new Error('Missing required environment variable: SITE_URL');
}
const basePath = process.env.BASE_PATH ?? '';
return `${siteUrl}${basePath}/http_api`;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Inconsistent trailing-slash handling across URL helpers.

getPublicHttpApiUrl() directly concatenates siteUrl without stripping a trailing slash, while toPublicUrl() (line 47) uses siteUrl.replace(/\/$/, ''). If SITE_URL is configured with a trailing slash (e.g., https://example.com/) and BASE_PATH starts with a slash (e.g., /tale), this function produces a double-slash: https://example.com//tale/http_api.

Consider normalizing consistently:

Proposed fix
 export function getPublicHttpApiUrl(): string {
   const siteUrl = process.env.SITE_URL;
   if (!siteUrl) {
     throw new Error('Missing required environment variable: SITE_URL');
   }
   const basePath = process.env.BASE_PATH ?? '';
-  return `${siteUrl}${basePath}/http_api`;
+  return `${siteUrl.replace(/\/$/, '')}${basePath}/http_api`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function getPublicHttpApiUrl(): string {
const siteUrl = process.env.SITE_URL;
if (!siteUrl) {
throw new Error('Missing required environment variable: SITE_URL');
}
const basePath = process.env.BASE_PATH ?? '';
return `${siteUrl}${basePath}/http_api`;
}
export function getPublicHttpApiUrl(): string {
const siteUrl = process.env.SITE_URL;
if (!siteUrl) {
throw new Error('Missing required environment variable: SITE_URL');
}
const basePath = process.env.BASE_PATH ?? '';
return `${siteUrl.replace(/\/$/, '')}${basePath}/http_api`;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/lib/helpers/public_storage_url.ts` around lines 15 -
22, getPublicHttpApiUrl() can produce double slashes because it concatenates
SITE_URL and BASE_PATH without normalization; update it to mirror toPublicUrl()
by stripping a trailing slash from siteUrl and normalizing basePath so there is
exactly one slash between them. Concretely, in getPublicHttpApiUrl(): set
siteUrl = siteUrl.replace(/\/$/, '') and normalize basePath to either '' or
`/${basePath.replace(/^\/|\/$/g, '')}`, then return
`${siteUrl}${basePath}/http_api`; reference getPublicHttpApiUrl(),
toPublicUrl(), siteUrl, basePath, SITE_URL, BASE_PATH.

Comment on lines +30 to +32
export function buildDownloadUrl(storageId: string, fileName: string): string {
return `${getPublicHttpApiUrl()}/storage?id=${storageId}&filename=${encodeURIComponent(fileName)}`;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider encoding storageId in the query string.

While Convex storage IDs are typically URL-safe, encoding all query parameters is defensive practice and guards against any future ID format changes.

Optional fix
 export function buildDownloadUrl(storageId: string, fileName: string): string {
-  return `${getPublicHttpApiUrl()}/storage?id=${storageId}&filename=${encodeURIComponent(fileName)}`;
+  return `${getPublicHttpApiUrl()}/storage?id=${encodeURIComponent(storageId)}&filename=${encodeURIComponent(fileName)}`;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function buildDownloadUrl(storageId: string, fileName: string): string {
return `${getPublicHttpApiUrl()}/storage?id=${storageId}&filename=${encodeURIComponent(fileName)}`;
}
export function buildDownloadUrl(storageId: string, fileName: string): string {
return `${getPublicHttpApiUrl()}/storage?id=${encodeURIComponent(storageId)}&filename=${encodeURIComponent(fileName)}`;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/lib/helpers/public_storage_url.ts` around lines 30 -
32, The query string currently only encodes fileName; update buildDownloadUrl to
also encode storageId before interpolation so both params are URL-safe. In the
buildDownloadUrl function (which calls getPublicHttpApiUrl()), replace raw
storageId usage with an encoded value (e.g., encodeURIComponent(storageId))
while retaining encodeURIComponent(fileName) to defensively handle any future
storage ID characters.

Comment on lines +12 to +13
const basePath = process.env.BASE_PATH || '';
const errorUrl = new URL(`${basePath}/log-in`, origin);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

SSO redirect handling is only partially BASE_PATH-aware.

redirectWithError now uses BASE_PATH, but successful login still redirects to ${frontendOrigin}/dashboard (Line 184). Under subpath deployments, success lands on the wrong URL while errors land correctly.

🔧 Proposed fix
-    headers.set('Location', `${frontendOrigin}/dashboard`);
+    const basePath = process.env.BASE_PATH || '';
+    headers.set('Location', `${frontendOrigin}${basePath}/dashboard`);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/sso_providers/sso_callback_handler.ts` around lines
12 - 13, The success redirect is not using BASE_PATH while error redirects do;
update the success redirect logic (where it builds
`${frontendOrigin}/dashboard`, referenced near the success branch in
sso_callback_handler.ts) to incorporate basePath/origin the same way errorUrl
does (use basePath and origin to construct the dashboard URL, e.g. new
URL(`${basePath}/dashboard`, origin) or otherwise join basePath safely), and
replace the existing `${frontendOrigin}/dashboard` construction so successful
logins land under the configured BASE_PATH consistently with
redirectWithError/errorUrl.

Comment on lines +85 to +95
const basePath = process.env.BASE_PATH || '';
const html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="refresh" content="0;url=/dashboard">
<meta http-equiv="refresh" content="0;url=${basePath}/dashboard">
<title>Completing login...</title>
</head>
<body>
<p>Completing login, please wait...</p>
<script>window.location.href = '/dashboard';</script>
<script>window.location.href = '${basePath}/dashboard';</script>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Make the SSO error recovery link BASE_PATH-aware as well.

Success redirect now uses BASE_PATH, but the error page still points to /log-in. Under subpath deployments, failed SSO flows can strand users on a broken recovery link.

💡 Proposed fix
 export async function ssoSetSessionHandler(
   ctx: ActionCtx,
   req: Request,
 ): Promise<Response> {
   const url = new URL(req.url);
   const token = url.searchParams.get('token');
   const frontendOrigin = url.origin;
+  const basePath = process.env.BASE_PATH || '';

   if (!token) {
-    return createErrorResponse(frontendOrigin, 'Missing session token');
+    return createErrorResponse(frontendOrigin, 'Missing session token', basePath);
   }

   const secret = process.env.BETTER_AUTH_SECRET;
   if (!secret) {
     console.error('[SSO Set Session] BETTER_AUTH_SECRET not configured');
-    return createErrorResponse(frontendOrigin, 'Server configuration error');
+    return createErrorResponse(frontendOrigin, 'Server configuration error', basePath);
   }

   try {
@@
-    const basePath = process.env.BASE_PATH || '';
     const html = `<!DOCTYPE html>
 <html>
 <head>
   <meta charset="utf-8">
   <meta http-equiv="refresh" content="0;url=${basePath}/dashboard">
@@
   } catch (error) {
     console.error('[SSO Set Session] Error:', error);
-    return createErrorResponse(frontendOrigin, 'Failed to complete login');
+    return createErrorResponse(frontendOrigin, 'Failed to complete login', basePath);
   }
 }
@@
-function createErrorResponse(origin: string, message: string): Response {
+function createErrorResponse(origin: string, message: string, basePath = ''): Response {
   const html = `<!DOCTYPE html>
 <html>
 <head>
   <meta charset="utf-8">
   <title>Login Error</title>
 </head>
 <body>
   <p>Error: ${escapeHtml(message)}</p>
-  <p><a href="/log-in">Return to login</a></p>
+  <p><a href="${basePath}/log-in">Return to login</a></p>
 </body>
 </html>`;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/convex/sso_providers/sso_set_session_handler.ts` around
lines 85 - 95, The error recovery link in the SSO HTML should use the same
BASE_PATH-aware basePath as the success redirect; update the error-page
HTML/template that currently points to '/log-in' to use `${basePath}/log-in` (or
join safely to avoid double slashes) and mirror both the meta refresh and the
script fallback to use the basePath variable (same approach used where basePath
is defined and used in the success html string).

Comment on lines +21 to 25
const basePath = getEnv('BASE_PATH');
return {
siteUrl,
convexUrl: `${siteUrl}/ws_api`,
convexUrl: `${siteUrl}${basePath}/ws_api`,
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for usages of convexUrl from SiteUrlContext
rg -n 'convexUrl' --type=ts --type=tsx -g '!*.test.*'

Repository: tale-project/tale

Length of output: 88


🏁 Script executed:

#!/bin/bash
# Search for usages of convexUrl (rg handles ts/tsx automatically)
rg -n 'convexUrl' -g '!*.test.*' -g '!*.spec.*'

Repository: tale-project/tale

Length of output: 3326


🏁 Script executed:

#!/bin/bash
# Read the full site-url-context.tsx file
cat -n services/platform/lib/site-url-context.tsx

Repository: tale-project/tale

Length of output: 1353


🏁 Script executed:

#!/bin/bash
# Search for direct context usage patterns
rg -n 'useContext\(SiteUrlContext\)|SiteUrlContext' -g '!*.test.*' -g '!*.spec.*'

Repository: tale-project/tale

Length of output: 473


Remove unused convexUrl from SiteUrlContext.

The convexUrl field is computed in the context but never used. The only exported hook is useSiteUrl() which returns only siteUrl, and no code accesses the context directly to retrieve convexUrl. Since other parts of the codebase (e.g., dev.ts, stress tests) compute the Convex URL independently from environment variables, this field is dead code and should be removed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@services/platform/lib/site-url-context.tsx` around lines 21 - 25, Remove the
dead convexUrl field from the SiteUrlContext: stop calling getEnv('BASE_PATH')
and stop returning convexUrl in the object; instead only supply siteUrl (which
is what useSiteUrl() consumes). Update the context creation in
site-url-context.tsx by removing the convexUrl property and any related
BASE_PATH usage, leaving only siteUrl so no unused symbols remain.

…bility

Fix BASE_PATH handling across OAuth, SSO, dashboard redirects, and URL
construction. Add retry logic for RAG document deletion, correct UUID
types in indexing service, and improve error handling/logging. Add tests
for document dates, composite cursor pagination, and transform helpers.
@larryro
larryro merged commit 982c29e into main Mar 26, 2026
16 checks passed
@larryro
larryro deleted the feat/subpath-deployment branch March 26, 2026 01:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant