@open-mercato/core 0.9.1-develop.7459.1.99e3accd30 → 0.9.1-develop.7464.1.9a392fca41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/api/route.js +29 -3
  3. package/dist/modules/attachments/api/route.js.map +2 -2
  4. package/dist/modules/attachments/lib/ocrLimits.js +49 -0
  5. package/dist/modules/attachments/lib/ocrLimits.js.map +7 -0
  6. package/dist/modules/attachments/lib/ocrQueue.js +76 -2
  7. package/dist/modules/attachments/lib/ocrQueue.js.map +2 -2
  8. package/dist/modules/attachments/lib/ocrService.js +4 -0
  9. package/dist/modules/attachments/lib/ocrService.js.map +2 -2
  10. package/dist/modules/attachments/lib/pdfProcessing.js +14 -2
  11. package/dist/modules/attachments/lib/pdfProcessing.js.map +2 -2
  12. package/dist/modules/attachments/lib/scoped-upload-service.js +4 -2
  13. package/dist/modules/attachments/lib/scoped-upload-service.js.map +2 -2
  14. package/dist/modules/attachments/lib/textExtraction.js +13 -1
  15. package/dist/modules/attachments/lib/textExtraction.js.map +2 -2
  16. package/dist/modules/catalog/search.js +3 -1
  17. package/dist/modules/catalog/search.js.map +2 -2
  18. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +2 -1
  19. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +2 -2
  20. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +10 -7
  21. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
  22. package/dist/modules/communication_channels/lib/oauth-result.js +12 -0
  23. package/dist/modules/communication_channels/lib/oauth-result.js.map +7 -0
  24. package/dist/modules/customers/components/detail/ActivitiesSection.js +8 -1
  25. package/dist/modules/customers/components/detail/ActivitiesSection.js.map +2 -2
  26. package/package.json +7 -7
  27. package/src/modules/attachments/api/route.ts +36 -3
  28. package/src/modules/attachments/lib/ocrLimits.ts +62 -0
  29. package/src/modules/attachments/lib/ocrQueue.ts +95 -2
  30. package/src/modules/attachments/lib/ocrService.ts +4 -0
  31. package/src/modules/attachments/lib/pdfProcessing.ts +14 -2
  32. package/src/modules/attachments/lib/scoped-upload-service.ts +4 -2
  33. package/src/modules/attachments/lib/textExtraction.ts +14 -1
  34. package/src/modules/catalog/search.ts +5 -1
  35. package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +2 -1
  36. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +12 -9
  37. package/src/modules/communication_channels/i18n/de.json +0 -1
  38. package/src/modules/communication_channels/i18n/en.json +0 -1
  39. package/src/modules/communication_channels/i18n/es.json +0 -1
  40. package/src/modules/communication_channels/i18n/ko.json +0 -1
  41. package/src/modules/communication_channels/i18n/pl.json +0 -1
  42. package/src/modules/communication_channels/lib/oauth-result.ts +13 -0
  43. package/src/modules/customers/components/detail/ActivitiesSection.tsx +8 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../../src/modules/communication_channels/api/get/oauth/%5Bprovider%5D/callback/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getAppBaseUrl, toAbsoluteUrl } from '@open-mercato/shared/lib/url'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createConnectedChannelRow, MailboxAlreadyConnectedError } from '../../../../../lib/connect-channel'\nimport { getChannelAdapter } from '../../../../../lib/adapter-registry-singleton'\nimport { resolveOAuthClientCredentials } from '../../../../../lib/oauth-client-config'\nimport {\n COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n consumeOAuthStateOnce,\n DEFAULT_OAUTH_RETURN_URL,\n normalizeOAuthReturnUrl,\n OAuthStateError,\n verifyOAuthState,\n type OAuthStateConsumeStore,\n} from '../../../../../lib/oauth-state'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'oauth-callback' })\n\nexport const metadata = {\n path: '/communication_channels/oauth/[provider]/callback',\n // No auth feature gate \u2014 the state cookie carries identity. The route still\n // verifies the session below to bind the callback to its initiator.\n GET: { requireAuth: true },\n}\n\ntype RouteContext = {\n params: Promise<{ provider: string }> | { provider: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nfunction redirectWithFlash(\n req: Request,\n returnUrl: string,\n flash: { type: 'connected' | 'error'; code?: string; provider?: string; channelId?: string },\n): Response {\n const base = new URL(\n normalizeOAuthReturnUrl(returnUrl, DEFAULT_OAUTH_RETURN_URL),\n getAppBaseUrl(req),\n )\n base.searchParams.set('flash', flash.type)\n if (flash.code) base.searchParams.set('code', flash.code)\n if (flash.provider) base.searchParams.set('provider', flash.provider)\n if (flash.channelId) base.searchParams.set('channelId', flash.channelId)\n const response = NextResponse.redirect(base.toString(), 302)\n response.cookies.set({\n name: COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n value: '',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge: 0,\n })\n return response\n}\n\nexport async function GET(req: Request, context: RouteContext): Promise<Response> {\n const { provider } = await context.params\n const url = new URL(req.url)\n const code = url.searchParams.get('code') ?? ''\n const stateParam = url.searchParams.get('state') ?? ''\n const error = url.searchParams.get('error')\n\n if (error) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, { type: 'error', code: error, provider })\n }\n if (!code || !stateParam) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'missing_code_or_state',\n provider,\n })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'unauthorized',\n provider,\n })\n }\n\n const adapter = getChannelAdapter(provider)\n if (!adapter || typeof adapter.exchangeOAuthCode !== 'function') {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'unknown_provider',\n provider,\n })\n }\n\n const cookieValue = req.headers.get('cookie') ?? ''\n const stateCookie = parseCookie(cookieValue, COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME)\n\n let statePayload\n try {\n statePayload = verifyOAuthState({\n cookie: stateCookie,\n expectedUserId: auth.sub as string,\n expectedProviderKey: provider,\n expectedState: stateParam,\n })\n } catch (err) {\n const errCode = err instanceof OAuthStateError ? err.code : 'invalid_state'\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: errCode,\n provider,\n })\n }\n\n // Defense-in-depth: the signed state is minted for a specific tenant at\n // initiate time and `verifyOAuthState` already binds it to `auth.sub`. Assert\n // the session tenant matches too, so a token/session anomaly can never create\n // a channel under a different tenant than the one that started the flow.\n if (statePayload.tenantId !== auth.tenantId) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'tenant_mismatch',\n provider,\n })\n }\n\n const returnUrl = normalizeOAuthReturnUrl(statePayload.returnUrl, DEFAULT_OAUTH_RETURN_URL)\n\n // Exchange the code via the adapter.\n const container = await createRequestContainer()\n\n // Single-use consume: reject a captured valid cookie replayed within the TTL.\n const resolved = (() => { try { return container.resolve('cache') } catch { return null } })()\n if (\n !resolved ||\n typeof (resolved as OAuthStateConsumeStore).has !== 'function' ||\n typeof (resolved as OAuthStateConsumeStore).set !== 'function'\n ) {\n return redirectWithFlash(req, returnUrl, { type: 'error', code: 'state_store_unavailable', provider })\n }\n const oauthStateStore = resolved as OAuthStateConsumeStore\n try {\n await consumeOAuthStateOnce(oauthStateStore, statePayload)\n } catch (err) {\n const errCode = err instanceof OAuthStateError ? err.code : 'invalid_state'\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: errCode,\n provider,\n })\n }\n const credentialsService = (() => {\n try {\n return container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n return null\n }\n })()\n // Resolve the tenant's OAuth client app config from the `channel_<provider>`\n // integration (userId = null). Same source the `initiate` route uses; a\n // missing row means the provider was never configured, so bounce back with an\n // actionable code rather than attempting an exchange with empty credentials.\n const oauthClientCredentials = await resolveOAuthClientCredentials(credentialsService, provider, {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? null,\n })\n if (!oauthClientCredentials) {\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'oauth_client_not_configured',\n provider,\n })\n }\n\n // Must byte-for-byte match the redirect_uri sent at authorize time (the\n // `initiate` route), including behind a reverse proxy \u2014 derive it from the\n // configured app origin rather than the raw request URL.\n const redirectUri = toAbsoluteUrl(req, `/api/communication_channels/oauth/${provider}/callback`)\n\n let exchange\n try {\n exchange = await adapter.exchangeOAuthCode({\n code,\n redirectUri,\n credentials: oauthClientCredentials,\n scope: {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? statePayload.tenantId,\n },\n stateExtra: statePayload.extra,\n })\n } catch (err) {\n logger.warn(\n 'code exchange failed for provider',\n { provider, err },\n )\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'exchange_failed',\n provider,\n })\n }\n\n // Persist the encrypted credentials under a per-user `integration_credentials`\n // row, then create / update the per-user `CommunicationChannel`.\n const em = (container.resolve('em') as EntityManager).fork()\n // Per-user scope: pass `userId` so the credentials service writes to a\n // user-scoped row instead of overwriting the tenant-wide row. Without this,\n // two users on the same tenant share one credentials row (see review R2-C1\n // / N1, 2026-05-26).\n const credentialsScope = {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? statePayload.tenantId,\n userId: auth.sub as string,\n }\n let credentialsRefId: string | null = null\n let credentialsPersisted = false\n if (credentialsService?.save) {\n try {\n // Save under a per-provider integration id namespace; per-user scoping is\n // recorded on `IntegrationCredentials.user_id` via the `scope.userId`.\n // Arg order MUST be (integrationId, credentials, scope) \u2014 matches the real\n // CredentialsService signature; the legacy reversed order corrupted the\n // saved row by writing the scope object into the credentials field.\n await credentialsService.save(\n `channel_${provider}`,\n {\n ...exchange.credentials,\n userId: auth.sub,\n expiresAt: exchange.expiresAt ? exchange.expiresAt.toISOString() : undefined,\n },\n credentialsScope,\n )\n credentialsPersisted = true\n } catch (err) {\n logger.warn(\n 'persisting credentials failed for provider',\n { provider, err },\n )\n }\n }\n // Resolve the saved row's id so we can link `channel.credentialsRef` to it.\n // `credentialsService.save` is `void`-returning by contract, so we re-find the\n // row immediately afterwards. Best-effort \u2014 null is acceptable; the channel\n // creation below will downgrade to `requires_reauth` so workers don't poll\n // a credential-less channel.\n if (credentialsPersisted) {\n try {\n const { IntegrationCredentials } = await import('@open-mercato/core/modules/integrations/data/entities')\n const { findOneWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n {\n integrationId: `channel_${provider}`,\n tenantId: credentialsScope.tenantId,\n organizationId: credentialsScope.organizationId,\n userId: credentialsScope.userId,\n deletedAt: null,\n },\n undefined,\n credentialsScope,\n )\n credentialsRefId = (row as { id?: string } | null)?.id ?? null\n } catch {\n credentialsRefId = null\n }\n }\n\n const displayName =\n exchange.displayName ?? exchange.externalIdentifier ?? `${provider} channel`\n // Fail-safe: if credentials persistence failed (no `credentialsRef` available),\n // create the channel in `requires_reauth` so workers don't poll a channel that\n // has no usable credentials. The user can re-run the OAuth flow to recover\n // (see review R2-H4 / F6, 2026-05-26).\n const credentialsAvailable = credentialsRefId !== null\n let channel\n try {\n channel = await createConnectedChannelRow({\n em,\n adapter,\n providerKey: provider,\n displayName,\n externalIdentifier: exchange.externalIdentifier ?? null,\n credentialsRefId,\n userId: auth.sub as string,\n scope: { tenantId: statePayload.tenantId, organizationId: statePayload.organizationId ?? null },\n })\n } catch (err) {\n // Same mailbox already connected via another provider \u2014 don't create a second\n // channel that double-ingests every message; send the user back with a flash.\n if (err instanceof MailboxAlreadyConnectedError) {\n logger.warn('mailbox already connected via another provider', { existingProviderKey: err.existingProviderKey })\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'mailbox_already_connected',\n provider,\n })\n }\n throw err\n }\n\n // Spec C \u00A7 Phase C5 \u2014 best-effort push registration for OAuth providers\n // that support it (Gmail). Same shape as the credential-connect\n // path: failures persist as `pushStatus='failed'` on channelState and DO\n // NOT fail the connect \u2014 polling fallback covers until the operator clicks\n // \"Re-register push\" on the channels page.\n const adapterSupportsPush =\n typeof adapter.registerPush === 'function' && typeof adapter.unregisterPush === 'function'\n if (\n credentialsAvailable &&\n adapterSupportsPush &&\n statePayload.organizationId &&\n provider === 'gmail'\n ) {\n try {\n const { pushRegister } = await import('../../../../../commands/push-register')\n await pushRegister({\n container,\n scope: {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId,\n userId: auth.sub as string,\n },\n input: { channelId: channel.id },\n })\n } catch (err) {\n logger.warn(\n 'best-effort pushRegister failed for channel',\n { channelId: channel.id, err },\n )\n }\n }\n\n return redirectWithFlash(req, returnUrl, {\n type: 'connected',\n provider,\n channelId: channel.id,\n })\n}\n\nfunction parseCookie(header: string, name: string): string | null {\n if (!header) return null\n const segments = header.split(';')\n for (const segment of segments) {\n const trimmed = segment.trim()\n if (trimmed.startsWith(`${name}=`)) {\n return decodeURIComponent(trimmed.slice(name.length + 1))\n }\n }\n return null\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'OAuth callback \u2014 exchange code, persist credentials, create per-user channel',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 302, description: 'Redirect back to returnUrl with flash query params' },\n ],\n },\n },\n}\nexport default GET\n"],
5
- "mappings": "AAAA,SAA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AAAA,EACrB,CAAC;AACH;AAEA,SAAS,YAAY,QAAgB,MAA6B;AAChE,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,WAAW,OAAO,MAAM,GAAG;AACjC,aAAW,WAAW,UAAU;AAC9B,UAAM,UAAU,QAAQ,KAAK;AAC7B,QAAI,QAAQ,WAAW,GAAG,IAAI,GAAG,GAAG;AAClC,aAAO,mBAAmB,QAAQ,MAAM,KAAK,SAAS,CAAC,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,SAAO;AACT;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,qDAAqD;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { getAppBaseUrl, toAbsoluteUrl } from '@open-mercato/shared/lib/url'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { createConnectedChannelRow, MailboxAlreadyConnectedError } from '../../../../../lib/connect-channel'\nimport { getChannelAdapter } from '../../../../../lib/adapter-registry-singleton'\nimport { resolveOAuthClientCredentials } from '../../../../../lib/oauth-client-config'\nimport {\n COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n consumeOAuthStateOnce,\n DEFAULT_OAUTH_RETURN_URL,\n normalizeOAuthReturnUrl,\n OAuthStateError,\n verifyOAuthState,\n type OAuthStateConsumeStore,\n} from '../../../../../lib/oauth-state'\nimport { OAUTH_RESULT_QUERY_PARAM } from '../../../../../lib/oauth-result'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('communication_channels').child({ component: 'oauth-callback' })\n\nexport const metadata = {\n path: '/communication_channels/oauth/[provider]/callback',\n // No auth feature gate \u2014 the state cookie carries identity. The route still\n // verifies the session below to bind the callback to its initiator.\n GET: { requireAuth: true },\n}\n\ntype RouteContext = {\n params: Promise<{ provider: string }> | { provider: string }\n}\n\ntype CredentialsServiceLike = {\n resolve: (\n integrationId: string,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<Record<string, unknown> | null>\n save?: (\n integrationId: string,\n credentials: Record<string, unknown>,\n scope: { organizationId: string; tenantId: string; userId?: string | null },\n ) => Promise<void>\n}\n\nfunction redirectWithFlash(\n req: Request,\n returnUrl: string,\n flash: { type: 'connected' | 'error'; code?: string; provider?: string; channelId?: string },\n): Response {\n const base = new URL(\n normalizeOAuthReturnUrl(returnUrl, DEFAULT_OAUTH_RETURN_URL),\n getAppBaseUrl(req),\n )\n base.searchParams.set(OAUTH_RESULT_QUERY_PARAM, flash.type)\n if (flash.code) base.searchParams.set('code', flash.code)\n if (flash.provider) base.searchParams.set('provider', flash.provider)\n if (flash.channelId) base.searchParams.set('channelId', flash.channelId)\n const response = NextResponse.redirect(base.toString(), 302)\n response.cookies.set({\n name: COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME,\n value: '',\n httpOnly: true,\n secure: process.env.NODE_ENV === 'production',\n sameSite: 'lax',\n path: '/',\n maxAge: 0,\n })\n return response\n}\n\nexport async function GET(req: Request, context: RouteContext): Promise<Response> {\n const { provider } = await context.params\n const url = new URL(req.url)\n const code = url.searchParams.get('code') ?? ''\n const stateParam = url.searchParams.get('state') ?? ''\n const error = url.searchParams.get('error')\n\n if (error) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, { type: 'error', code: error, provider })\n }\n if (!code || !stateParam) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'missing_code_or_state',\n provider,\n })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'unauthorized',\n provider,\n })\n }\n\n const adapter = getChannelAdapter(provider)\n if (!adapter || typeof adapter.exchangeOAuthCode !== 'function') {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'unknown_provider',\n provider,\n })\n }\n\n const cookieValue = req.headers.get('cookie') ?? ''\n const stateCookie = parseCookie(cookieValue, COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME)\n\n let statePayload\n try {\n statePayload = verifyOAuthState({\n cookie: stateCookie,\n expectedUserId: auth.sub as string,\n expectedProviderKey: provider,\n expectedState: stateParam,\n })\n } catch (err) {\n const errCode = err instanceof OAuthStateError ? err.code : 'invalid_state'\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: errCode,\n provider,\n })\n }\n\n // Defense-in-depth: the signed state is minted for a specific tenant at\n // initiate time and `verifyOAuthState` already binds it to `auth.sub`. Assert\n // the session tenant matches too, so a token/session anomaly can never create\n // a channel under a different tenant than the one that started the flow.\n if (statePayload.tenantId !== auth.tenantId) {\n return redirectWithFlash(req, DEFAULT_OAUTH_RETURN_URL, {\n type: 'error',\n code: 'tenant_mismatch',\n provider,\n })\n }\n\n const returnUrl = normalizeOAuthReturnUrl(statePayload.returnUrl, DEFAULT_OAUTH_RETURN_URL)\n\n // Exchange the code via the adapter.\n const container = await createRequestContainer()\n\n // Single-use consume: reject a captured valid cookie replayed within the TTL.\n const resolved = (() => { try { return container.resolve('cache') } catch { return null } })()\n if (\n !resolved ||\n typeof (resolved as OAuthStateConsumeStore).has !== 'function' ||\n typeof (resolved as OAuthStateConsumeStore).set !== 'function'\n ) {\n return redirectWithFlash(req, returnUrl, { type: 'error', code: 'state_store_unavailable', provider })\n }\n const oauthStateStore = resolved as OAuthStateConsumeStore\n try {\n await consumeOAuthStateOnce(oauthStateStore, statePayload)\n } catch (err) {\n const errCode = err instanceof OAuthStateError ? err.code : 'invalid_state'\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: errCode,\n provider,\n })\n }\n const credentialsService = (() => {\n try {\n return container.resolve('integrationCredentialsService') as CredentialsServiceLike\n } catch {\n return null\n }\n })()\n // Resolve the tenant's OAuth client app config from the `channel_<provider>`\n // integration (userId = null). Same source the `initiate` route uses; a\n // missing row means the provider was never configured, so bounce back with an\n // actionable code rather than attempting an exchange with empty credentials.\n const oauthClientCredentials = await resolveOAuthClientCredentials(credentialsService, provider, {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? null,\n })\n if (!oauthClientCredentials) {\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'oauth_client_not_configured',\n provider,\n })\n }\n\n // Must byte-for-byte match the redirect_uri sent at authorize time (the\n // `initiate` route), including behind a reverse proxy \u2014 derive it from the\n // configured app origin rather than the raw request URL.\n const redirectUri = toAbsoluteUrl(req, `/api/communication_channels/oauth/${provider}/callback`)\n\n let exchange\n try {\n exchange = await adapter.exchangeOAuthCode({\n code,\n redirectUri,\n credentials: oauthClientCredentials,\n scope: {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? statePayload.tenantId,\n },\n stateExtra: statePayload.extra,\n })\n } catch (err) {\n logger.warn(\n 'code exchange failed for provider',\n { provider, err },\n )\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'exchange_failed',\n provider,\n })\n }\n\n // Persist the encrypted credentials under a per-user `integration_credentials`\n // row, then create / update the per-user `CommunicationChannel`.\n const em = (container.resolve('em') as EntityManager).fork()\n // Per-user scope: pass `userId` so the credentials service writes to a\n // user-scoped row instead of overwriting the tenant-wide row. Without this,\n // two users on the same tenant share one credentials row (see review R2-C1\n // / N1, 2026-05-26).\n const credentialsScope = {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId ?? statePayload.tenantId,\n userId: auth.sub as string,\n }\n let credentialsRefId: string | null = null\n let credentialsPersisted = false\n if (credentialsService?.save) {\n try {\n // Save under a per-provider integration id namespace; per-user scoping is\n // recorded on `IntegrationCredentials.user_id` via the `scope.userId`.\n // Arg order MUST be (integrationId, credentials, scope) \u2014 matches the real\n // CredentialsService signature; the legacy reversed order corrupted the\n // saved row by writing the scope object into the credentials field.\n await credentialsService.save(\n `channel_${provider}`,\n {\n ...exchange.credentials,\n userId: auth.sub,\n expiresAt: exchange.expiresAt ? exchange.expiresAt.toISOString() : undefined,\n },\n credentialsScope,\n )\n credentialsPersisted = true\n } catch (err) {\n logger.warn(\n 'persisting credentials failed for provider',\n { provider, err },\n )\n }\n }\n // Resolve the saved row's id so we can link `channel.credentialsRef` to it.\n // `credentialsService.save` is `void`-returning by contract, so we re-find the\n // row immediately afterwards. Best-effort \u2014 null is acceptable; the channel\n // creation below will downgrade to `requires_reauth` so workers don't poll\n // a credential-less channel.\n if (credentialsPersisted) {\n try {\n const { IntegrationCredentials } = await import('@open-mercato/core/modules/integrations/data/entities')\n const { findOneWithDecryption } = await import('@open-mercato/shared/lib/encryption/find')\n const row = await findOneWithDecryption(\n em,\n IntegrationCredentials,\n {\n integrationId: `channel_${provider}`,\n tenantId: credentialsScope.tenantId,\n organizationId: credentialsScope.organizationId,\n userId: credentialsScope.userId,\n deletedAt: null,\n },\n undefined,\n credentialsScope,\n )\n credentialsRefId = (row as { id?: string } | null)?.id ?? null\n } catch {\n credentialsRefId = null\n }\n }\n\n const displayName =\n exchange.displayName ?? exchange.externalIdentifier ?? `${provider} channel`\n // Fail-safe: if credentials persistence failed (no `credentialsRef` available),\n // create the channel in `requires_reauth` so workers don't poll a channel that\n // has no usable credentials. The user can re-run the OAuth flow to recover\n // (see review R2-H4 / F6, 2026-05-26).\n const credentialsAvailable = credentialsRefId !== null\n let channel\n try {\n channel = await createConnectedChannelRow({\n em,\n adapter,\n providerKey: provider,\n displayName,\n externalIdentifier: exchange.externalIdentifier ?? null,\n credentialsRefId,\n userId: auth.sub as string,\n scope: { tenantId: statePayload.tenantId, organizationId: statePayload.organizationId ?? null },\n })\n } catch (err) {\n // Same mailbox already connected via another provider \u2014 don't create a second\n // channel that double-ingests every message; send the user back with a flash.\n if (err instanceof MailboxAlreadyConnectedError) {\n logger.warn('mailbox already connected via another provider', { existingProviderKey: err.existingProviderKey })\n return redirectWithFlash(req, returnUrl, {\n type: 'error',\n code: 'mailbox_already_connected',\n provider,\n })\n }\n throw err\n }\n\n // Spec C \u00A7 Phase C5 \u2014 best-effort push registration for OAuth providers\n // that support it (Gmail). Same shape as the credential-connect\n // path: failures persist as `pushStatus='failed'` on channelState and DO\n // NOT fail the connect \u2014 polling fallback covers until the operator clicks\n // \"Re-register push\" on the channels page.\n const adapterSupportsPush =\n typeof adapter.registerPush === 'function' && typeof adapter.unregisterPush === 'function'\n if (\n credentialsAvailable &&\n adapterSupportsPush &&\n statePayload.organizationId &&\n provider === 'gmail'\n ) {\n try {\n const { pushRegister } = await import('../../../../../commands/push-register')\n await pushRegister({\n container,\n scope: {\n tenantId: statePayload.tenantId,\n organizationId: statePayload.organizationId,\n userId: auth.sub as string,\n },\n input: { channelId: channel.id },\n })\n } catch (err) {\n logger.warn(\n 'best-effort pushRegister failed for channel',\n { channelId: channel.id, err },\n )\n }\n }\n\n return redirectWithFlash(req, returnUrl, {\n type: 'connected',\n provider,\n channelId: channel.id,\n })\n}\n\nfunction parseCookie(header: string, name: string): string | null {\n if (!header) return null\n const segments = header.split(';')\n for (const segment of segments) {\n const trimmed = segment.trim()\n if (trimmed.startsWith(`${name}=`)) {\n return decodeURIComponent(trimmed.slice(name.length + 1))\n }\n }\n return null\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'OAuth callback \u2014 exchange code, persist credentials, create per-user channel',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 302, description: 'Redirect back to returnUrl with flash query params' },\n ],\n },\n },\n}\nexport default GET\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SA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;AACH;AAEA,SAAS,YAAY,QAAgB,MAA6B;AAChE,MAAI,CAAC,OAAQ,QAAO;AACpB,QAAM,WAAW,OAAO,MAAM,GAAG;AACjC,aAAW,WAAW,UAAU;AAC9B,UAAM,UAAU,QAAQ,KAAK;AAC7B,QAAI,QAAQ,WAAW,GAAG,IAAI,GAAG,GAAG;AAClC,aAAO,mBAAmB,QAAQ,MAAM,KAAK,SAAS,CAAC,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,SAAO;AACT;AAEO,MAAM,UAAU;AAAA,EACrB,MAAM,CAAC,uBAAuB;AAAA,EAC9B,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,MAAM,CAAC,uBAAuB;AAAA,MAC9B,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,qDAAqD;AAAA,MACnF;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -3,6 +3,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
3
3
  import * as React from "react";
4
4
  import { extensionPoints } from "@open-mercato/core/modules/communication_channels/extension-points";
5
5
  import { getImportHistoryLimits } from "@open-mercato/core/modules/communication_channels/lib/import-history-limits";
6
+ import { OAUTH_RESULT_QUERY_PARAM, stripOAuthResultParams } from "@open-mercato/core/modules/communication_channels/lib/oauth-result";
6
7
  import { useRouter, useSearchParams } from "next/navigation";
7
8
  import { Page, PageBody } from "@open-mercato/ui/backend/Page";
8
9
  import { DataTable } from "@open-mercato/ui/backend/DataTable";
@@ -37,7 +38,7 @@ function ProfileCommunicationChannelsPage() {
37
38
  const t = useT();
38
39
  const router = useRouter();
39
40
  const searchParams = useSearchParams();
40
- const flashType = searchParams?.get("flash");
41
+ const flashType = searchParams?.get(OAUTH_RESULT_QUERY_PARAM);
41
42
  const flashCode = searchParams?.get("code");
42
43
  const flashProvider = searchParams?.get("provider");
43
44
  const [rows, setRows] = React.useState([]);
@@ -53,9 +54,10 @@ function ProfileCommunicationChannelsPage() {
53
54
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
54
55
  React.useEffect(() => {
55
56
  if (flashType === "connected") {
57
+ const providerLabel = flashProvider ? t(`communication_channels.channel.providers.${flashProvider}`, "") : "";
56
58
  flash(
57
- flashProvider ? t("communication_channels.profile.flash.connectedWithProvider", "Channel connected ({provider}).", {
58
- provider: flashProvider
59
+ providerLabel ? t("communication_channels.profile.flash.connectedWithProvider", "Channel connected ({provider}).", {
60
+ provider: providerLabel
59
61
  }) : t("communication_channels.profile.flash.connected", "Channel connected."),
60
62
  "success"
61
63
  );
@@ -73,13 +75,14 @@ function ProfileCommunicationChannelsPage() {
73
75
  ) : flashCode === "state_store_unavailable" ? t(
74
76
  "communication_channels.profile.flash.stateStoreUnavailable",
75
77
  "A server error prevented completing the connection. Please try again in a moment."
76
- ) : flashCode ? t("communication_channels.profile.flash.errorWithCode", "Failed to connect channel \u2014 {code}.", {
77
- code: flashCode
78
- }) : t("communication_channels.profile.flash.error", "Failed to connect channel."),
78
+ ) : t("communication_channels.profile.flash.error", "Failed to connect channel."),
79
79
  "error"
80
80
  );
81
+ } else {
82
+ return;
81
83
  }
82
- }, [flashType, flashCode, flashProvider, t]);
84
+ router.replace(stripOAuthResultParams(window.location.href), { scroll: false });
85
+ }, [flashType, flashCode, flashProvider, router, t]);
83
86
  React.useEffect(() => {
84
87
  let cancelled = false;
85
88
  async function load() {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/communication_channels/backend/profile/communication-channels/page.tsx"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { extensionPoints } from '@open-mercato/core/modules/communication_channels/extension-points'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport type { LegacyColumnDef as ColumnDef } from '@tanstack/react-table/legacy'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { DataTable } from '@open-mercato/ui/backend/DataTable'\nimport { Tag } from '@open-mercato/ui/primitives/tag'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { KbdShortcut } from '@open-mercato/ui/primitives/kbd'\nimport { RowActions, type RowActionItem } from '@open-mercato/ui/backend/RowActions'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { ConnectChannelMenu } from './ConnectChannelMenu'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\n /** `shared` = a team mailbox: teammates can read the CRM email it ingests. */\n visibility: 'private' | 'shared'\n /** Version token for the share toggle's optimistic-lock header. */\n updatedAt: string | null\n isActive: boolean\n status: 'connected' | 'requires_reauth' | 'error' | 'disconnected'\n lastError: string | null\n pollIntervalSeconds: number | null\n lastPolledAt: string | null\n /** Spec C \u2014 push delivery state (null when provider doesn't support push). */\n pushStatus: 'active' | 'inactive' | 'failed' | null\n lastPushError: { code: string | null; message: string | null; at: string | null } | null\n /**\n * `true` when the adapter declares real-time push, so the hub's poll worker\n * skips this channel entirely \u2014 inbound arrives over the provider connection.\n */\n supportsRealtimePush: boolean\n /** `true` when the adapter implements `registerPush` (Gmail-style subscriptions). */\n supportsPushRegistration: boolean\n createdAt: string | null\n}\n\nconst PROFILE_CHANNELS_MUTATION_CONTEXT_ID = 'communication-channels-profile'\nconst IMPORT_HISTORY_MUTATION_CONTEXT_ID = 'communication-channels-import-history'\nconst DISCONNECT_MUTATION_CONTEXT_ID = 'communication-channels-disconnect'\n\ntype ChannelMutationContext = {\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport default function ProfileCommunicationChannelsPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const flashType = searchParams?.get('flash')\n const flashCode = searchParams?.get('code')\n const flashProvider = searchParams?.get('provider')\n\n const [rows, setRows] = React.useState<ChannelRow[]>([])\n const [isLoading, setIsLoading] = React.useState(true)\n const [errorMessage, setErrorMessage] = React.useState<string | null>(null)\n const [reloadKey, setReloadKey] = React.useState(0)\n const [importChannel, setImportChannel] = React.useState<ChannelRow | null>(null)\n const [disconnectChannel, setDisconnectChannel] = React.useState<ChannelRow | null>(null)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n // Sharing a mailbox is privacy-consequential, so the widening direction is\n // confirmed. Escape cancels and Cmd/Ctrl+Enter submits (ConfirmDialog owns both).\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n React.useEffect(() => {\n if (flashType === 'connected') {\n flash(\n flashProvider\n ? t('communication_channels.profile.flash.connectedWithProvider', 'Channel connected ({provider}).', {\n provider: flashProvider,\n })\n : t('communication_channels.profile.flash.connected', 'Channel connected.'),\n 'success',\n )\n } else if (flashType === 'error') {\n flash(\n flashCode === 'oauth_client_not_configured'\n ? t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n )\n : flashCode === 'mailbox_already_connected'\n ? t(\n 'communication_channels.profile.connect.mailboxAlreadyConnected',\n 'This mailbox is already connected through another provider. Disconnect it first to reconnect it with a different one.',\n )\n : flashCode === 'replay'\n ? t(\n 'communication_channels.profile.flash.replayedState',\n 'This connection link was already used \u2014 please start the connection again.',\n )\n : flashCode === 'state_store_unavailable'\n ? t(\n 'communication_channels.profile.flash.stateStoreUnavailable',\n 'A server error prevented completing the connection. Please try again in a moment.',\n )\n : flashCode\n ? t('communication_channels.profile.flash.errorWithCode', 'Failed to connect channel \u2014 {code}.', {\n code: flashCode,\n })\n : t('communication_channels.profile.flash.error', 'Failed to connect channel.'),\n 'error',\n )\n }\n }, [flashType, flashCode, flashProvider, t])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setIsLoading(true)\n setErrorMessage(null)\n const response = await apiCall<{ items?: ChannelRow[] }>(\n '/api/communication_channels/me/channels',\n ).catch((err: unknown) => ({\n ok: false,\n result: { error: err instanceof Error ? err.message : 'Failed to load channels' },\n }))\n if (cancelled) return\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n setErrorMessage(\n body?.error ?? t('communication_channels.errors.loadList', 'Failed to load channels'),\n )\n setRows([])\n } else {\n const data = (response.result ?? {}) as { items?: ChannelRow[] }\n setRows(Array.isArray(data.items) ? data.items : [])\n }\n setIsLoading(false)\n }\n void load()\n return () => {\n cancelled = true\n }\n }, [reloadKey, t])\n\n const reauthRows = rows.filter((r) => r.status === 'requires_reauth')\n\n const reloadChannels = React.useCallback(() => setReloadKey((k) => k + 1), [])\n\n const onSetVisibility = React.useCallback(\n async (channel: ChannelRow, nextShared: boolean) => {\n // Only the widening direction needs a confirmation; making a mailbox\n // private again is the safe direction and stays one click.\n if (nextShared) {\n const confirmed = await confirm({\n title: t(\n 'communication_channels.profile.share.confirm.title',\n 'Share this mailbox with your team?',\n ),\n text: t(\n 'communication_channels.profile.share.confirm.text',\n 'Colleagues will be able to read the CRM email this mailbox handles, including messages already received. You stay the only person who can manage the connection, and you can stop sharing at any time.',\n ),\n confirmText: t('communication_channels.profile.share.confirm.cta', 'Share with team'),\n })\n if (!confirmed) return\n }\n\n const nextVisibility = nextShared ? 'shared' : 'private'\n let response\n try {\n response = await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(channel.updatedAt),\n () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/visibility`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visibility: nextVisibility }),\n },\n ),\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { visibility: nextVisibility },\n })\n } catch (err) {\n if (surfaceRecordConflict(err, t)) return\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n if (!response.ok) {\n if (surfaceRecordConflict(\n { status: response.status, body: response.result },\n t,\n { onRefresh: () => setReloadKey((k) => k + 1) },\n )) return\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n flash(\n nextShared\n ? t('communication_channels.profile.share.sharedSuccess', 'Mailbox shared with your team.')\n : t('communication_channels.profile.share.privateSuccess', 'Mailbox is private again.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [runMutation, retryLastMutation, confirm, t],\n )\n\n const onSetPrimary = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/set-primary`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { isPrimary: true },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'),\n 'error',\n )\n return\n }\n flash(\n t('communication_channels.profile.actions.setPrimarySuccess', 'Marked as primary.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onRegisterPush = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ pushStatus?: string; error?: { code: string; message: string } }>(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/push/register`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'push-register' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.push.button.reregister', 'Re-register push'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(body?.error ?? t('communication_channels.push.flash.registerFailed', 'Failed to register push'), 'error')\n return\n }\n const result = (response.result ?? {}) as { pushStatus?: string }\n if (result.pushStatus === 'active') {\n flash(t('communication_channels.push.status.active', 'Push active'), 'success')\n } else {\n flash(\n t(\n 'communication_channels.push.status.failed',\n 'Push registration returned a non-active status \u2014 falling back to polling.',\n ),\n 'error',\n )\n }\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onPollNow = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'poll-now' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.pollNowSuccess',\n 'Poll triggered \u2014 new messages will appear on linked Person timelines in a few seconds.',\n ),\n 'success',\n )\n // Give the worker a moment to fetch + ingest, then refetch our channel list\n // so `lastPolledAt` updates in the UI.\n setTimeout(() => setReloadKey((k) => k + 1), 1500)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const columns = React.useMemo<ColumnDef<ChannelRow>[]>(\n () => [\n {\n header: t('communication_channels.columns.displayName', 'Channel'),\n accessorKey: 'displayName',\n },\n {\n header: t('communication_channels.columns.provider', 'Provider'),\n accessorKey: 'providerKey',\n cell: ({ row }) => (\n <Tag variant=\"info\">\n {t(\n `communication_channels.channel.providers.${row.original.providerKey}`,\n row.original.providerKey,\n )}\n </Tag>\n ),\n },\n {\n header: t('communication_channels.columns.identifier', 'Email / username'),\n accessorKey: 'externalIdentifier',\n cell: ({ row }) => row.original.externalIdentifier ?? '\u2014',\n meta: { truncate: true, maxWidth: 240 },\n },\n {\n header: t('communication_channels.profile.columns.primary', 'Primary'),\n accessorKey: 'isPrimary',\n // Status only \u2014 \"Set as primary\" lives in the row actions menu.\n cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n header: t('communication_channels.profile.columns.sharing', 'Team access'),\n accessorKey: 'visibility',\n // Status only \u2014 the share/unshare flip lives in the row actions menu.\n //\n // Only email ingestion writes customer_interactions, so on an SMS or push\n // channel a share would flip the flag and flash success while changing\n // nothing anyone can observe. The menu applies the same email-only rule.\n cell: ({ row }) =>\n row.original.channelType !== 'email' ? (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ) : row.original.visibility === 'shared' ? (\n <Tag variant=\"info\" dot>\n {t('communication_channels.profile.share.shared', 'Shared')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.profile.share.private', 'Only you')}\n </span>\n ),\n },\n {\n header: t('communication_channels.columns.status', 'Status'),\n accessorKey: 'status',\n cell: ({ row }) => statusTag(row.original.status, t),\n },\n {\n id: 'pushStatus',\n // Its own key: sharing `push.status.active` made the header render\n // \"Push active\" over a column whose rows say \"Polling only\" (#4980).\n header: t('communication_channels.profile.columns.push', 'Push'),\n cell: ({ row }) => {\n const ps = row.original.pushStatus\n const errorTitle = row.original.lastPushError?.message ?? undefined\n // Derived from the adapter's declared capabilities, never from the\n // provider name: `supportsPushRegistration` means push subscriptions\n // can be (re-)registered from here, `supportsRealtimePush` means the\n // hub's poll worker skips the channel because the provider connection\n // delivers inbound itself (#4980).\n if (!row.original.supportsPushRegistration) {\n if (!row.original.supportsRealtimePush) {\n return (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.pushDrivenFailed', 'Push connection failed')}\n </Tag>\n )\n }\n // The \"why is there no Poll now action?\" explanation used to live on\n // the disabled Sync button's aria-label. That button is gone, so the\n // reason moves here rather than being lost.\n return (\n <Tag\n variant=\"success\"\n dot\n title={t(\n 'communication_channels.profile.actions.pollNowPushDriven',\n 'This channel is push-driven \u2014 inbound messages arrive over the provider connection, so polling does not apply.',\n )}\n >\n {t('communication_channels.push.status.pushDriven', 'Push-driven')}\n </Tag>\n )\n }\n if (ps === 'active') {\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.push.status.active', 'Push active')}\n </Tag>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n )\n }\n // null or 'inactive' \u2014 the provider can register push but has not yet.\n // Only a hub-polled channel falls back to polling meanwhile; for a\n // push-driven one nothing is delivering inbound at all, so claiming\n // \"Polling only\" would repeat the defect this issue is about (#4980).\n return (\n <span className=\"text-xs text-muted-foreground\">\n {row.original.supportsRealtimePush\n ? t('communication_channels.push.status.notRegistered', 'Push not registered')\n : t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n },\n },\n {\n header: t('communication_channels.profile.columns.lastPolled', 'Last synced'),\n accessorKey: 'lastPolledAt',\n cell: ({ row }) =>\n row.original.lastPolledAt\n ? new Date(row.original.lastPolledAt).toLocaleString()\n : '\u2014',\n },\n ],\n [t],\n )\n\n /**\n * Every per-row action, in one menu. The table previously carried five action\n * columns, which pushed the row past the viewport and clipped the trailing\n * buttons.\n *\n * Passed as DataTable's `rowActions` rather than as a hand-rolled column so the\n * table can merge row actions injected by other modules into this same menu\n * (`extensionTableId` below) instead of rendering a second one, and so the\n * actions cell keeps the table's own header, alignment and sticky behaviour.\n *\n * `RowActionItem` has no disabled state, so an unavailable action is OMITTED\n * rather than greyed out. The reason stays visible in the row: the Status and\n * Push columns already say why a channel cannot be polled or needs reconnecting.\n */\n const rowActions = React.useCallback(\n (channel: ChannelRow) => {\n const items: RowActionItem[] = []\n\n if (!channel.isPrimary) {\n items.push({\n id: 'set-primary',\n label: t('communication_channels.profile.actions.setPrimary', 'Set as primary'),\n onSelect: () => { void onSetPrimary(channel.id) },\n })\n }\n\n // Email only, for the reason the Team access column documents: on a\n // non-email channel the flip would change nothing anyone can observe.\n if (channel.channelType === 'email') {\n items.push(\n channel.visibility === 'shared'\n ? {\n id: 'make-private',\n label: t('communication_channels.profile.share.makePrivate', 'Make private'),\n onSelect: () => { void onSetVisibility(channel, false) },\n }\n : {\n id: 'share-with-team',\n label: t('communication_channels.profile.share.shareCta', 'Share with team'),\n onSelect: () => { void onSetVisibility(channel, true) },\n },\n )\n }\n\n // Offered only when the adapter can register push AND it is not already\n // active \u2014 re-registering a healthy subscription is a no-op.\n if (channel.supportsPushRegistration && channel.pushStatus !== 'active') {\n items.push({\n id: 'register-push',\n label: t('communication_channels.push.button.reregister', 'Re-register push'),\n onSelect: () => { void onRegisterPush(channel.id) },\n })\n }\n\n // Same eligibility the History column enforced.\n if (channel.isActive && channel.status === 'connected' && channel.channelType === 'email') {\n items.push({\n id: 'import-history',\n label: t('communication_channels.profile.actions.importHistory', 'Import history'),\n onSelect: () => setImportChannel(channel),\n })\n }\n\n // Same eligibility the Sync column enforced: allowed from 'connected'\n // AND 'error' (so a stuck channel can be recovered without a\n // reconnect), never for a push-driven channel the worker skips (#4980).\n const pollable =\n channel.isActive &&\n !channel.supportsRealtimePush &&\n (channel.status === 'connected' || channel.status === 'error')\n if (pollable) {\n items.push({\n id: 'poll-now',\n label:\n channel.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now'),\n onSelect: () => { void onPollNow(channel.id) },\n })\n }\n\n items.push({\n id: 'disconnect',\n label: t('communication_channels.profile.actions.disconnect', 'Disconnect'),\n destructive: true,\n onSelect: () => setDisconnectChannel(channel),\n })\n\n return <RowActions items={items} />\n },\n [onSetPrimary, onSetVisibility, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4\">\n <div className=\"min-w-0\">\n <h1 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h1>\n <p className=\"text-sm text-muted-foreground\">\n {t(\n 'communication_channels.profile.subtitle',\n 'Connect your communication channels so outbound messages come from your own account and inbound messages land in your unified inbox.',\n )}\n </p>\n </div>\n {/* Provider connect entry points injected by each channel-* package\n (channel-gmail, channel-imap) via UMES. They stack inside one\n dropdown so the header does not widen per installed provider. */}\n <ConnectChannelMenu onConnected={reloadChannels} />\n </header>\n\n {reauthRows.length > 0 ? (\n <Alert status=\"warning\" className=\"mb-4\">\n <AlertDescription>\n {t(\n 'communication_channels.profile.alerts.requiresReauth',\n '{count} channel(s) need reconnection. Click \"Reconnect\" on the affected channel below.',\n { count: reauthRows.length },\n )}\n </AlertDescription>\n </Alert>\n ) : null}\n\n <DataTable<ChannelRow>\n title={t('communication_channels.profile.tableTitle', 'Your channels')}\n titleHeadingLevel={2}\n extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n rowActions={rowActions}\n // Pinned because this table is wider than a laptop viewport: at 1280px\n // the row runs out well before the actions cell, and since Primary,\n // Team access and Push are status-only there is no other control in\n // view. Unpinned, reaching \u22EF meant scrolling to the far end, which\n // scrolls the Channel column away \u2014 so you could no longer see which\n // channel the open menu belonged to (#6717).\n stickyActionsColumn\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Add one using the menu at the top of this page.',\n )}\n />\n <ImportHistoryDialog\n channel={importChannel}\n onClose={() => setImportChannel(null)}\n onQueued={() => {\n setImportChannel(null)\n router.refresh()\n }}\n />\n <DisconnectChannelDialog\n channel={disconnectChannel}\n onClose={() => setDisconnectChannel(null)}\n onDisconnected={() => {\n setDisconnectChannel(null)\n setReloadKey((k) => k + 1)\n }}\n />\n {ConfirmDialogElement}\n </PageBody>\n </Page>\n )\n}\n\ntype ImportHistoryDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onQueued: () => void\n}\n\nfunction ImportHistoryDialog({ channel, onClose, onQueued }: ImportHistoryDialogProps): React.JSX.Element {\n const t = useT()\n const importLimits = React.useMemo(() => getImportHistoryLimits(channel?.providerKey), [channel?.providerKey])\n const [sinceDays, setSinceDays] = React.useState('30')\n const [contactEmails, setContactEmails] = React.useState('')\n const [maxMessages, setMaxMessages] = React.useState('500')\n const [fieldErrors, setFieldErrors] = React.useState<Record<string, string>>({})\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) {\n setSinceDays('30')\n setContactEmails('')\n setMaxMessages('500')\n setFieldErrors({})\n setSubmitting(false)\n }\n }, [channel?.id])\n\n const handleSubmit = React.useCallback(async () => {\n if (!channel || submitting) return\n const sinceNum = Number.parseInt(sinceDays, 10)\n const maxNum = Number.parseInt(maxMessages, 10)\n const errors: Record<string, string> = {}\n if (!Number.isFinite(sinceNum) || sinceNum < 1 || sinceNum > importLimits.maxSinceDays) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and {max} days.',\n { max: importLimits.maxSinceDays },\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > importLimits.maxMessages) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and {max} messages.',\n { max: importLimits.maxMessages },\n )\n }\n const parsedEmails = contactEmails\n .split(/[\\s,;]+/)\n .map((s) => s.trim())\n .filter(Boolean)\n if (parsedEmails.length > 0 && parsedEmails.some((s) => !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s))) {\n errors.contactEmails = t(\n 'communication_channels.profile.importHistory.errors.contactEmails',\n 'One or more entries is not a valid email address.',\n )\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors)\n return\n }\n setFieldErrors({})\n setSubmitting(true)\n const mutationPayload = {\n sinceDays: sinceNum,\n maxMessages: maxNum,\n ...(parsedEmails.length > 0 ? { contactEmails: parsedEmails } : {}),\n }\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ progressJobId?: string }>(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/import-history`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(mutationPayload),\n },\n ),\n context: {\n formId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload,\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.importHistory.flash.error', 'Failed to queue history import.'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string; fieldErrors?: Record<string, string> } | undefined\n if (body?.fieldErrors && Object.keys(body.fieldErrors).length > 0) {\n setFieldErrors(body.fieldErrors)\n return\n }\n flash(\n body?.error ??\n t(\n 'communication_channels.profile.importHistory.flash.error',\n 'Failed to queue history import.',\n ),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.importHistory.flash.success',\n 'History import queued \u2014 track progress in the top bar.',\n ),\n 'success',\n )\n onQueued()\n }, [channel, sinceDays, maxMessages, contactEmails, submitting, t, onQueued, retryLastMutation, runMutation, importLimits])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleSubmit()\n }\n },\n [handleSubmit],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.importHistory.title', 'Import channel history')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.importHistory.description',\n 'Pull older messages this channel never observed at connect-time. Filters narrow the search server-side.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-since\">\n {t('communication_channels.profile.importHistory.fields.sinceDays', 'Look back (days)')}\n </Label>\n <Input\n id=\"import-history-since\"\n type=\"number\"\n min={1}\n max={importLimits.maxSinceDays}\n value={sinceDays}\n onChange={(e) => setSinceDays(e.target.value)}\n aria-invalid={Boolean(fieldErrors.sinceDays)}\n />\n {fieldErrors.sinceDays ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.sinceDays}</p>\n ) : null}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-emails\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmails',\n 'Filter by sender (optional)',\n )}\n </Label>\n <Textarea\n id=\"import-history-emails\"\n rows={3}\n value={contactEmails}\n onChange={(e) => setContactEmails(e.target.value)}\n placeholder={t(\n 'communication_channels.profile.importHistory.fields.contactEmailsPlaceholder',\n 'alice@example.com, bob@example.com',\n )}\n aria-invalid={Boolean(fieldErrors.contactEmails)}\n />\n {fieldErrors.contactEmails ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.contactEmails}</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmailsHint',\n 'Leave empty to scan all senders in the window.',\n )}\n </p>\n )}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-max\">\n {t('communication_channels.profile.importHistory.fields.maxMessages', 'Maximum messages')}\n </Label>\n <Input\n id=\"import-history-max\"\n type=\"number\"\n min={1}\n max={importLimits.maxMessages}\n value={maxMessages}\n onChange={(e) => setMaxMessages(e.target.value)}\n aria-invalid={Boolean(fieldErrors.maxMessages)}\n />\n {fieldErrors.maxMessages ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.maxMessages}</p>\n ) : null}\n </div>\n\n {fieldErrors.channelId ? (\n <Alert status=\"warning\">\n <AlertDescription>{fieldErrors.channelId}</AlertDescription>\n </Alert>\n ) : null}\n </div>\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.importHistory.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={() => void handleSubmit()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.importHistory.submitting', 'Queueing\u2026')\n : t('communication_channels.profile.importHistory.submit', 'Start import')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype DisconnectChannelDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onDisconnected: () => void\n}\n\nfunction DisconnectChannelDialog({\n channel,\n onClose,\n onDisconnected,\n}: DisconnectChannelDialogProps): React.JSX.Element {\n const t = useT()\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: DISCONNECT_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) setSubmitting(false)\n }, [channel?.id])\n\n const handleConfirm = React.useCallback(async () => {\n if (!channel || submitting) return\n setSubmitting(true)\n let response\n try {\n response = await runMutation({\n // optimistic-lock-exempt: self-service connect/disconnect of the\n // signed-in operator's OWN communication channel (an integration link),\n // not a shared multi-editor record. Disconnect is a terminal action\n // keyed by channel id; there is no concurrent-edit lost-update window to\n // guard, and the row carries no client-surfaced `updatedAt` round-trip.\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}`,\n { method: 'DELETE' },\n ),\n context: {\n formId: DISCONNECT_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { action: 'disconnect' },\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ??\n t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.disconnectSuccess',\n 'Channel disconnected. You can reconnect it anytime.',\n ),\n 'success',\n )\n onDisconnected()\n }, [channel, submitting, runMutation, retryLastMutation, t, onDisconnected])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleConfirm()\n }\n },\n [handleConfirm],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.disconnect.title', 'Disconnect channel')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.disconnect.description',\n 'This removes the connection and stops syncing. Emails already imported stay on your timelines. You can reconnect anytime.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n {channel ? (\n <p className=\"text-sm font-medium\">{channel.externalIdentifier ?? channel.displayName}</p>\n ) : null}\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.disconnect.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" variant=\"destructive-solid\" onClick={() => void handleConfirm()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.disconnect.submitting', 'Disconnecting\u2026')\n : t('communication_channels.profile.disconnect.confirm', 'Disconnect')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction statusTag(\n status: ChannelRow['status'],\n t: (key: string, fallback?: string) => string,\n): React.ReactNode {\n switch (status) {\n case 'connected':\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.status.connected', 'Connected')}\n </Tag>\n )\n case 'requires_reauth':\n return (\n <Tag variant=\"warning\" dot>\n {t('communication_channels.status.requiresReauth', 'Needs reconnection')}\n </Tag>\n )\n case 'error':\n return (\n <Tag variant=\"error\" dot>\n {t('communication_channels.status.error', 'Error')}\n </Tag>\n )\n case 'disconnected':\n return <Tag variant=\"neutral\">{t('communication_channels.status.disconnected', 'Disconnected')}</Tag>\n default:\n return <Tag variant=\"neutral\">{status}</Tag>\n }\n}\n"],
5
- "mappings": ";AA8XU,cAyOA,YAzOA;AA5XV,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AAEvC,SAAS,WAAW,uBAAuB;AAC3C,SAAS,MAAM,gBAAgB;AAC/B,SAAS,iBAAiB;AAC1B,SAAS,WAAW;AACpB,SAAS,cAAc;AACvB,SAAS,OAAO,wBAAwB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,kBAAsC;AAC/C,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,wBAAwB;AACjC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,0BAA0B;AA+BnC,MAAM,uCAAuC;AAC7C,MAAM,qCAAqC;AAC3C,MAAM,iCAAiC;AASxB,SAAR,mCAAoD;AACzD,QAAM,IAAI,KAAK;AACf,QAAM,SAAS,UAAU;AACzB,QAAM,eAAe,gBAAgB;AACrC,QAAM,YAAY,cAAc,IAAI,OAAO;AAC3C,QAAM,YAAY,cAAc,IAAI,MAAM;AAC1C,QAAM,gBAAgB,cAAc,IAAI,UAAU;AAElD,QAAM,CAAC,MAAM,OAAO,IAAI,MAAM,SAAuB,CAAC,CAAC;AACvD,QAAM,CAAC,WAAW,YAAY,IAAI,MAAM,SAAS,IAAI;AACrD,QAAM,CAAC,cAAc,eAAe,IAAI,MAAM,SAAwB,IAAI;A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ACzE;AAAA,OACF;AAAA,KACF,GACF;AAEJ;AAEA,SAAS,UACP,QACA,GACiB;AACjB,UAAQ,QAAQ;AAAA,IACd,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,2CAA2C,WAAW,GAC3D;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,gDAAgD,oBAAoB,GACzE;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,SAAQ,KAAG,MACrB,YAAE,uCAAuC,OAAO,GACnD;AAAA,IAEJ,KAAK;AACH,aAAO,oBAAC,OAAI,SAAQ,WAAW,YAAE,8CAA8C,cAAc,GAAE;AAAA,IACjG;AACE,aAAO,oBAAC,OAAI,SAAQ,WAAW,kBAAO;AAAA,EAC1C;AACF;",
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { extensionPoints } from '@open-mercato/core/modules/communication_channels/extension-points'\nimport { getImportHistoryLimits } from '@open-mercato/core/modules/communication_channels/lib/import-history-limits'\nimport { OAUTH_RESULT_QUERY_PARAM, stripOAuthResultParams } from '@open-mercato/core/modules/communication_channels/lib/oauth-result'\nimport type { LegacyColumnDef as ColumnDef } from '@tanstack/react-table/legacy'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { DataTable } from '@open-mercato/ui/backend/DataTable'\nimport { Tag } from '@open-mercato/ui/primitives/tag'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { Alert, AlertDescription } from '@open-mercato/ui/primitives/alert'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Label } from '@open-mercato/ui/primitives/label'\nimport { Textarea } from '@open-mercato/ui/primitives/textarea'\nimport { KbdShortcut } from '@open-mercato/ui/primitives/kbd'\nimport { RowActions, type RowActionItem } from '@open-mercato/ui/backend/RowActions'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { useConfirmDialog } from '@open-mercato/ui/backend/confirm-dialog'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { ConnectChannelMenu } from './ConnectChannelMenu'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\n /** `shared` = a team mailbox: teammates can read the CRM email it ingests. */\n visibility: 'private' | 'shared'\n /** Version token for the share toggle's optimistic-lock header. */\n updatedAt: string | null\n isActive: boolean\n status: 'connected' | 'requires_reauth' | 'error' | 'disconnected'\n lastError: string | null\n pollIntervalSeconds: number | null\n lastPolledAt: string | null\n /** Spec C \u2014 push delivery state (null when provider doesn't support push). */\n pushStatus: 'active' | 'inactive' | 'failed' | null\n lastPushError: { code: string | null; message: string | null; at: string | null } | null\n /**\n * `true` when the adapter declares real-time push, so the hub's poll worker\n * skips this channel entirely \u2014 inbound arrives over the provider connection.\n */\n supportsRealtimePush: boolean\n /** `true` when the adapter implements `registerPush` (Gmail-style subscriptions). */\n supportsPushRegistration: boolean\n createdAt: string | null\n}\n\nconst PROFILE_CHANNELS_MUTATION_CONTEXT_ID = 'communication-channels-profile'\nconst IMPORT_HISTORY_MUTATION_CONTEXT_ID = 'communication-channels-import-history'\nconst DISCONNECT_MUTATION_CONTEXT_ID = 'communication-channels-disconnect'\n\ntype ChannelMutationContext = {\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport default function ProfileCommunicationChannelsPage() {\n const t = useT()\n const router = useRouter()\n const searchParams = useSearchParams()\n const flashType = searchParams?.get(OAUTH_RESULT_QUERY_PARAM)\n const flashCode = searchParams?.get('code')\n const flashProvider = searchParams?.get('provider')\n\n const [rows, setRows] = React.useState<ChannelRow[]>([])\n const [isLoading, setIsLoading] = React.useState(true)\n const [errorMessage, setErrorMessage] = React.useState<string | null>(null)\n const [reloadKey, setReloadKey] = React.useState(0)\n const [importChannel, setImportChannel] = React.useState<ChannelRow | null>(null)\n const [disconnectChannel, setDisconnectChannel] = React.useState<ChannelRow | null>(null)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n // Sharing a mailbox is privacy-consequential, so the widening direction is\n // confirmed. Escape cancels and Cmd/Ctrl+Enter submits (ConfirmDialog owns both).\n const { confirm, ConfirmDialogElement } = useConfirmDialog()\n\n React.useEffect(() => {\n if (flashType === 'connected') {\n const providerLabel = flashProvider\n ? t(`communication_channels.channel.providers.${flashProvider}`, '')\n : ''\n flash(\n providerLabel\n ? t('communication_channels.profile.flash.connectedWithProvider', 'Channel connected ({provider}).', {\n provider: providerLabel,\n })\n : t('communication_channels.profile.flash.connected', 'Channel connected.'),\n 'success',\n )\n } else if (flashType === 'error') {\n flash(\n flashCode === 'oauth_client_not_configured'\n ? t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n )\n : flashCode === 'mailbox_already_connected'\n ? t(\n 'communication_channels.profile.connect.mailboxAlreadyConnected',\n 'This mailbox is already connected through another provider. Disconnect it first to reconnect it with a different one.',\n )\n : flashCode === 'replay'\n ? t(\n 'communication_channels.profile.flash.replayedState',\n 'This connection link was already used \u2014 please start the connection again.',\n )\n : flashCode === 'state_store_unavailable'\n ? t(\n 'communication_channels.profile.flash.stateStoreUnavailable',\n 'A server error prevented completing the connection. Please try again in a moment.',\n )\n : t('communication_channels.profile.flash.error', 'Failed to connect channel.'),\n 'error',\n )\n } else {\n return\n }\n router.replace(stripOAuthResultParams(window.location.href), { scroll: false })\n }, [flashType, flashCode, flashProvider, router, t])\n\n React.useEffect(() => {\n let cancelled = false\n async function load() {\n setIsLoading(true)\n setErrorMessage(null)\n const response = await apiCall<{ items?: ChannelRow[] }>(\n '/api/communication_channels/me/channels',\n ).catch((err: unknown) => ({\n ok: false,\n result: { error: err instanceof Error ? err.message : 'Failed to load channels' },\n }))\n if (cancelled) return\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n setErrorMessage(\n body?.error ?? t('communication_channels.errors.loadList', 'Failed to load channels'),\n )\n setRows([])\n } else {\n const data = (response.result ?? {}) as { items?: ChannelRow[] }\n setRows(Array.isArray(data.items) ? data.items : [])\n }\n setIsLoading(false)\n }\n void load()\n return () => {\n cancelled = true\n }\n }, [reloadKey, t])\n\n const reauthRows = rows.filter((r) => r.status === 'requires_reauth')\n\n const reloadChannels = React.useCallback(() => setReloadKey((k) => k + 1), [])\n\n const onSetVisibility = React.useCallback(\n async (channel: ChannelRow, nextShared: boolean) => {\n // Only the widening direction needs a confirmation; making a mailbox\n // private again is the safe direction and stays one click.\n if (nextShared) {\n const confirmed = await confirm({\n title: t(\n 'communication_channels.profile.share.confirm.title',\n 'Share this mailbox with your team?',\n ),\n text: t(\n 'communication_channels.profile.share.confirm.text',\n 'Colleagues will be able to read the CRM email this mailbox handles, including messages already received. You stay the only person who can manage the connection, and you can stop sharing at any time.',\n ),\n confirmText: t('communication_channels.profile.share.confirm.cta', 'Share with team'),\n })\n if (!confirmed) return\n }\n\n const nextVisibility = nextShared ? 'shared' : 'private'\n let response\n try {\n response = await runMutation({\n operation: () => withScopedApiRequestHeaders(\n buildOptimisticLockHeader(channel.updatedAt),\n () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/visibility`,\n {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ visibility: nextVisibility }),\n },\n ),\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { visibility: nextVisibility },\n })\n } catch (err) {\n if (surfaceRecordConflict(err, t)) return\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n if (!response.ok) {\n if (surfaceRecordConflict(\n { status: response.status, body: response.result },\n t,\n { onRefresh: () => setReloadKey((k) => k + 1) },\n )) return\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.share.failed', 'Failed to update sharing'),\n 'error',\n )\n return\n }\n flash(\n nextShared\n ? t('communication_channels.profile.share.sharedSuccess', 'Mailbox shared with your team.')\n : t('communication_channels.profile.share.privateSuccess', 'Mailbox is private again.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [runMutation, retryLastMutation, confirm, t],\n )\n\n const onSetPrimary = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/set-primary`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { isPrimary: true },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.setPrimaryFailed', 'Failed to set as primary'),\n 'error',\n )\n return\n }\n flash(\n t('communication_channels.profile.actions.setPrimarySuccess', 'Marked as primary.'),\n 'success',\n )\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onRegisterPush = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ pushStatus?: string; error?: { code: string; message: string } }>(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/push/register`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'push-register' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.push.button.reregister', 'Re-register push'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(body?.error ?? t('communication_channels.push.flash.registerFailed', 'Failed to register push'), 'error')\n return\n }\n const result = (response.result ?? {}) as { pushStatus?: string }\n if (result.pushStatus === 'active') {\n flash(t('communication_channels.push.status.active', 'Push active'), 'success')\n } else {\n flash(\n t(\n 'communication_channels.push.status.failed',\n 'Push registration returned a non-active status \u2014 falling back to polling.',\n ),\n 'error',\n )\n }\n setReloadKey((k) => k + 1)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const onPollNow = React.useCallback(\n async (channelId: string) => {\n let response\n try {\n response = await runMutation({\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,\n { method: 'POST' },\n ),\n context: {\n formId: PROFILE_CHANNELS_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channelId,\n retryLastMutation,\n },\n mutationPayload: { action: 'poll-now' },\n })\n } catch (err) {\n flash(err instanceof Error ? err.message : t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'), 'error')\n return\n }\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ?? t('communication_channels.profile.actions.pollNowFailed', 'Failed to trigger poll'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.pollNowSuccess',\n 'Poll triggered \u2014 new messages will appear on linked Person timelines in a few seconds.',\n ),\n 'success',\n )\n // Give the worker a moment to fetch + ingest, then refetch our channel list\n // so `lastPolledAt` updates in the UI.\n setTimeout(() => setReloadKey((k) => k + 1), 1500)\n },\n [retryLastMutation, runMutation, t],\n )\n\n const columns = React.useMemo<ColumnDef<ChannelRow>[]>(\n () => [\n {\n header: t('communication_channels.columns.displayName', 'Channel'),\n accessorKey: 'displayName',\n },\n {\n header: t('communication_channels.columns.provider', 'Provider'),\n accessorKey: 'providerKey',\n cell: ({ row }) => (\n <Tag variant=\"info\">\n {t(\n `communication_channels.channel.providers.${row.original.providerKey}`,\n row.original.providerKey,\n )}\n </Tag>\n ),\n },\n {\n header: t('communication_channels.columns.identifier', 'Email / username'),\n accessorKey: 'externalIdentifier',\n cell: ({ row }) => row.original.externalIdentifier ?? '\u2014',\n meta: { truncate: true, maxWidth: 240 },\n },\n {\n header: t('communication_channels.profile.columns.primary', 'Primary'),\n accessorKey: 'isPrimary',\n // Status only \u2014 \"Set as primary\" lives in the row actions menu.\n cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ),\n },\n {\n header: t('communication_channels.profile.columns.sharing', 'Team access'),\n accessorKey: 'visibility',\n // Status only \u2014 the share/unshare flip lives in the row actions menu.\n //\n // Only email ingestion writes customer_interactions, so on an SMS or push\n // channel a share would flip the flag and flash success while changing\n // nothing anyone can observe. The menu applies the same email-only rule.\n cell: ({ row }) =>\n row.original.channelType !== 'email' ? (\n <span className=\"text-xs text-muted-foreground\">\u2014</span>\n ) : row.original.visibility === 'shared' ? (\n <Tag variant=\"info\" dot>\n {t('communication_channels.profile.share.shared', 'Shared')}\n </Tag>\n ) : (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.profile.share.private', 'Only you')}\n </span>\n ),\n },\n {\n header: t('communication_channels.columns.status', 'Status'),\n accessorKey: 'status',\n cell: ({ row }) => statusTag(row.original.status, t),\n },\n {\n id: 'pushStatus',\n // Its own key: sharing `push.status.active` made the header render\n // \"Push active\" over a column whose rows say \"Polling only\" (#4980).\n header: t('communication_channels.profile.columns.push', 'Push'),\n cell: ({ row }) => {\n const ps = row.original.pushStatus\n const errorTitle = row.original.lastPushError?.message ?? undefined\n // Derived from the adapter's declared capabilities, never from the\n // provider name: `supportsPushRegistration` means push subscriptions\n // can be (re-)registered from here, `supportsRealtimePush` means the\n // hub's poll worker skips the channel because the provider connection\n // delivers inbound itself (#4980).\n if (!row.original.supportsPushRegistration) {\n if (!row.original.supportsRealtimePush) {\n return (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.pushDrivenFailed', 'Push connection failed')}\n </Tag>\n )\n }\n // The \"why is there no Poll now action?\" explanation used to live on\n // the disabled Sync button's aria-label. That button is gone, so the\n // reason moves here rather than being lost.\n return (\n <Tag\n variant=\"success\"\n dot\n title={t(\n 'communication_channels.profile.actions.pollNowPushDriven',\n 'This channel is push-driven \u2014 inbound messages arrive over the provider connection, so polling does not apply.',\n )}\n >\n {t('communication_channels.push.status.pushDriven', 'Push-driven')}\n </Tag>\n )\n }\n if (ps === 'active') {\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.push.status.active', 'Push active')}\n </Tag>\n )\n }\n if (ps === 'failed') {\n return (\n <Tag variant=\"error\" dot title={errorTitle}>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n )\n }\n // null or 'inactive' \u2014 the provider can register push but has not yet.\n // Only a hub-polled channel falls back to polling meanwhile; for a\n // push-driven one nothing is delivering inbound at all, so claiming\n // \"Polling only\" would repeat the defect this issue is about (#4980).\n return (\n <span className=\"text-xs text-muted-foreground\">\n {row.original.supportsRealtimePush\n ? t('communication_channels.push.status.notRegistered', 'Push not registered')\n : t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n },\n },\n {\n header: t('communication_channels.profile.columns.lastPolled', 'Last synced'),\n accessorKey: 'lastPolledAt',\n cell: ({ row }) =>\n row.original.lastPolledAt\n ? new Date(row.original.lastPolledAt).toLocaleString()\n : '\u2014',\n },\n ],\n [t],\n )\n\n /**\n * Every per-row action, in one menu. The table previously carried five action\n * columns, which pushed the row past the viewport and clipped the trailing\n * buttons.\n *\n * Passed as DataTable's `rowActions` rather than as a hand-rolled column so the\n * table can merge row actions injected by other modules into this same menu\n * (`extensionTableId` below) instead of rendering a second one, and so the\n * actions cell keeps the table's own header, alignment and sticky behaviour.\n *\n * `RowActionItem` has no disabled state, so an unavailable action is OMITTED\n * rather than greyed out. The reason stays visible in the row: the Status and\n * Push columns already say why a channel cannot be polled or needs reconnecting.\n */\n const rowActions = React.useCallback(\n (channel: ChannelRow) => {\n const items: RowActionItem[] = []\n\n if (!channel.isPrimary) {\n items.push({\n id: 'set-primary',\n label: t('communication_channels.profile.actions.setPrimary', 'Set as primary'),\n onSelect: () => { void onSetPrimary(channel.id) },\n })\n }\n\n // Email only, for the reason the Team access column documents: on a\n // non-email channel the flip would change nothing anyone can observe.\n if (channel.channelType === 'email') {\n items.push(\n channel.visibility === 'shared'\n ? {\n id: 'make-private',\n label: t('communication_channels.profile.share.makePrivate', 'Make private'),\n onSelect: () => { void onSetVisibility(channel, false) },\n }\n : {\n id: 'share-with-team',\n label: t('communication_channels.profile.share.shareCta', 'Share with team'),\n onSelect: () => { void onSetVisibility(channel, true) },\n },\n )\n }\n\n // Offered only when the adapter can register push AND it is not already\n // active \u2014 re-registering a healthy subscription is a no-op.\n if (channel.supportsPushRegistration && channel.pushStatus !== 'active') {\n items.push({\n id: 'register-push',\n label: t('communication_channels.push.button.reregister', 'Re-register push'),\n onSelect: () => { void onRegisterPush(channel.id) },\n })\n }\n\n // Same eligibility the History column enforced.\n if (channel.isActive && channel.status === 'connected' && channel.channelType === 'email') {\n items.push({\n id: 'import-history',\n label: t('communication_channels.profile.actions.importHistory', 'Import history'),\n onSelect: () => setImportChannel(channel),\n })\n }\n\n // Same eligibility the Sync column enforced: allowed from 'connected'\n // AND 'error' (so a stuck channel can be recovered without a\n // reconnect), never for a push-driven channel the worker skips (#4980).\n const pollable =\n channel.isActive &&\n !channel.supportsRealtimePush &&\n (channel.status === 'connected' || channel.status === 'error')\n if (pollable) {\n items.push({\n id: 'poll-now',\n label:\n channel.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now'),\n onSelect: () => { void onPollNow(channel.id) },\n })\n }\n\n items.push({\n id: 'disconnect',\n label: t('communication_channels.profile.actions.disconnect', 'Disconnect'),\n destructive: true,\n onSelect: () => setDisconnectChannel(channel),\n })\n\n return <RowActions items={items} />\n },\n [onSetPrimary, onSetVisibility, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4\">\n <div className=\"min-w-0\">\n <h1 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h1>\n <p className=\"text-sm text-muted-foreground\">\n {t(\n 'communication_channels.profile.subtitle',\n 'Connect your communication channels so outbound messages come from your own account and inbound messages land in your unified inbox.',\n )}\n </p>\n </div>\n {/* Provider connect entry points injected by each channel-* package\n (channel-gmail, channel-imap) via UMES. They stack inside one\n dropdown so the header does not widen per installed provider. */}\n <ConnectChannelMenu onConnected={reloadChannels} />\n </header>\n\n {reauthRows.length > 0 ? (\n <Alert status=\"warning\" className=\"mb-4\">\n <AlertDescription>\n {t(\n 'communication_channels.profile.alerts.requiresReauth',\n '{count} channel(s) need reconnection. Click \"Reconnect\" on the affected channel below.',\n { count: reauthRows.length },\n )}\n </AlertDescription>\n </Alert>\n ) : null}\n\n <DataTable<ChannelRow>\n title={t('communication_channels.profile.tableTitle', 'Your channels')}\n titleHeadingLevel={2}\n extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n rowActions={rowActions}\n // Pinned because this table is wider than a laptop viewport: at 1280px\n // the row runs out well before the actions cell, and since Primary,\n // Team access and Push are status-only there is no other control in\n // view. Unpinned, reaching \u22EF meant scrolling to the far end, which\n // scrolls the Channel column away \u2014 so you could no longer see which\n // channel the open menu belonged to (#6717).\n stickyActionsColumn\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Add one using the menu at the top of this page.',\n )}\n />\n <ImportHistoryDialog\n channel={importChannel}\n onClose={() => setImportChannel(null)}\n onQueued={() => {\n setImportChannel(null)\n router.refresh()\n }}\n />\n <DisconnectChannelDialog\n channel={disconnectChannel}\n onClose={() => setDisconnectChannel(null)}\n onDisconnected={() => {\n setDisconnectChannel(null)\n setReloadKey((k) => k + 1)\n }}\n />\n {ConfirmDialogElement}\n </PageBody>\n </Page>\n )\n}\n\ntype ImportHistoryDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onQueued: () => void\n}\n\nfunction ImportHistoryDialog({ channel, onClose, onQueued }: ImportHistoryDialogProps): React.JSX.Element {\n const t = useT()\n const importLimits = React.useMemo(() => getImportHistoryLimits(channel?.providerKey), [channel?.providerKey])\n const [sinceDays, setSinceDays] = React.useState('30')\n const [contactEmails, setContactEmails] = React.useState('')\n const [maxMessages, setMaxMessages] = React.useState('500')\n const [fieldErrors, setFieldErrors] = React.useState<Record<string, string>>({})\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) {\n setSinceDays('30')\n setContactEmails('')\n setMaxMessages('500')\n setFieldErrors({})\n setSubmitting(false)\n }\n }, [channel?.id])\n\n const handleSubmit = React.useCallback(async () => {\n if (!channel || submitting) return\n const sinceNum = Number.parseInt(sinceDays, 10)\n const maxNum = Number.parseInt(maxMessages, 10)\n const errors: Record<string, string> = {}\n if (!Number.isFinite(sinceNum) || sinceNum < 1 || sinceNum > importLimits.maxSinceDays) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and {max} days.',\n { max: importLimits.maxSinceDays },\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > importLimits.maxMessages) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and {max} messages.',\n { max: importLimits.maxMessages },\n )\n }\n const parsedEmails = contactEmails\n .split(/[\\s,;]+/)\n .map((s) => s.trim())\n .filter(Boolean)\n if (parsedEmails.length > 0 && parsedEmails.some((s) => !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s))) {\n errors.contactEmails = t(\n 'communication_channels.profile.importHistory.errors.contactEmails',\n 'One or more entries is not a valid email address.',\n )\n }\n if (Object.keys(errors).length > 0) {\n setFieldErrors(errors)\n return\n }\n setFieldErrors({})\n setSubmitting(true)\n const mutationPayload = {\n sinceDays: sinceNum,\n maxMessages: maxNum,\n ...(parsedEmails.length > 0 ? { contactEmails: parsedEmails } : {}),\n }\n let response\n try {\n response = await runMutation({\n operation: () => apiCall<{ progressJobId?: string }>(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}/import-history`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(mutationPayload),\n },\n ),\n context: {\n formId: IMPORT_HISTORY_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload,\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.importHistory.flash.error', 'Failed to queue history import.'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string; fieldErrors?: Record<string, string> } | undefined\n if (body?.fieldErrors && Object.keys(body.fieldErrors).length > 0) {\n setFieldErrors(body.fieldErrors)\n return\n }\n flash(\n body?.error ??\n t(\n 'communication_channels.profile.importHistory.flash.error',\n 'Failed to queue history import.',\n ),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.importHistory.flash.success',\n 'History import queued \u2014 track progress in the top bar.',\n ),\n 'success',\n )\n onQueued()\n }, [channel, sinceDays, maxMessages, contactEmails, submitting, t, onQueued, retryLastMutation, runMutation, importLimits])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleSubmit()\n }\n },\n [handleSubmit],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.importHistory.title', 'Import channel history')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.importHistory.description',\n 'Pull older messages this channel never observed at connect-time. Filters narrow the search server-side.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n <div className=\"space-y-4\">\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-since\">\n {t('communication_channels.profile.importHistory.fields.sinceDays', 'Look back (days)')}\n </Label>\n <Input\n id=\"import-history-since\"\n type=\"number\"\n min={1}\n max={importLimits.maxSinceDays}\n value={sinceDays}\n onChange={(e) => setSinceDays(e.target.value)}\n aria-invalid={Boolean(fieldErrors.sinceDays)}\n />\n {fieldErrors.sinceDays ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.sinceDays}</p>\n ) : null}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-emails\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmails',\n 'Filter by sender (optional)',\n )}\n </Label>\n <Textarea\n id=\"import-history-emails\"\n rows={3}\n value={contactEmails}\n onChange={(e) => setContactEmails(e.target.value)}\n placeholder={t(\n 'communication_channels.profile.importHistory.fields.contactEmailsPlaceholder',\n 'alice@example.com, bob@example.com',\n )}\n aria-invalid={Boolean(fieldErrors.contactEmails)}\n />\n {fieldErrors.contactEmails ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.contactEmails}</p>\n ) : (\n <p className=\"text-xs text-muted-foreground\">\n {t(\n 'communication_channels.profile.importHistory.fields.contactEmailsHint',\n 'Leave empty to scan all senders in the window.',\n )}\n </p>\n )}\n </div>\n\n <div className=\"space-y-1\">\n <Label htmlFor=\"import-history-max\">\n {t('communication_channels.profile.importHistory.fields.maxMessages', 'Maximum messages')}\n </Label>\n <Input\n id=\"import-history-max\"\n type=\"number\"\n min={1}\n max={importLimits.maxMessages}\n value={maxMessages}\n onChange={(e) => setMaxMessages(e.target.value)}\n aria-invalid={Boolean(fieldErrors.maxMessages)}\n />\n {fieldErrors.maxMessages ? (\n <p className=\"text-xs text-status-error-text\">{fieldErrors.maxMessages}</p>\n ) : null}\n </div>\n\n {fieldErrors.channelId ? (\n <Alert status=\"warning\">\n <AlertDescription>{fieldErrors.channelId}</AlertDescription>\n </Alert>\n ) : null}\n </div>\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.importHistory.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" onClick={() => void handleSubmit()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.importHistory.submitting', 'Queueing\u2026')\n : t('communication_channels.profile.importHistory.submit', 'Start import')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\ntype DisconnectChannelDialogProps = {\n channel: ChannelRow | null\n onClose: () => void\n onDisconnected: () => void\n}\n\nfunction DisconnectChannelDialog({\n channel,\n onClose,\n onDisconnected,\n}: DisconnectChannelDialogProps): React.JSX.Element {\n const t = useT()\n const [submitting, setSubmitting] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation<ChannelMutationContext>({\n contextId: DISCONNECT_MUTATION_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n React.useEffect(() => {\n if (channel) setSubmitting(false)\n }, [channel?.id])\n\n const handleConfirm = React.useCallback(async () => {\n if (!channel || submitting) return\n setSubmitting(true)\n let response\n try {\n response = await runMutation({\n // optimistic-lock-exempt: self-service connect/disconnect of the\n // signed-in operator's OWN communication channel (an integration link),\n // not a shared multi-editor record. Disconnect is a terminal action\n // keyed by channel id; there is no concurrent-edit lost-update window to\n // guard, and the row carries no client-surfaced `updatedAt` round-trip.\n operation: () => apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channel.id)}`,\n { method: 'DELETE' },\n ),\n context: {\n formId: DISCONNECT_MUTATION_CONTEXT_ID,\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n retryLastMutation,\n },\n mutationPayload: { action: 'disconnect' },\n })\n } catch (err) {\n setSubmitting(false)\n flash(\n err instanceof Error\n ? err.message\n : t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n setSubmitting(false)\n if (!response.ok) {\n const body = response.result as { error?: string } | undefined\n flash(\n body?.error ??\n t('communication_channels.profile.actions.disconnectFailed', 'Failed to disconnect channel'),\n 'error',\n )\n return\n }\n flash(\n t(\n 'communication_channels.profile.actions.disconnectSuccess',\n 'Channel disconnected. You can reconnect it anytime.',\n ),\n 'success',\n )\n onDisconnected()\n }, [channel, submitting, runMutation, retryLastMutation, t, onDisconnected])\n\n const handleKeyDown = React.useCallback(\n (event: React.KeyboardEvent) => {\n if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {\n event.preventDefault()\n void handleConfirm()\n }\n },\n [handleConfirm],\n )\n\n return (\n <Dialog open={channel !== null} onOpenChange={(open) => { if (!open) onClose() }}>\n <DialogContent onKeyDown={handleKeyDown}>\n <DialogHeader>\n <DialogTitle>\n {t('communication_channels.profile.disconnect.title', 'Disconnect channel')}\n </DialogTitle>\n <DialogDescription>\n {t(\n 'communication_channels.profile.disconnect.description',\n 'This removes the connection and stops syncing. Emails already imported stay on your timelines. You can reconnect anytime.',\n )}\n </DialogDescription>\n </DialogHeader>\n\n {channel ? (\n <p className=\"text-sm font-medium\">{channel.externalIdentifier ?? channel.displayName}</p>\n ) : null}\n\n <DialogFooter>\n <span className=\"mr-auto text-xs text-muted-foreground\">\n <KbdShortcut keys={['\u2318', 'Enter']} />\n </span>\n <Button type=\"button\" variant=\"outline\" onClick={onClose} disabled={submitting}>\n {t('communication_channels.profile.disconnect.cancel', 'Cancel')}\n </Button>\n <Button type=\"button\" variant=\"destructive-solid\" onClick={() => void handleConfirm()} disabled={submitting}>\n {submitting\n ? t('communication_channels.profile.disconnect.submitting', 'Disconnecting\u2026')\n : t('communication_channels.profile.disconnect.confirm', 'Disconnect')}\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n )\n}\n\nfunction statusTag(\n status: ChannelRow['status'],\n t: (key: string, fallback?: string) => string,\n): React.ReactNode {\n switch (status) {\n case 'connected':\n return (\n <Tag variant=\"success\" dot>\n {t('communication_channels.status.connected', 'Connected')}\n </Tag>\n )\n case 'requires_reauth':\n return (\n <Tag variant=\"warning\" dot>\n {t('communication_channels.status.requiresReauth', 'Needs reconnection')}\n </Tag>\n )\n case 'error':\n return (\n <Tag variant=\"error\" dot>\n {t('communication_channels.status.error', 'Error')}\n </Tag>\n )\n case 'disconnected':\n return <Tag variant=\"neutral\">{t('communication_channels.status.disconnected', 'Disconnected')}</Tag>\n default:\n return <Tag variant=\"neutral\">{status}</Tag>\n }\n}\n"],
5
+ "mappings": ";AAiYU,cAyOA,YAzOA;AA/XV,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,0B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AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,WAAU,KAAG,MACvB,YAAE,gDAAgD,oBAAoB,GACzE;AAAA,IAEJ,KAAK;AACH,aACE,oBAAC,OAAI,SAAQ,SAAQ,KAAG,MACrB,YAAE,uCAAuC,OAAO,GACnD;AAAA,IAEJ,KAAK;AACH,aAAO,oBAAC,OAAI,SAAQ,WAAW,YAAE,8CAA8C,cAAc,GAAE;AAAA,IACjG;AACE,aAAO,oBAAC,OAAI,SAAQ,WAAW,kBAAO;AAAA,EAC1C;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,12 @@
1
+ const OAUTH_RESULT_QUERY_PARAM = "oauth";
2
+ const OAUTH_RESULT_QUERY_PARAMS = [OAUTH_RESULT_QUERY_PARAM, "code", "provider", "channelId"];
3
+ function stripOAuthResultParams(href) {
4
+ const url = new URL(href);
5
+ for (const param of OAUTH_RESULT_QUERY_PARAMS) url.searchParams.delete(param);
6
+ return `${url.pathname}${url.search}${url.hash}`;
7
+ }
8
+ export {
9
+ OAUTH_RESULT_QUERY_PARAM,
10
+ stripOAuthResultParams
11
+ };
12
+ //# sourceMappingURL=oauth-result.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/communication_channels/lib/oauth-result.ts"],
4
+ "sourcesContent": ["// The OAuth callback reports its outcome to the return page through this query\n// param. It must not be `flash`: the global <FlashMessages> host reads `?flash=`\n// as the message text and would render the raw outcome (\"error\"/\"connected\") as\n// a success toast (#6402).\nexport const OAUTH_RESULT_QUERY_PARAM = 'oauth'\n\nconst OAUTH_RESULT_QUERY_PARAMS = [OAUTH_RESULT_QUERY_PARAM, 'code', 'provider', 'channelId']\n\nexport function stripOAuthResultParams(href: string): string {\n const url = new URL(href)\n for (const param of OAUTH_RESULT_QUERY_PARAMS) url.searchParams.delete(param)\n return `${url.pathname}${url.search}${url.hash}`\n}\n"],
5
+ "mappings": "AAIO,MAAM,2BAA2B;AAExC,MAAM,4BAA4B,CAAC,0BAA0B,QAAQ,YAAY,WAAW;AAErF,SAAS,uBAAuB,MAAsB;AAC3D,QAAM,MAAM,IAAI,IAAI,IAAI;AACxB,aAAW,SAAS,0BAA2B,KAAI,aAAa,OAAO,KAAK;AAC5E,SAAO,GAAG,IAAI,QAAQ,GAAG,IAAI,MAAM,GAAG,IAAI,IAAI;AAChD;",
6
+ "names": []
7
+ }
@@ -74,6 +74,7 @@ function ActivitiesSection({
74
74
  useCanonicalInteractions = false,
75
75
  onActionChange,
76
76
  onLoadingChange,
77
+ onDataRefresh,
77
78
  refreshKey = 0,
78
79
  onEditActivity,
79
80
  runGuardedMutation,
@@ -232,8 +233,14 @@ function ActivitiesSection({
232
233
  } catch (err) {
233
234
  logger.warn("Mark done failed", { component: "ActivitiesSection", activityId, err });
234
235
  flash(t("customers.activities.actions.markDoneError", "Could not mark activity as done"), "error");
236
+ return;
237
+ }
238
+ try {
239
+ await Promise.resolve(onDataRefresh?.());
240
+ } catch (err) {
241
+ logger.warn("Parent refresh after mark done failed", { component: "ActivitiesSection", activityId, err });
235
242
  }
236
- }, [loadActivities, runGuardedMutation, t]);
243
+ }, [loadActivities, onDataRefresh, runGuardedMutation, t]);
237
244
  const resolvedUserIdsRef = React.useRef(/* @__PURE__ */ new Set());
238
245
  React.useEffect(() => {
239
246
  loadActivities().then(() => {