Repository navigation
feat: source file dates, dbmate migrations, and subpath deployment support - #870
Conversation
There was a problem hiding this comment.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
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.
b0ef347 to
f194554
Compare
📝 WalkthroughWalkthroughThis PR implements support for Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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
EnvConfigis missingTALE_VERSIONcompared toserver.tsandlib/env.ts.The
EnvConfiginterface here omitsTALE_VERSION, which is present in bothservices/platform/server.ts(line 12) and theWindow.__ENV__interface inservices/platform/lib/env.ts. During development (non-production), this plugin injectswindow.__ENV__withoutTALE_VERSION, causinggetEnv('TALE_VERSION')to always returnundefinedin 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 | 🔵 TrivialMinor redundancy:
getBasePath()is called twice per HTML request.
getEnvConfig()on line 78 already callsgetBasePath()to populateenvConfig.BASE_PATH. Line 80 then callsgetBasePath()again. Consider reusingenvConfig.BASE_PATHinstead:- 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
📒 Files selected for processing (45)
.env.exampleREADME.mdservices/platform/app/components/ui/data-display/image.tsxservices/platform/app/components/ui/logo/tale-logo-text.tsxservices/platform/app/components/ui/logo/tale-logo.tsxservices/platform/app/components/user-button.tsxservices/platform/app/features/automations/triggers/components/webhooks-section.tsxservices/platform/app/features/custom-agents/components/custom-agent-webhook-section.tsxservices/platform/app/features/documents/components/microsoft-reauth-button.tsxservices/platform/app/router.tsxservices/platform/app/routes/_auth/log-in.tsxservices/platform/app/routes/_auth/sign-up.tsxservices/platform/app/routes/dashboard.tsxservices/platform/convex/agent_tools/files/docx_tool.tsservices/platform/convex/agent_tools/files/excel_tool.tsservices/platform/convex/agent_tools/files/helpers/append_file_part.tsservices/platform/convex/agent_tools/files/image_tool.tsservices/platform/convex/agent_tools/files/pdf_tool.tsservices/platform/convex/agent_tools/files/pptx_tool.tsservices/platform/convex/agent_tools/files/text_tool.tsservices/platform/convex/documents/actions.tsservices/platform/convex/documents/generate_document_helpers.tsservices/platform/convex/documents/generate_signed_url.tsservices/platform/convex/documents/internal_actions.tsservices/platform/convex/documents/internal_queries.tsservices/platform/convex/documents/list_indexed_documents_for_agent.tsservices/platform/convex/documents/transform_to_document_item.tsservices/platform/convex/files/mutations.tsservices/platform/convex/integrations/generate_oauth2_auth_url.tsservices/platform/convex/integrations/oauth2_callback.tsservices/platform/convex/lib/helpers/public_storage_url.tsservices/platform/convex/sso_providers/sso_callback_handler.tsservices/platform/convex/sso_providers/sso_set_session_handler.tsservices/platform/convex/websites/internal_actions.tsservices/platform/docker-entrypoint.shservices/platform/lib/auth-client.tsservices/platform/lib/env.tsservices/platform/lib/site-url-context.tsxservices/platform/server.tsservices/platform/vite-plugins/inject-env.tsservices/platform/vite.config.tsservices/proxy/Caddyfileservices/proxy/docker-entrypoint.shservices/rag/app/routers/search.pyservices/rag/app/services/indexing_service.py
| const isMember = await ctx.runQuery( | ||
| internal.documents.internal_queries.verifyOrganizationMembership, | ||
| { | ||
| organizationId: document.organizationId, | ||
| userId: String(authUser._id), | ||
| }, | ||
| ); | ||
| if (!isMember) { | ||
| return { success: false, error: 'Unauthorized' }; | ||
| } |
There was a problem hiding this comment.
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.
| 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.
| return { | ||
| success: true, | ||
| url, | ||
| url: buildDownloadUrl(document.fileId, document.title ?? 'download'), | ||
| }; |
There was a problem hiding this comment.
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:
- The document record is validated to exist (lines 14-20)
- The
fileIdfield is validated to be present (lines 22-27) - Document records with
fileIdshould 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.
| const basePath = process.env.BASE_PATH || ''; | ||
| const redirectUri = `${siteUrl}${basePath}/api/integrations/oauth2/callback`; |
There was a problem hiding this comment.
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.
| 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`; | ||
| } |
There was a problem hiding this comment.
🧹 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.
| 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.
| export function buildDownloadUrl(storageId: string, fileName: string): string { | ||
| return `${getPublicHttpApiUrl()}/storage?id=${storageId}&filename=${encodeURIComponent(fileName)}`; | ||
| } |
There was a problem hiding this comment.
🧹 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.
| 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.
| const basePath = process.env.BASE_PATH || ''; | ||
| const errorUrl = new URL(`${basePath}/log-in`, origin); |
There was a problem hiding this comment.
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.
| 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> |
There was a problem hiding this comment.
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).
| const basePath = getEnv('BASE_PATH'); | ||
| return { | ||
| siteUrl, | ||
| convexUrl: `${siteUrl}/ws_api`, | ||
| convexUrl: `${siteUrl}${basePath}/ws_api`, | ||
| }; |
There was a problem hiding this comment.
🧩 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.tsxRepository: 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.
Summary
list_indexedagent operation and denormalizedindexedfield for fast lookups.ensure_*functions in the RAG service with versioned dbmate migrations that run automatically on DB container startup.https://example.com/tale/) viaBASE_PATHenv var. Wires through OAuth callbacks, SSO redirects, webhook URLs, frontend routing, auth, Convex WebSocket URLs, and Caddy proxy config.Test plan
source_created_at/source_modified_atannotationslist_indexedagent operation returns indexed documents correctlyensure_*stateBASE_PATH=/tale/behind a reverse proxy and verify login, OAuth, SSO, file uploads/downloads, and WebSocket connections all workBASE_PATHand verify no regressionsSummary by CodeRabbit
Release Notes
New Features
BASE_PATHconfiguration for serving the application under a URL subpath (e.g.,https://example.com/app).Bug Fixes
Documentation
Improvements