@open-mercato/core 0.6.8-develop.6891.1.4dca3f1ad3 → 0.6.8-develop.6892.1.f179677788

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 (31) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/communication_channels/api/get/me/channels/route.js +16 -2
  3. package/dist/modules/communication_channels/api/get/me/channels/route.js.map +2 -2
  4. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js +14 -1
  5. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js.map +2 -2
  6. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +24 -11
  7. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +2 -2
  8. package/dist/modules/communication_channels/lib/polling-eligibility.js +8 -0
  9. package/dist/modules/communication_channels/lib/polling-eligibility.js.map +7 -0
  10. package/dist/modules/communication_channels/workers/poll-channel.js +2 -2
  11. package/dist/modules/communication_channels/workers/poll-channel.js.map +2 -2
  12. package/dist/modules/configs/cli.js +12 -10
  13. package/dist/modules/configs/cli.js.map +2 -2
  14. package/dist/modules/configs/lib/touchGeneratedBarrels.js +2 -2
  15. package/dist/modules/configs/lib/touchGeneratedBarrels.js.map +2 -2
  16. package/dist/modules/customers/message-objects.js +1 -1
  17. package/dist/modules/customers/message-objects.js.map +1 -1
  18. package/package.json +7 -7
  19. package/src/modules/communication_channels/api/get/me/channels/route.ts +24 -2
  20. package/src/modules/communication_channels/api/post/channels/[id]/poll-now/route.ts +22 -1
  21. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +58 -13
  22. package/src/modules/communication_channels/i18n/de.json +6 -0
  23. package/src/modules/communication_channels/i18n/en.json +6 -0
  24. package/src/modules/communication_channels/i18n/es.json +6 -0
  25. package/src/modules/communication_channels/i18n/ko.json +6 -0
  26. package/src/modules/communication_channels/i18n/pl.json +6 -0
  27. package/src/modules/communication_channels/lib/polling-eligibility.ts +14 -0
  28. package/src/modules/communication_channels/workers/poll-channel.ts +3 -3
  29. package/src/modules/configs/cli.ts +12 -10
  30. package/src/modules/configs/lib/touchGeneratedBarrels.ts +5 -2
  31. package/src/modules/customers/message-objects.ts +1 -1
@@ -1,4 +1,4 @@
1
- [build:core] found 3798 entry points
1
+ [build:core] found 3799 entry points
2
2
  [build:core] built successfully
3
3
  [build:core:generated] found 198 entry points
4
4
  [build:core:generated] built successfully
@@ -3,6 +3,7 @@ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
3
3
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
4
4
  import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
5
5
  import { CommunicationChannel } from "../../../../data/entities.js";
6
+ import { isHubPolledChannel } from "../../../../lib/polling-eligibility.js";
6
7
  const metadata = {
7
8
  path: "/communication_channels/me/channels",
8
9
  GET: {
@@ -29,12 +30,20 @@ async function GET(req) {
29
30
  { orderBy: { createdAt: "desc" } },
30
31
  { tenantId: auth.tenantId, organizationId: auth.orgId ?? null }
31
32
  );
33
+ let adapterRegistry = null;
34
+ try {
35
+ adapterRegistry = container.resolve("channelAdapterRegistry");
36
+ } catch {
37
+ adapterRegistry = null;
38
+ }
32
39
  return NextResponse.json({
33
- items: channels.map(serialize),
40
+ items: channels.map(
41
+ (channel) => serialize(channel, adapterRegistry)
42
+ ),
34
43
  total: channels.length
35
44
  });
36
45
  }
37
- function serialize(channel) {
46
+ function serialize(channel, adapterRegistry) {
38
47
  const channelState = channel.channelState ?? null;
39
48
  const pushStatus = typeof channelState?.pushStatus === "string" ? channelState.pushStatus : null;
40
49
  const lastPushError = channelState?.lastPushError && typeof channelState.lastPushError === "object" ? {
@@ -42,6 +51,9 @@ function serialize(channel) {
42
51
  message: channelState.lastPushError.message ?? null,
43
52
  at: channelState.lastPushError.at ?? null
44
53
  } : null;
54
+ const supportsRealtimePush = !isHubPolledChannel(channel.capabilities);
55
+ const adapter = adapterRegistry?.get(channel.providerKey);
56
+ const supportsPushRegistration = typeof adapter?.registerPush === "function";
45
57
  return {
46
58
  id: channel.id,
47
59
  providerKey: channel.providerKey,
@@ -56,6 +68,8 @@ function serialize(channel) {
56
68
  lastPolledAt: channel.lastPolledAt?.toISOString?.() ?? null,
57
69
  pushStatus,
58
70
  lastPushError,
71
+ supportsRealtimePush,
72
+ supportsPushRegistration,
59
73
  createdAt: channel.createdAt?.toISOString?.() ?? null
60
74
  };
61
75
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/communication_channels/api/get/me/channels/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../../../../data/entities'\n\nexport const metadata = {\n path: '/communication_channels/me/channels',\n GET: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\n/**\n * List the current user's owned channels. Used by the profile page.\n *\n * Returns the user-scoped subset only (NOT tenant-wide channels). Admin views\n * of all channels live under `/api/communication_channels/channels` (slice 2e).\n */\nexport async function GET(req: Request): Promise<Response> {\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n userId: auth.sub as string,\n deletedAt: null,\n },\n { orderBy: { createdAt: 'desc' } },\n { tenantId: auth.tenantId as string, organizationId: (auth as { orgId?: string | null }).orgId ?? null },\n )\n\n return NextResponse.json({\n items: (channels as CommunicationChannel[]).map(serialize),\n total: channels.length,\n })\n}\n\nfunction serialize(channel: CommunicationChannel) {\n // Spec C \u2014 expose push status + last push error to the operator UI so\n // the `PushStatusSection` can render the \"Re-register push\" affordance.\n const channelState =\n (channel.channelState as\n | { pushStatus?: string; lastPushError?: { code?: string; message?: string; at?: string } | null }\n | null) ?? null\n const pushStatus =\n typeof channelState?.pushStatus === 'string'\n ? (channelState.pushStatus as 'active' | 'inactive' | 'failed')\n : null\n const lastPushError =\n channelState?.lastPushError && typeof channelState.lastPushError === 'object'\n ? {\n code: channelState.lastPushError.code ?? null,\n message: channelState.lastPushError.message ?? null,\n at: channelState.lastPushError.at ?? null,\n }\n : null\n return {\n id: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n displayName: channel.displayName,\n externalIdentifier: channel.externalIdentifier ?? null,\n isPrimary: channel.isPrimary,\n isActive: channel.isActive,\n status: channel.status,\n lastError: channel.lastError ?? null,\n pollIntervalSeconds: channel.pollIntervalSeconds ?? null,\n lastPolledAt: channel.lastPolledAt?.toISOString?.() ?? null,\n pushStatus,\n lastPushError,\n createdAt: channel.createdAt?.toISOString?.() ?? null,\n }\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'List the current user\\'s connected channels',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 200, description: 'List of user-owned channels' },\n { status: 401, description: 'Unauthorized' },\n ],\n },\n },\n}\nexport default GET\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AAE9B,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK;AAAA,IACH,aAAa;AAAA,IACb,iBAAiB,CAAC,6CAA6C;AAAA,EACjE;AACF;AAQA,eAAsB,IAAI,KAAiC;AACzD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,OAAO,CAAC,MAAM,UAAU;AACj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WAAW,QAAQ,WAAW,cAAc,KAAK;AAAA,EACnD;AACF;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,8BAA8B;AAAA,QAC1D,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,MAC7C;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 { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../../../../data/entities'\nimport { isHubPolledChannel } from '../../../../lib/polling-eligibility'\nimport type { ChannelAdapterRegistry } from '../../../../lib/registry'\n\nexport const metadata = {\n path: '/communication_channels/me/channels',\n GET: {\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\n/**\n * List the current user's owned channels. Used by the profile page.\n *\n * Returns the user-scoped subset only (NOT tenant-wide channels). Admin views\n * of all channels live under `/api/communication_channels/channels` (slice 2e).\n */\nexport async function GET(req: Request): Promise<Response> {\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n {\n tenantId: auth.tenantId as string,\n organizationId: (auth as { orgId?: string | null }).orgId ?? null,\n userId: auth.sub as string,\n deletedAt: null,\n },\n { orderBy: { createdAt: 'desc' } },\n { tenantId: auth.tenantId as string, organizationId: (auth as { orgId?: string | null }).orgId ?? null },\n )\n\n // The profile grid renders \"is this channel polled or push-driven?\" and\n // \"can push be registered here?\" \u2014 both are adapter facts, not provider names,\n // so they are resolved server-side (#4980).\n let adapterRegistry: ChannelAdapterRegistry | null = null\n try {\n adapterRegistry = container.resolve('channelAdapterRegistry') as ChannelAdapterRegistry\n } catch {\n adapterRegistry = null\n }\n\n return NextResponse.json({\n items: (channels as CommunicationChannel[]).map((channel) =>\n serialize(channel, adapterRegistry),\n ),\n total: channels.length,\n })\n}\n\nfunction serialize(channel: CommunicationChannel, adapterRegistry: ChannelAdapterRegistry | null) {\n // Spec C \u2014 expose push status + last push error to the operator UI so\n // the `PushStatusSection` can render the \"Re-register push\" affordance.\n const channelState =\n (channel.channelState as\n | { pushStatus?: string; lastPushError?: { code?: string; message?: string; at?: string } | null }\n | null) ?? null\n const pushStatus =\n typeof channelState?.pushStatus === 'string'\n ? (channelState.pushStatus as 'active' | 'inactive' | 'failed')\n : null\n const lastPushError =\n channelState?.lastPushError && typeof channelState.lastPushError === 'object'\n ? {\n code: channelState.lastPushError.code ?? null,\n message: channelState.lastPushError.message ?? null,\n at: channelState.lastPushError.at ?? null,\n }\n : null\n // `true` when the hub's poll worker skips this channel because the adapter\n // declares real-time push \u2014 the inverse of `isHubPolledChannel`, which the\n // worker itself uses, so the label cannot contradict the behaviour.\n const supportsRealtimePush = !isHubPolledChannel(channel.capabilities)\n const adapter = adapterRegistry?.get(channel.providerKey)\n const supportsPushRegistration = typeof adapter?.registerPush === 'function'\n return {\n id: channel.id,\n providerKey: channel.providerKey,\n channelType: channel.channelType,\n displayName: channel.displayName,\n externalIdentifier: channel.externalIdentifier ?? null,\n isPrimary: channel.isPrimary,\n isActive: channel.isActive,\n status: channel.status,\n lastError: channel.lastError ?? null,\n pollIntervalSeconds: channel.pollIntervalSeconds ?? null,\n lastPolledAt: channel.lastPolledAt?.toISOString?.() ?? null,\n pushStatus,\n lastPushError,\n supportsRealtimePush,\n supportsPushRegistration,\n createdAt: channel.createdAt?.toISOString?.() ?? null,\n }\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n GET: {\n summary: 'List the current user\\'s connected channels',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 200, description: 'List of user-owned channels' },\n { status: 401, description: 'Unauthorized' },\n ],\n },\n },\n}\nexport default GET\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B;AACrC,SAAS,0BAA0B;AAG5B,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,KAAK;AAAA,IACH,aAAa;AAAA,IACb,iBAAiB,CAAC,6CAA6C;AAAA,EACjE;AACF;AAQA,eAAsB,IAAI,KAAiC;AACzD,QAAM,OAAO,MAAM,mBAAmB,GAAG;AACzC,MAAI,CAAC,MAAM,OAAO,CAAC,MAAM,UAAU;AACjC,WAAO,aAAa,KAAK,EAAE,OAAO,eAAe,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACrE;AAEA,QAAM,YAAY,MAAM,uBAAuB;AAC/C,QAAM,KAAM,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAE3D,QAAM,WAAW,MAAM;AAAA,IACrB;AAAA,IACA;AAAA,IACA;AAAA,MACE,UAAU,KAAK;AAAA,MACf,gBAAiB,KAAmC,SAAS;AAAA,MAC7D,QAAQ,KAAK;AAAA,MACb,WAAW;AAAA,IACb;AAAA,IACA,EAAE,SAAS,EAAE,WAAW,OAAO,EAAE;AAAA,IACjC,EAAE,UAAU,KAAK,UAAoB,gBAAiB,KAAmC,SAAS,KAAK;AAAA,EACzG;AAKA,MAAI,kBAAiD;AACrD,MAAI;AACF,sBAAkB,UAAU,QAAQ,wBAAwB;AAAA,EAC9D,QAAQ;AACN,sBAAkB;AAAA,EACpB;AAEA,SAAO,aAAa,KAAK;AAAA,IACvB,OAAQ,SAAoC;AAAA,MAAI,CAAC,YAC/C,UAAU,SAAS,eA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,gBAAQ;",
6
6
  "names": []
7
7
  }
@@ -1,11 +1,13 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { z } from "zod";
3
3
  import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
4
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
4
5
  import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
6
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
6
7
  import { CommunicationChannel } from "../../../../../data/entities.js";
7
8
  import { ChannelAccessDeniedError, assertCanManageChannel } from "../../../../../lib/access-control.js";
8
9
  import { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from "../../../../../lib/queue.js";
10
+ import { isHubPolledChannel } from "../../../../../lib/polling-eligibility.js";
9
11
  import { validateRouteMutationGuard } from "../../../../../lib/route-mutation-guard.js";
10
12
  const metadata = {
11
13
  path: "/communication_channels/channels/[id]/poll-now",
@@ -84,6 +86,17 @@ async function POST(req, context) {
84
86
  { status: 409 }
85
87
  );
86
88
  }
89
+ if (!isHubPolledChannel(channel.capabilities)) {
90
+ const fallback = "Channel is push-driven \u2014 polling does not apply. Inbound messages arrive through the provider push connection.";
91
+ let message = fallback;
92
+ try {
93
+ const { translate } = await resolveTranslations();
94
+ message = translate("communication_channels.errors.pollNowPushDriven", fallback);
95
+ } catch {
96
+ message = fallback;
97
+ }
98
+ return NextResponse.json({ error: message }, { status: 409 });
99
+ }
87
100
  const guard = await validateRouteMutationGuard({
88
101
  container,
89
102
  req,
@@ -128,7 +141,7 @@ const openApi = {
128
141
  { status: 400, description: "Invalid channel id" },
129
142
  { status: 401, description: "Unauthorized" },
130
143
  { status: 404, description: "Channel not found" },
131
- { status: 409, description: "Channel disabled or not connected" }
144
+ { status: 409, description: "Channel disabled, not connected, or push-driven (never polled)" }
132
145
  ]
133
146
  }
134
147
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../../src/modules/communication_channels/api/post/channels/%5Bid%5D/poll-now/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../../../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanManageChannel } from '../../../../../lib/access-control'\nimport { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from '../../../../../lib/queue'\nimport type { PollChannelJobPayload } from '../../../../../workers/poll-channel'\nimport { validateRouteMutationGuard } from '../../../../../lib/route-mutation-guard'\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/channels/[id]/poll-now',\n POST: {\n // Owner self-service: a user may sync their OWN mailbox (gated by\n // `connect_user_channel`). Polling a shared/tenant-wide channel still\n // requires `manage` \u2014 enforced per channel type by `assertCanManageChannel`.\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\n/**\n * Manual poll trigger \u2014 enqueues a single `poll-channel` job immediately so\n * the operator (or a demo) doesn't have to wait for the 60-second scheduler\n * tick + per-channel `poll_interval_seconds` window.\n *\n * Per-user access guard mirrors the rest of the channels API: only the channel\n * owner (or an admin with `communication_channels.admin`) can trigger a poll.\n */\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { id } = await context.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Invalid channel id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n const organizationId = (auth as { orgId?: string | null }).orgId ?? null\n const dscope = { tenantId: auth.tenantId as string, organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id,\n tenantId: auth.tenantId as string,\n organizationId,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n // Load features via RBAC so admin bypass is honoured.\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(auth.sub as string, {\n tenantId: auth.tenantId as string,\n organizationId,\n })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanManageChannel(\n { userId: (channel as { userId?: string | null }).userId },\n auth.sub as string,\n userFeatures,\n 'communication_channels.manage',\n )\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n throw err\n }\n\n if (!channel.isActive) {\n return NextResponse.json({ error: 'Channel is disabled' }, { status: 409 })\n }\n // Allow manual poll-now from 'connected' AND 'error' states. The operator's\n // intent in clicking \"Poll now\" while the channel is in error is exactly\n // \"retry the connection right now\"; a successful poll auto-resets status\n // back to 'connected' (see poll-channel.ts).\n // Block only the explicitly-broken lifecycle states.\n if (channel.status === 'requires_reauth') {\n return NextResponse.json(\n { error: 'Channel needs reauthentication \u2014 reconnect from /backend/profile/communication-channels' },\n { status: 409 },\n )\n }\n if (channel.status === 'disconnected') {\n return NextResponse.json(\n { error: 'Channel is disconnected \u2014 reconnect to resume polling' },\n { status: 409 },\n )\n }\n\n const guard = await validateRouteMutationGuard({\n container,\n req,\n auth,\n input: {\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n operation: 'custom',\n mutationPayload: { action: 'poll-now' },\n },\n })\n if ('response' in guard) return guard.response\n\n const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.poll)\n const payload: PollChannelJobPayload = {\n channelId: channel.id,\n scope: {\n tenantId: auth.tenantId as string,\n organizationId: organizationId ?? null,\n },\n attempt: 1,\n }\n await queue.enqueue(payload as unknown as Record<string, unknown>)\n await guard.afterSuccess()\n\n return NextResponse.json(\n {\n ok: true,\n channelId: channel.id,\n queued: true,\n message: 'Poll queued \u2014 new messages will appear after the worker runs.',\n },\n { status: 202 },\n )\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n POST: {\n summary: 'Manually trigger a poll cycle for a channel (demo / operator override)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 202, description: 'Poll job enqueued' },\n { status: 400, description: 'Invalid channel id' },\n { status: 401, description: 'Unauthorized' },\n { status: 404, description: 'Channel not found' },\n { status: 409, description: 'Channel disabled or not connected' },\n ],\n },\n },\n}\nexport default POST\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAEvC,SAAS,6BAA6B;AACtC,SAAS,4BAA4B;AACrC,SAAS,0BAA0B,8BAA8B;AACjE,SAAS,+BAA+B,qCAAqC;AAE7E,SAAS,kCAAkC;AASpC,MAAM,WAAW;AAAA,EACtB,MAAM;AAAA,EACN,MAAM;AAAA;AAAA;AAAA;AAAA,IAIJ,aAAa;AAAA,IACb,iBAAiB,CAAC,6CAA6C;AAAA,EACjE;AACF;AAcA,eAAsB,KAAK,KAAc,SAA0C;AACjF,QAAM,EAAE,GAAG,IAAI,MAAM,QAAQ;AAC7B,MAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,SAAS;AAC5C,WAAO,aAAa,KAAK,EAAE,OAAO,qBAAqB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC3E;AAEA,QAAM,OAAO,MAAM,mBAAmB,G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,qBAAqB;AAAA,QACjD,EAAE,QAAQ,KAAK,aAAa,eAAe;AAAA,QAC3C,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,QAChD,EAAE,QAAQ,KAAK,aAAa,oCAAoC;AAAA,MAClE;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAO,gBAAQ;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CommunicationChannel } from '../../../../../data/entities'\nimport { ChannelAccessDeniedError, assertCanManageChannel } from '../../../../../lib/access-control'\nimport { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from '../../../../../lib/queue'\nimport { isHubPolledChannel } from '../../../../../lib/polling-eligibility'\nimport type { PollChannelJobPayload } from '../../../../../workers/poll-channel'\nimport { validateRouteMutationGuard } from '../../../../../lib/route-mutation-guard'\n\ntype RbacServiceLike = {\n loadAcl: (\n userId: string,\n scope: { tenantId: string | null; organizationId: string | null },\n ) => Promise<{ isSuperAdmin: boolean; features: string[]; organizations: string[] | null }>\n}\n\nexport const metadata = {\n path: '/communication_channels/channels/[id]/poll-now',\n POST: {\n // Owner self-service: a user may sync their OWN mailbox (gated by\n // `connect_user_channel`). Polling a shared/tenant-wide channel still\n // requires `manage` \u2014 enforced per channel type by `assertCanManageChannel`.\n requireAuth: true,\n requireFeatures: ['communication_channels.connect_user_channel'],\n },\n}\n\ntype RouteContext = {\n params: Promise<{ id: string }> | { id: string }\n}\n\n/**\n * Manual poll trigger \u2014 enqueues a single `poll-channel` job immediately so\n * the operator (or a demo) doesn't have to wait for the 60-second scheduler\n * tick + per-channel `poll_interval_seconds` window.\n *\n * Per-user access guard mirrors the rest of the channels API: only the channel\n * owner (or an admin with `communication_channels.admin`) can trigger a poll.\n */\nexport async function POST(req: Request, context: RouteContext): Promise<Response> {\n const { id } = await context.params\n if (!z.string().uuid().safeParse(id).success) {\n return NextResponse.json({ error: 'Invalid channel id' }, { status: 400 })\n }\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.sub || !auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const container = await createRequestContainer()\n const em = (container.resolve('em') as EntityManager).fork()\n const organizationId = (auth as { orgId?: string | null }).orgId ?? null\n const dscope = { tenantId: auth.tenantId as string, organizationId }\n\n const channel = await findOneWithDecryption(\n em,\n CommunicationChannel,\n {\n id,\n tenantId: auth.tenantId as string,\n organizationId,\n deletedAt: null,\n },\n undefined,\n dscope,\n )\n if (!channel) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n\n // Load features via RBAC so admin bypass is honoured.\n let userFeatures: string[] = []\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike\n const acl = await rbac.loadAcl(auth.sub as string, {\n tenantId: auth.tenantId as string,\n organizationId,\n })\n userFeatures = acl?.isSuperAdmin ? ['*'] : Array.isArray(acl?.features) ? acl.features : []\n } catch {\n userFeatures = []\n }\n try {\n assertCanManageChannel(\n { userId: (channel as { userId?: string | null }).userId },\n auth.sub as string,\n userFeatures,\n 'communication_channels.manage',\n )\n } catch (err) {\n if (err instanceof ChannelAccessDeniedError) {\n return NextResponse.json({ error: 'Channel not found' }, { status: 404 })\n }\n throw err\n }\n\n if (!channel.isActive) {\n return NextResponse.json({ error: 'Channel is disabled' }, { status: 409 })\n }\n // Allow manual poll-now from 'connected' AND 'error' states. The operator's\n // intent in clicking \"Poll now\" while the channel is in error is exactly\n // \"retry the connection right now\"; a successful poll auto-resets status\n // back to 'connected' (see poll-channel.ts).\n // Block only the explicitly-broken lifecycle states.\n if (channel.status === 'requires_reauth') {\n return NextResponse.json(\n { error: 'Channel needs reauthentication \u2014 reconnect from /backend/profile/communication-channels' },\n { status: 409 },\n )\n }\n if (channel.status === 'disconnected') {\n return NextResponse.json(\n { error: 'Channel is disconnected \u2014 reconnect to resume polling' },\n { status: 409 },\n )\n }\n // The poll worker returns immediately for a channel whose adapter declares\n // real-time push, so enqueueing a job here would answer 202 for work that can\n // never run and the UI would promise messages that never arrive (#4980).\n if (!isHubPolledChannel(channel.capabilities)) {\n // The page flashes this string verbatim, so it is operator-facing. Localize\n // it when a request locale is resolvable and fall back to English rather\n // than failing the request if the i18n registry is uninitialized \u2014 the same\n // defensive shape the module's command interceptors use.\n const fallback =\n 'Channel is push-driven \u2014 polling does not apply. Inbound messages arrive through the provider push connection.'\n let message = fallback\n try {\n const { translate } = await resolveTranslations()\n message = translate('communication_channels.errors.pollNowPushDriven', fallback)\n } catch {\n message = fallback\n }\n return NextResponse.json({ error: message }, { status: 409 })\n }\n\n const guard = await validateRouteMutationGuard({\n container,\n req,\n auth,\n input: {\n resourceKind: 'communication_channels.channel',\n resourceId: channel.id,\n operation: 'custom',\n mutationPayload: { action: 'poll-now' },\n },\n })\n if ('response' in guard) return guard.response\n\n const queue = getCommunicationChannelsQueue(COMMUNICATION_CHANNELS_QUEUES.poll)\n const payload: PollChannelJobPayload = {\n channelId: channel.id,\n scope: {\n tenantId: auth.tenantId as string,\n organizationId: organizationId ?? null,\n },\n attempt: 1,\n }\n await queue.enqueue(payload as unknown as Record<string, unknown>)\n await guard.afterSuccess()\n\n return NextResponse.json(\n {\n ok: true,\n channelId: channel.id,\n queued: true,\n message: 'Poll queued \u2014 new messages will appear after the worker runs.',\n },\n { status: 202 },\n )\n}\n\nexport const openApi = {\n tags: ['CommunicationChannels'],\n methods: {\n POST: {\n summary: 'Manually trigger a poll cycle for a channel (demo / operator override)',\n tags: ['CommunicationChannels'],\n responses: [\n { status: 202, description: 'Poll job enqueued' },\n { status: 400, description: 'Invalid channel id' },\n { status: 401, description: 'Unauthorized' },\n { status: 404, description: 'Channel not found' },\n { status: 409, description: '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;",
6
6
  "names": []
7
7
  }
@@ -259,18 +259,25 @@ function ProfileCommunicationChannelsPage() {
259
259
  },
260
260
  {
261
261
  id: "pushStatus",
262
- header: t("communication_channels.push.status.active", "Push"),
262
+ // Its own key: sharing `push.status.active` made the header render
263
+ // "Push active" over a column whose rows say "Polling only" (#4980).
264
+ header: t("communication_channels.profile.columns.push", "Push"),
263
265
  cell: ({ row }) => {
264
- const supportsPush = row.original.providerKey === "gmail";
265
- if (!supportsPush) {
266
- return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("communication_channels.push.status.inactive", "Polling only") });
267
- }
268
266
  const ps = row.original.pushStatus;
267
+ const errorTitle = row.original.lastPushError?.message ?? void 0;
268
+ if (!row.original.supportsPushRegistration) {
269
+ if (!row.original.supportsRealtimePush) {
270
+ return /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("communication_channels.push.status.inactive", "Polling only") });
271
+ }
272
+ if (ps === "failed") {
273
+ return /* @__PURE__ */ jsx(Tag, { variant: "error", dot: true, title: errorTitle, children: t("communication_channels.push.status.pushDrivenFailed", "Push connection failed") });
274
+ }
275
+ return /* @__PURE__ */ jsx(Tag, { variant: "success", dot: true, children: t("communication_channels.push.status.pushDriven", "Push-driven") });
276
+ }
269
277
  if (ps === "active") {
270
278
  return /* @__PURE__ */ jsx(Tag, { variant: "success", dot: true, children: t("communication_channels.push.status.active", "Push active") });
271
279
  }
272
280
  if (ps === "failed") {
273
- const errorMsg = row.original.lastPushError?.message ?? null;
274
281
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
275
282
  /* @__PURE__ */ jsx(Tag, { variant: "error", dot: true, children: t("communication_channels.push.status.failed", "Push failed \u2014 using polling") }),
276
283
  /* @__PURE__ */ jsx(
@@ -281,14 +288,14 @@ function ProfileCommunicationChannelsPage() {
281
288
  size: "sm",
282
289
  onClick: () => void onRegisterPush(row.original.id),
283
290
  "aria-label": t("communication_channels.push.button.reregister", "Re-register push"),
284
- title: errorMsg ?? void 0,
291
+ title: errorTitle,
285
292
  children: t("communication_channels.push.button.reregister", "Re-register push")
286
293
  }
287
294
  )
288
295
  ] });
289
296
  }
290
297
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
291
- /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t("communication_channels.push.status.inactive", "Polling only") }),
298
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: row.original.supportsRealtimePush ? t("communication_channels.push.status.notRegistered", "Push not registered") : t("communication_channels.push.status.inactive", "Polling only") }),
292
299
  /* @__PURE__ */ jsx(
293
300
  Button,
294
301
  {
@@ -332,9 +339,14 @@ function ProfileCommunicationChannelsPage() {
332
339
  id: "pollNow",
333
340
  header: t("communication_channels.profile.columns.pollNow", "Sync"),
334
341
  cell: ({ row }) => {
335
- const pollable = row.original.isActive && (row.original.status === "connected" || row.original.status === "error");
342
+ const pushDriven = row.original.supportsRealtimePush;
343
+ const pollable = row.original.isActive && !pushDriven && (row.original.status === "connected" || row.original.status === "error");
336
344
  const label = row.original.status === "error" ? t("communication_channels.profile.actions.retryPoll", "Retry") : t("communication_channels.profile.actions.pollNow", "Poll now");
337
- return /* @__PURE__ */ jsx(
345
+ const disabledReason = pushDriven ? t(
346
+ "communication_channels.profile.actions.pollNowPushDriven",
347
+ "This channel is push-driven \u2014 inbound messages arrive over the provider connection, so polling does not apply."
348
+ ) : void 0;
349
+ const button = /* @__PURE__ */ jsx(
338
350
  Button,
339
351
  {
340
352
  type: "button",
@@ -342,10 +354,11 @@ function ProfileCommunicationChannelsPage() {
342
354
  size: "sm",
343
355
  onClick: () => void onPollNow(row.original.id),
344
356
  disabled: !pollable,
345
- "aria-label": label,
357
+ "aria-label": disabledReason ? `${label} \u2014 ${disabledReason}` : label,
346
358
  children: label
347
359
  }
348
360
  );
361
+ return disabledReason ? /* @__PURE__ */ jsx("span", { title: disabledReason, children: button }) : button;
349
362
  }
350
363
  },
351
364
  {
@@ -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 type { ColumnDef } from '@tanstack/react-table'\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 { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\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'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\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 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\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\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 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 cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onSetPrimary(row.original.id)}\n aria-label={t('communication_channels.profile.actions.setPrimary', 'Set as primary')}\n >\n {t('communication_channels.profile.actions.setPrimary', 'Set as primary')}\n </Button>\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 header: t('communication_channels.push.status.active', 'Push'),\n cell: ({ row }) => {\n const supportsPush = row.original.providerKey === 'gmail'\n if (!supportsPush) {\n return (\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n )\n }\n const ps = row.original.pushStatus\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 const errorMsg = row.original.lastPushError?.message ?? null\n return (\n <div className=\"flex items-center gap-2\">\n <Tag variant=\"error\" dot>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onRegisterPush(row.original.id)}\n aria-label={t('communication_channels.push.button.reregister', 'Re-register push')}\n title={errorMsg ?? undefined}\n >\n {t('communication_channels.push.button.reregister', 'Re-register push')}\n </Button>\n </div>\n )\n }\n // null or 'inactive' \u2014 provider supports push but not registered yet.\n return (\n <div className=\"flex items-center gap-2\">\n <span className=\"text-xs text-muted-foreground\">\n {t('communication_channels.push.status.inactive', 'Polling only')}\n </span>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onRegisterPush(row.original.id)}\n aria-label={t('communication_channels.push.button.reregister', 'Re-register push')}\n >\n {t('communication_channels.push.button.reregister', 'Re-register push')}\n </Button>\n </div>\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 id: 'importHistory',\n header: t('communication_channels.profile.columns.importHistory', 'History'),\n cell: ({ row }) => {\n const eligible =\n row.original.isActive &&\n row.original.status === 'connected' &&\n row.original.channelType === 'email'\n const label = t('communication_channels.profile.actions.importHistory', 'Import history')\n return (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setImportChannel(row.original)}\n disabled={!eligible}\n aria-label={label}\n >\n {label}\n </Button>\n )\n },\n },\n {\n id: 'pollNow',\n header: t('communication_channels.profile.columns.pollNow', 'Sync'),\n cell: ({ row }) => {\n // Allowed from 'connected' AND 'error' \u2014 the latter lets the user\n // recover a stuck channel without disconnecting + reconnecting.\n // 'requires_reauth' and 'disconnected' are owned by other flows.\n const pollable =\n row.original.isActive &&\n (row.original.status === 'connected' || row.original.status === 'error')\n const label =\n row.original.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now')\n return (\n <Button\n type=\"button\"\n variant={row.original.status === 'error' ? 'default' : 'outline'}\n size=\"sm\"\n onClick={() => void onPollNow(row.original.id)}\n disabled={!pollable}\n aria-label={label}\n >\n {label}\n </Button>\n )\n },\n },\n {\n id: 'disconnect',\n header: t('communication_channels.profile.columns.disconnect', 'Connection'),\n cell: ({ row }) => {\n const label = t('communication_channels.profile.actions.disconnect', 'Disconnect')\n return (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setDisconnectChannel(row.original)}\n aria-label={label}\n >\n {label}\n </Button>\n )\n },\n },\n ],\n [onSetPrimary, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex items-baseline justify-between\">\n <div>\n <h2 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h2>\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. */}\n <InjectionSpot\n spotId={extensionPoints.hosts.profileConnect.spotId}\n context={{ reload: () => setReloadKey((k) => k + 1) }}\n data={{}}\n />\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 extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Use one of the Connect buttons above to add a channel.',\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 </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 [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 > 365) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and 365 days.',\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > 5000) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and 5000 messages.',\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])\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={365}\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={5000}\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": ";AAmRU,cA8DI,YA9DJ;AAjRV,YAAY,WAAW;AACvB,SAAS,uBAAuB;AAEhC,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,qBAAqB;AAC9B,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AAoBrB,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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,QACA;AAAA,MACF,GACF;AAAA,OACF;AAAA,IAEC,UACC,oBAAC,OAAE,WAAU,uBAAuB,kBAAQ,sBAAsB,QAAQ,aAAY,IACpF;AAAA,IAEJ,qBAAC,gBACC;AAAA,0BAAC,UAAK,WAAU,yCACd,8BAAC,eAAY,MAAM,CAAC,UAAK,OAAO,GAAG,GACrC;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAAS,UAAU,YACjE,YAAE,oDAAoD,QAAQ,GACjE;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,qBAAoB,SAAS,MAAM,KAAK,cAAc,GAAG,UAAU,YAC9F,uBACG,EAAE,wDAAwD,qBAAgB,IAC1E,EAAE,qDAAqD,YAAY,GACzE;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 type { ColumnDef } from '@tanstack/react-table'\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 { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\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'\n\ntype ChannelRow = {\n id: string\n providerKey: string\n channelType: string\n displayName: string\n externalIdentifier: string | null\n isPrimary: boolean\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\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\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 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 cell: ({ row }) =>\n row.original.isPrimary ? (\n <Tag variant=\"success\" dot>\n {t('communication_channels.profile.primary', 'Primary')}\n </Tag>\n ) : (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onSetPrimary(row.original.id)}\n aria-label={t('communication_channels.profile.actions.setPrimary', 'Set as primary')}\n >\n {t('communication_channels.profile.actions.setPrimary', 'Set as primary')}\n </Button>\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 return (\n <Tag variant=\"success\" dot>\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 <div className=\"flex items-center gap-2\">\n <Tag variant=\"error\" dot>\n {t('communication_channels.push.status.failed', 'Push failed \u2014 using polling')}\n </Tag>\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onRegisterPush(row.original.id)}\n aria-label={t('communication_channels.push.button.reregister', 'Re-register push')}\n title={errorTitle}\n >\n {t('communication_channels.push.button.reregister', 'Re-register push')}\n </Button>\n </div>\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 <div className=\"flex items-center gap-2\">\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 <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => void onRegisterPush(row.original.id)}\n aria-label={t('communication_channels.push.button.reregister', 'Re-register push')}\n >\n {t('communication_channels.push.button.reregister', 'Re-register push')}\n </Button>\n </div>\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 id: 'importHistory',\n header: t('communication_channels.profile.columns.importHistory', 'History'),\n cell: ({ row }) => {\n const eligible =\n row.original.isActive &&\n row.original.status === 'connected' &&\n row.original.channelType === 'email'\n const label = t('communication_channels.profile.actions.importHistory', 'Import history')\n return (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setImportChannel(row.original)}\n disabled={!eligible}\n aria-label={label}\n >\n {label}\n </Button>\n )\n },\n },\n {\n id: 'pollNow',\n header: t('communication_channels.profile.columns.pollNow', 'Sync'),\n cell: ({ row }) => {\n // Allowed from 'connected' AND 'error' \u2014 the latter lets the user\n // recover a stuck channel without disconnecting + reconnecting.\n // 'requires_reauth' and 'disconnected' are owned by other flows.\n // A push-driven channel is never polled by the worker, so offering the\n // action at all would promise a sync that cannot happen (#4980).\n const pushDriven = row.original.supportsRealtimePush\n const pollable =\n row.original.isActive &&\n !pushDriven &&\n (row.original.status === 'connected' || row.original.status === 'error')\n const label =\n row.original.status === 'error'\n ? t('communication_channels.profile.actions.retryPoll', 'Retry')\n : t('communication_channels.profile.actions.pollNow', 'Poll now')\n const disabledReason = pushDriven\n ? 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 : undefined\n const button = (\n <Button\n type=\"button\"\n variant={row.original.status === 'error' ? 'default' : 'outline'}\n size=\"sm\"\n onClick={() => void onPollNow(row.original.id)}\n disabled={!pollable}\n aria-label={disabledReason ? `${label} \u2014 ${disabledReason}` : label}\n >\n {label}\n </Button>\n )\n // A disabled button does not receive hover events in every browser, so\n // the explanation lives on a wrapper the pointer can still reach.\n return disabledReason ? <span title={disabledReason}>{button}</span> : button\n },\n },\n {\n id: 'disconnect',\n header: t('communication_channels.profile.columns.disconnect', 'Connection'),\n cell: ({ row }) => {\n const label = t('communication_channels.profile.actions.disconnect', 'Disconnect')\n return (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => setDisconnectChannel(row.original)}\n aria-label={label}\n >\n {label}\n </Button>\n )\n },\n },\n ],\n [onSetPrimary, onPollNow, onRegisterPush, t],\n )\n\n return (\n <Page>\n <PageBody>\n <header className=\"mb-4 flex items-baseline justify-between\">\n <div>\n <h2 className=\"text-2xl font-semibold\">\n {t('communication_channels.profile.title', 'My communication channels')}\n </h2>\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. */}\n <InjectionSpot\n spotId={extensionPoints.hosts.profileConnect.spotId}\n context={{ reload: () => setReloadKey((k) => k + 1) }}\n data={{}}\n />\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 extensionTableId={extensionPoints.hosts.profileChannelsTable.tableId}\n columns={columns}\n data={rows}\n isLoading={isLoading}\n error={errorMessage}\n emptyState={t(\n 'communication_channels.profile.empty',\n 'You have no connected channels yet. Use one of the Connect buttons above to add a channel.',\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 </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 [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 > 365) {\n errors.sinceDays = t(\n 'communication_channels.profile.importHistory.errors.sinceDays',\n 'Choose a number between 1 and 365 days.',\n )\n }\n if (!Number.isFinite(maxNum) || maxNum < 1 || maxNum > 5000) {\n errors.maxMessages = t(\n 'communication_channels.profile.importHistory.errors.maxMessages',\n 'Choose a number between 1 and 5000 messages.',\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])\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={365}\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={5000}\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": ";AA0RU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OACF;AAAA,IAEC,UACC,oBAAC,OAAE,WAAU,uBAAuB,kBAAQ,sBAAsB,QAAQ,aAAY,IACpF;AAAA,IAEJ,qBAAC,gBACC;AAAA,0BAAC,UAAK,WAAU,yCACd,8BAAC,eAAY,MAAM,CAAC,UAAK,OAAO,GAAG,GACrC;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,WAAU,SAAS,SAAS,UAAU,YACjE,YAAE,oDAAoD,QAAQ,GACjE;AAAA,MACA,oBAAC,UAAO,MAAK,UAAS,SAAQ,qBAAoB,SAAS,MAAM,KAAK,cAAc,GAAG,UAAU,YAC9F,uBACG,EAAE,wDAAwD,qBAAgB,IAC1E,EAAE,qDAAqD,YAAY,GACzE;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;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,8 @@
1
+ function isHubPolledChannel(capabilities) {
2
+ if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) return false;
3
+ return capabilities.realtimePush === false;
4
+ }
5
+ export {
6
+ isHubPolledChannel
7
+ };
8
+ //# sourceMappingURL=polling-eligibility.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/communication_channels/lib/polling-eligibility.ts"],
4
+ "sourcesContent": ["/**\n * Single source of truth for \"does the hub poll this channel?\".\n *\n * `ChannelCapabilities.realtimePush` is optional and defaults to `true` for\n * back-compat (chat providers predating the flag omit it), so only an explicit\n * `false` opts a channel into hub-managed polling. The poll worker, the manual\n * `poll-now` route and the profile grid all derive their behaviour from this\n * predicate, so the UI can never label a channel the opposite of what the worker\n * actually does (#4980).\n */\nexport function isHubPolledChannel(capabilities: unknown): boolean {\n if (!capabilities || typeof capabilities !== 'object' || Array.isArray(capabilities)) return false\n return (capabilities as { realtimePush?: unknown }).realtimePush === false\n}\n"],
5
+ "mappings": "AAUO,SAAS,mBAAmB,cAAgC;AACjE,MAAI,CAAC,gBAAgB,OAAO,iBAAiB,YAAY,MAAM,QAAQ,YAAY,EAAG,QAAO;AAC7F,SAAQ,aAA4C,iBAAiB;AACvE;",
6
+ "names": []
7
+ }
@@ -5,6 +5,7 @@ import {
5
5
  } from "../commands/ingest-inbound-message.js";
6
6
  import { COMMUNICATION_CHANNELS_QUEUES, getCommunicationChannelsQueue } from "../lib/queue.js";
7
7
  import { preservePushState } from "../lib/push-state.js";
8
+ import { isHubPolledChannel } from "../lib/polling-eligibility.js";
8
9
  import { writeIngestDeadLetter } from "../lib/dead-letter.js";
9
10
  import { classifyOutboundError, computeBackoffMs, isReauthError } from "../lib/error-classification.js";
10
11
  import { refreshCredentialsIfNeeded } from "../lib/credential-refresh.js";
@@ -45,8 +46,7 @@ async function handle(job, ctx) {
45
46
  logger.warn("no adapter for provider", { providerKey: channel.providerKey, channelId });
46
47
  return;
47
48
  }
48
- const capabilities = channel.capabilities ?? null;
49
- if (capabilities?.realtimePush !== false) {
49
+ if (!isHubPolledChannel(channel.capabilities)) {
50
50
  return;
51
51
  }
52
52
  if (typeof adapter.fetchHistory !== "function") {